context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Web.UI.HtmlControls;
using System.Text;
using System.Quality;
using System.Collections.Generic;
using System.Patterns.ReleaseManagement;
namespace System.Web.UI.Integrate
{
using UIClientScript = ClientScript;
/// <summary>
/// ShareThis
/// </summary>
public class ShareThis : HtmlContainerControl
{
private static Type s_type = typeof(ShareThis);
private string _scriptBody;
public ShareThis()
: base()
{
DeploymentTarget = DeploymentEnvironment.Production;
Include = new ShareThisInclude();
Inject = true;
}
public DeploymentEnvironment DeploymentTarget { get; set; }
public string AttachToButtonId { get; set; }
public bool UseClientScript { get; set; }
public ShareThisInclude Include { get; set; }
public ShareThisObject Object { get; set; }
public bool Inject { get; set; }
[Microsoft.Practices.Unity.Dependency]
[ServiceDependency]
public IClientScriptManager ClientScriptManager { get; set; }
/// <summary>
/// Gets or sets the button text.
/// </summary>
/// <value>The button text.</value>
public string ButtonText
{
get { return Include.ButtonText; }
set { Include.ButtonText = value; }
}
/// <summary>
/// Gets or sets the color of the header background.
/// </summary>
/// <value>The color of the header background.</value>
public string HeaderBackgroundColor
{
get { return Include.HeaderBackgroundColor; }
set { Include.HeaderBackgroundColor = value; }
}
/// <summary>
/// Gets or sets the color of the header foreground.
/// </summary>
/// <value>The color of the header foreground.</value>
public string HeaderForegroundColor
{
get { return Include.HeaderForegroundColor; }
set { Include.HeaderForegroundColor = value; }
}
/// <summary>
/// Gets or sets the header title.
/// </summary>
/// <value>The header title.</value>
public string HeaderTitle
{
get { return Include.HeaderTitle; }
set { Include.HeaderTitle = value; }
}
/// <summary>
/// Gets or sets the post services.
/// </summary>
/// <value>The post services.</value>
public string PostServices
{
get { return Include.PostServices; }
set { Include.PostServices = value; }
}
/// <summary>
/// Gets or sets the publisher.
/// </summary>
/// <value>The publisher.</value>
public string Publisher
{
get { return Include.Publisher; }
set { Include.Publisher = value; }
}
/// <summary>
/// Gets or sets the send services.
/// </summary>
/// <value>The send services.</value>
public string SendServices
{
get { return Include.SendServices; }
set { Include.SendServices = value; }
}
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public string Type
{
get { return Include.Type; }
set { Include.Type = value; }
}
protected override void OnPreRender(EventArgs e)
{
if (Inject)
ServiceLocator.Inject(this);
if (Include == null)
throw new ArgumentNullException("Include");
base.OnPreRender(e);
// include
if (ClientScriptManager != null)
ClientScriptManager.EnsureItem<HtmlHead>(ID, () => new IncludeClientScriptItem(GetIncludeUriString()));
}
protected override void Render(HtmlTextWriter w)
{
if (Object == null)
throw new ArgumentNullException("Object");
// object
_scriptBody = GetObjectString();
if (ClientScriptManager != null)
{
ClientScriptManager.AddRange(_scriptBody);
_scriptBody = null;
}
//if (EnvironmentEx.DeploymentEnvironment == DeploymentTarget)
//{
if (!string.IsNullOrEmpty(_scriptBody))
{
w.Write(@"<script type=""text/javascript"">
// <![CDATA[
");
w.Write(_scriptBody);
w.Write(@"
// ]]>
</script>");
}
//}
//else
// w.WriteLine("<!-- Share This -->");
}
private string GetObjectString()
{
var objectLiteral = (Object as ShareThisObjectLiteral);
if (objectLiteral != null)
return objectLiteral.Literal;
//
var b = new StringBuilder("SHARETHIS.addEntry(");
var obj = Object;
bool hasButton = string.IsNullOrEmpty(AttachToButtonId);
b.Append(SerializeObjectToJsonString(obj));
b.Append(",");
b.Append(SerializeObjectMetaToJsonString((obj.Meta == null ? ShareThisObjectMeta.Default : obj.Meta), hasButton));
b.Append(")");
//
b.Append(!hasButton ? ".attachButton(document.getElementById('" + AttachToButtonId + "'));" : ";");
return b.ToString();
}
private string GetIncludeUriString()
{
var includeLiteral = (Include as ShareThisIncludeLiteral);
if (includeLiteral != null)
{
var value = includeLiteral.Literal;
if (value.IndexOf("&button=", StringComparison.OrdinalIgnoreCase) == -1)
value += "&button=false";
return value;
}
//
var include = Include;
if (string.IsNullOrEmpty(include.Type))
throw new InvalidOperationException("'Type' cannot be null");
return SerializeIncludeToUriString(include);
}
#region Serializers
public static string SerializeIncludeToUriString(ShareThisInclude include)
{
// todo: build urlserialize here
var b = new StringBuilder();
b.Append(string.Format("http://w.sharethis.com/button/sharethis.js#type={0}", Uri.EscapeDataString(include.Type)));
if (!string.IsNullOrEmpty(include.Publisher))
b.Append("&publisher=" + Uri.EscapeDataString(include.Publisher));
if (!string.IsNullOrEmpty(include.ButtonText))
b.Append("&buttonText=" + Uri.EscapeDataString(include.ButtonText));
if (!string.IsNullOrEmpty(include.HeaderBackgroundColor))
b.Append("&headerbg=" + Uri.EscapeDataString(include.HeaderBackgroundColor));
if (!string.IsNullOrEmpty(include.HeaderForegroundColor))
b.Append("&headerfg=" + Uri.EscapeDataString(include.HeaderForegroundColor));
if (!string.IsNullOrEmpty(include.HeaderTitle))
b.Append("&headerTitle=" + Uri.EscapeDataString(include.HeaderTitle));
if (!string.IsNullOrEmpty(include.PostServices))
b.Append("&post_services=" + Uri.EscapeDataString(include.PostServices));
if (!string.IsNullOrEmpty(include.SendServices))
b.Append("&send_services=" + Uri.EscapeDataString(include.SendServices));
//foreach (var keyValue in _javascriptAttribs)
// b.Append("&" + keyValue.Key + "=" + Uri.EscapeDataString(keyValue.Value));
b.Append("&button=false");
return b.ToString();
}
public static string SerializeObjectToJsonString(ShareThisObject obj)
{
var b = new StringBuilder("{");
var objectPropertyList = new List<string>();
if (!string.IsNullOrEmpty(obj.Author))
objectPropertyList.Add("author: " + UIClientScript.EncodeText(obj.Author));
if (!string.IsNullOrEmpty(obj.Category))
objectPropertyList.Add("category: " + UIClientScript.EncodeText(obj.Category));
if (!string.IsNullOrEmpty(obj.Content))
objectPropertyList.Add("content: " + UIClientScript.EncodeText(obj.Content));
if (!string.IsNullOrEmpty(obj.Icon))
objectPropertyList.Add("icon: " + UIClientScript.EncodeText(obj.Icon));
if (!string.IsNullOrEmpty(obj.Published))
objectPropertyList.Add("published: " + UIClientScript.EncodeText(obj.Published));
if (!string.IsNullOrEmpty(obj.Summary))
objectPropertyList.Add("summary: " + UIClientScript.EncodeText(obj.Summary));
if (!string.IsNullOrEmpty(obj.Title))
objectPropertyList.Add("title: " + UIClientScript.EncodeText(obj.Title));
if (!string.IsNullOrEmpty(obj.Updated))
objectPropertyList.Add("updated: " + UIClientScript.EncodeText(obj.Updated));
if (!string.IsNullOrEmpty(obj.Url))
objectPropertyList.Add("url: " + UIClientScript.EncodeText(obj.Url));
//
b.Append(string.Join(",", objectPropertyList.ToArray()));
b.Append("}");
return b.ToString();
}
public static string SerializeObjectMetaToJsonString(ShareThisObjectMeta objMeta, bool hasButton)
{
var b = new StringBuilder("{");
b.Append("button: " + (hasButton ? "true" : "false"));
b.AppendFormat(", embeds: {0}", UIClientScript.EncodeBool(objMeta.Embeds));
if (objMeta.OffsetLeft != 0)
b.AppendFormat(", offsetLeft: {0}", UIClientScript.EncodeInt32(objMeta.OffsetLeft));
if (objMeta.OffsetTop != 0)
b.AppendFormat(", offsetTop: {0}", UIClientScript.EncodeInt32(objMeta.OffsetTop));
if (!string.IsNullOrEmpty(objMeta.OnClientClick))
b.AppendFormat(", onclick: {0}", objMeta.OnClientClick);
b.AppendFormat(", popup: {0}", UIClientScript.EncodeBool(objMeta.Popup));
b.Append("}");
return b.ToString();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using org.apache.zookeeper;
using org.apache.zookeeper.data;
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// A Membership Table implementation using Apache Zookeeper 3.4.6 https://zookeeper.apache.org/doc/r3.4.6/
/// </summary>
/// <remarks>
/// A brief overview of ZK features used: The data is represented by a tree of nodes (similar to a file system).
/// Every node is addressed by a path and can hold data as a byte array and has a version. When a node is created,
/// its version is 0. Upon updates, the version is atomically incremented. An update can also be conditional on an
/// expected current version. A transaction can hold several operations, which succeed or fail atomically.
/// when creating a zookeeper client, one can set a base path where all operations are relative to.
///
/// In this implementation:
/// Every Orleans deployment has a node /UniqueDeploymentId
/// Every Silo's state is saved in /UniqueDeploymentId/IP:Port@Gen
/// Every Silo's IAmAlive is saved in /UniqueDeploymentId/IP:Port@Gen/IAmAlive
/// IAmAlive is saved in a separate node because its updates are unconditional.
///
/// a node's ZK version is its ETag:
/// the table version is the version of /UniqueDeploymentId
/// the silo entry version is the version of /UniqueDeploymentId/IP:Port@Gen
/// </remarks>
public class ZooKeeperBasedMembershipTable : IMembershipTable, IGatewayListProvider
{
private Logger Logger;
private const int ZOOKEEPER_CONNECTION_TIMEOUT = 2000;
private ZooKeeperWatcher watcher;
/// <summary>
/// The deployment connection string. for eg. "192.168.1.1,192.168.1.2/DeploymentId"
/// </summary>
private string deploymentConnectionString;
/// <summary>
/// the node name for this deployment. for eg. /DeploymentId
/// </summary>
private string deploymentPath;
/// <summary>
/// The root connection string. for eg. "192.168.1.1,192.168.1.2"
/// </summary>
private string rootConnectionString;
private TimeSpan maxStaleness;
/// <summary>
/// Initializes the ZooKeeper based gateway provider
/// </summary>
/// <param name="config">The given client configuration.</param>
/// <param name="logger">The logger to be used by this instance</param>
public Task InitializeGatewayListProvider(ClientConfiguration config, Logger logger)
{
InitConfig(logger,config.DataConnectionString, config.DeploymentId);
maxStaleness = config.GatewayListRefreshPeriod;
return TaskDone.Done;
}
/// <summary>
/// Initializes the ZooKeeper based membership table.
/// </summary>
/// <param name="config">The configuration for this instance.</param>
/// <param name="tryInitPath">if set to true, we'll try to create a node named "/DeploymentId"</param>
/// <param name="logger">The logger to be used by this instance</param>
/// <returns></returns>
public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitPath, Logger logger)
{
InitConfig(logger, config.DataConnectionString, config.DeploymentId);
// even if I am not the one who created the path,
// try to insert an initial path if it is not already there,
// so we always have the path, before this silo starts working.
// note that when a zookeeper connection adds /DeploymentId to the connection string, the nodes are relative
await UsingZookeeper(rootConnectionString, async zk =>
{
try
{
await zk.createAsync(deploymentPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
await zk.sync(deploymentPath);
//if we got here we know that we've just created the deployment path with version=0
logger.Info("Created new deployment path: " + deploymentPath);
}
catch (KeeperException.NodeExistsException)
{
logger.Verbose("Deployment path already exists: " + deploymentPath);
}
});
}
private void InitConfig(Logger logger, string dataConnectionString, string deploymentId)
{
watcher = new ZooKeeperWatcher(logger);
Logger = logger;
deploymentPath = "/" + deploymentId;
deploymentConnectionString = dataConnectionString + deploymentPath;
rootConnectionString = dataConnectionString;
}
/// <summary>
/// Atomically reads the Membership Table information about a given silo.
/// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the
/// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically.
/// </summary>
/// <param name="siloAddress">The address of the silo whose membership information needs to be read.</param>
/// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and
/// TableVersion, read atomically.</returns>
public Task<MembershipTableData> ReadRow(SiloAddress siloAddress)
{
return UsingZookeeper(async zk =>
{
var getRowTask = GetRow(zk, siloAddress);
var getTableNodeTask = zk.getDataAsync("/");//get the current table version
List<Tuple<MembershipEntry, string>> rows = new List<Tuple<MembershipEntry, string>>(1);
try
{
await Task.WhenAll(getRowTask, getTableNodeTask);
rows.Add(await getRowTask);
}
catch (KeeperException.NoNodeException)
{
//that's ok because orleans expects an empty list in case of a missing row
}
var tableVersion = ConvertToTableVersion((await getTableNodeTask).Stat);
return new MembershipTableData(rows, tableVersion);
}, true);
}
/// <summary>
/// Atomically reads the full content of the Membership Table.
/// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the
/// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically.
/// </summary>
/// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and
/// TableVersion, all read atomically.</returns>
public Task<MembershipTableData> ReadAll()
{
return UsingZookeeper(async zk =>
{
var childrenResult = await zk.getChildrenAsync("/");//get all the child nodes (without the data)
var childrenTasks = //get the data from each child node
childrenResult.Children.Select(child => GetRow(zk, SiloAddress.FromParsableString(child))).ToList();
var childrenTaskResults = await Task.WhenAll(childrenTasks);
var tableVersion = ConvertToTableVersion(childrenResult.Stat);//this is the current table version
return new MembershipTableData(childrenTaskResults.ToList(), tableVersion);
}, true);
}
/// <summary>
/// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) New MembershipEntry will be added to the table.
/// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo already exist in the table
/// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be inserted.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the insert operation succeeded and false otherwise.</returns>
public Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
string rowPath = ConvertToRowPath(entry.SiloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
byte[] newRowData = Serialize(entry);
byte[] newRowIAmAliveData = Serialize(entry.IAmAliveTime);
int expectedTableVersion = int.Parse(tableVersion.VersionEtag, CultureInfo.InvariantCulture);
return TryTransaction(t => t
.setData("/", null, expectedTableVersion)//increments the version of node "/"
.create(rowPath, newRowData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
.create(rowIAmAlivePath, newRowIAmAliveData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
}
/// <summary>
/// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substitued by the new entry)
/// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo does not exist in the table
/// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag.
/// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be updated.</param>
/// <param name="etag">The etag for the given MembershipEntry.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the update operation succeeded and false otherwise.</returns>
public Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
string rowPath = ConvertToRowPath(entry.SiloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
var newRowData = Serialize(entry);
var newRowIAmAliveData = Serialize(entry.IAmAliveTime);
int expectedTableVersion = int.Parse(tableVersion.VersionEtag, CultureInfo.InvariantCulture);
int expectedRowVersion = int.Parse(etag, CultureInfo.InvariantCulture);
return TryTransaction(t => t
.setData("/", null, expectedTableVersion)//increments the version of node "/"
.setData(rowPath, newRowData, expectedRowVersion)//increments the version of node "/IP:Port@Gen"
.setData(rowIAmAlivePath, newRowIAmAliveData));
}
/// <summary>
/// Updates the IAmAlive part (column) of the MembershipEntry for this silo.
/// This operation should only update the IAmAlive collumn and not change other columns.
/// This operation is a "dirty write" or "in place update" and is performed without etag validation.
/// With regards to eTags update:
/// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write").
/// With regards to TableVersion:
/// this operation should not change the TableVersion of the table. It should leave it untouched.
/// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability.
/// </summary>
/// <param name="entry">The target MembershipEntry tp update</param>
/// <returns>Task representing the successful execution of this operation. </returns>
public Task UpdateIAmAlive(MembershipEntry entry)
{
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
byte[] newRowIAmAliveData = Serialize(entry.IAmAliveTime);
//update the data for IAmAlive unconditionally
return UsingZookeeper(zk => zk.setDataAsync(rowIAmAlivePath, newRowIAmAliveData));
}
/// <summary>
/// Returns the list of gateways (silos) that can be used by a client to connect to Orleans cluster.
/// The Uri is in the form of: "gwy.tcp://IP:port/Generation". See Utils.ToGatewayUri and Utils.ToSiloAddress for more details about Uri format.
/// </summary>
public async Task<IList<Uri>> GetGateways()
{
var membershipTableData = await ReadAll();
return membershipTableData.Members.Select(e => e.Item1).
Where(m => m.Status == SiloStatus.Active && m.ProxyPort != 0).
Select(m =>
{
m.SiloAddress.Endpoint.Port = m.ProxyPort;
return m.SiloAddress.ToGatewayUri();
}).ToList();
}
/// <summary>
/// Specifies how often this IGatewayListProvider is refreshed, to have a bound on max staleness of its returned infomation.
/// </summary>
public TimeSpan MaxStaleness
{
get { return maxStaleness; }
}
/// <summary>
/// Specifies whether this IGatewayListProvider ever refreshes its returned infomation, or always returns the same gw list.
/// (currently only the static config based StaticGatewayListProvider is not updatable. All others are.)
/// </summary>
public bool IsUpdatable
{
get { return true; }
}
/// <summary>
/// Deletes all table entries of the given deploymentId
/// </summary>
public Task DeleteMembershipTableEntries(string deploymentId)
{
string pathToDelete = "/" + deploymentId;
return UsingZookeeper(rootConnectionString, async zk =>
{
await ZKUtil.deleteRecursiveAsync(zk, pathToDelete);
await zk.sync(pathToDelete);
});
}
private async Task<bool> TryTransaction(Func<Transaction, Transaction> transactionFunc)
{
try
{
await UsingZookeeper(zk => transactionFunc(zk.transaction()).commitAsync());
return true;
}
catch (KeeperException e)
{
//these exceptions are thrown when the transaction fails to commit due to semantical reasons
if (e is KeeperException.NodeExistsException || e is KeeperException.NoNodeException ||
e is KeeperException.BadVersionException)
{
return false;
}
throw;
}
}
/// <summary>
/// Reads the nodes /IP:Port@Gen and /IP:Port@Gen/IAmAlive (which together is one row)
/// </summary>
/// <param name="zk">The zookeeper instance used for the read</param>
/// <param name="siloAddress">The silo address.</param>
private static async Task<Tuple<MembershipEntry, string>> GetRow(ZooKeeper zk, SiloAddress siloAddress)
{
string rowPath = ConvertToRowPath(siloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(siloAddress);
var rowDataTask = zk.getDataAsync(rowPath);
var rowIAmAliveDataTask = zk.getDataAsync(rowIAmAlivePath);
await Task.WhenAll(rowDataTask, rowIAmAliveDataTask);
MembershipEntry me = Deserialize<MembershipEntry>((await rowDataTask).Data);
me.IAmAliveTime = Deserialize<DateTime>((await rowIAmAliveDataTask).Data);
int rowVersion = (await rowDataTask).Stat.getVersion();
return new Tuple<MembershipEntry, string>(me, rowVersion.ToString(CultureInfo.InvariantCulture));
}
private Task<T> UsingZookeeper<T>(Func<ZooKeeper, Task<T>> zkMethod, bool canBeReadOnly = false)
{
return ZooKeeper.Using(deploymentConnectionString, ZOOKEEPER_CONNECTION_TIMEOUT, watcher, zkMethod, canBeReadOnly);
}
private Task UsingZookeeper(string connectString, Func<ZooKeeper, Task> zkMethod)
{
return ZooKeeper.Using(connectString, ZOOKEEPER_CONNECTION_TIMEOUT, watcher, zkMethod);
}
private static string ConvertToRowPath(SiloAddress siloAddress)
{
return "/" + siloAddress.ToParsableString();
}
private static string ConvertToRowIAmAlivePath(SiloAddress siloAddress)
{
return ConvertToRowPath(siloAddress) + "/IAmAlive";
}
private static TableVersion ConvertToTableVersion(Stat stat)
{
int version = stat.getVersion();
return new TableVersion(version, version.ToString(CultureInfo.InvariantCulture));
}
private static byte[] Serialize(object obj)
{
return
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj, Formatting.None,
MembershipSerializerSettings.Instance));
}
private static T Deserialize<T>(byte[] data)
{
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(data), MembershipSerializerSettings.Instance);
}
/// <summary>
/// the state of every ZooKeeper client and its push notifications are published using watchers.
/// in orleans the watcher is only for debugging purposes
/// </summary>
private class ZooKeeperWatcher : Watcher
{
private readonly Logger logger;
public ZooKeeperWatcher(Logger logger)
{
this.logger = logger;
}
public override Task process(WatchedEvent @event)
{
if (logger.IsVerbose)
{
logger.Verbose(@event.ToString());
}
return TaskDone.Done;
}
}
}
}
| |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
#endregion
namespace JigLibX.Math
{
#region public struct Transform
/// <summary>
/// Transform is unneeded and should be removed soon. The XNA matrix4x4 can store
/// the orientation and position.
/// </summary>
public struct Transform
{
/// <summary>
/// Position
/// </summary>
public Vector3 Position;
/// <summary>
/// Orientation
/// </summary>
public Matrix Orientation;
/// <summary>
/// Gets net Tranform
/// </summary>
public static Transform Identity
{
get { return new Transform(Vector3.Zero, Matrix.Identity); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="position"></param>
/// <param name="orientation"></param>
public Transform(Vector3 position, Matrix orientation)
{
this.Position = position;
this.Orientation = orientation;
}
/// <summary>
/// ApplyTransformRate
/// </summary>
/// <param name="rate"></param>
/// <param name="dt"></param>
public void ApplyTransformRate(ref TransformRate rate, float dt)
{
//Position += dt * rate.Velocity;
Vector3 pos;
Vector3.Multiply(ref rate.Velocity, dt, out pos);
Vector3.Add(ref Position, ref pos, out Position);
Vector3 dir = rate.AngularVelocity;
float ang = dir.Length();
if (ang > 0.0f)
{
Vector3.Divide(ref dir, ang, out dir); // dir /= ang;
ang *= dt;
Matrix rot;
Matrix.CreateFromAxisAngle(ref dir, ang, out rot);
Matrix.Multiply(ref Orientation, ref rot, out Orientation);
}
//JiggleMath.Orthonormalise(ref this.Orientation);
}
/// <summary>
/// ApplyTranformRate
/// </summary>
/// <param name="rate"></param>
/// <param name="dt"></param>
public void ApplyTransformRate(TransformRate rate, float dt)
{
//Position += dt * rate.Velocity;
Vector3 pos;
Vector3.Multiply(ref rate.Velocity, dt, out pos);
Vector3.Add(ref Position, ref pos, out Position);
Vector3 dir = rate.AngularVelocity;
float ang = dir.Length();
if (ang > 0.0f)
{
Vector3.Divide(ref dir, ang, out dir); // dir /= ang;
ang *= dt;
Matrix rot;
Matrix.CreateFromAxisAngle(ref dir, ang, out rot);
Matrix.Multiply(ref Orientation, ref rot, out Orientation);
}
// JiggleMath.Orthonormalise(ref this.Orientation);
}
/// <summary>
/// Operator overload of "*"
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>Tranform</returns>
public static Transform operator *(Transform lhs, Transform rhs)
{
Transform result;
Transform.Multiply(ref lhs, ref rhs, out result);
return result;
}
/// <summary>
/// Multiply
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>Transform</returns>
public static Transform Multiply(Transform lhs, Transform rhs)
{
Transform result = new Transform();
Matrix.Multiply(ref rhs.Orientation, ref lhs.Orientation, out result.Orientation);
//result.Orientation = rhs.Orientation * lhs.Orientation;
Vector3.TransformNormal(ref rhs.Position, ref lhs.Orientation, out result.Position);
Vector3.Add(ref lhs.Position, ref result.Position, out result.Position);
//result.Position = lhs.Position + Vector3.Transform(rhs.Position, lhs.Orientation);
return result;
}
/// <summary>
/// Multiply
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <param name="result"></param>
public static void Multiply(ref Transform lhs, ref Transform rhs, out Transform result)
{
result = new Transform();
Matrix.Multiply(ref rhs.Orientation, ref lhs.Orientation, out result.Orientation);
//result.Orientation = rhs.Orientation * lhs.Orientation;
Vector3.TransformNormal(ref rhs.Position, ref lhs.Orientation, out result.Position);
Vector3.Add(ref lhs.Position, ref result.Position, out result.Position);
//result.Position = lhs.Position + Vector3.Transform(rhs.Position, lhs.Orientation);
}
}
#endregion
#region public struct TransformRate
/// <summary>
/// Stuct TransormRate
/// </summary>
public struct TransformRate
{
/// <summary>
/// Velocity
/// </summary>
public Vector3 Velocity;
/// <summary>
/// AngularVelocity
/// </summary>
public Vector3 AngularVelocity;
/// <summary>
/// Constructor
/// </summary>
/// <param name="velocity"></param>
/// <param name="angularVelocity"></param>
public TransformRate(Vector3 velocity, Vector3 angularVelocity)
{
this.Velocity = velocity;
this.AngularVelocity = angularVelocity;
}
/// <summary>
/// Gets new TransformRate
/// </summary>
public static TransformRate Zero { get { return new TransformRate(); } }
/// <summary>
/// Add
/// </summary>
/// <param name="rate1"></param>
/// <param name="rate2"></param>
/// <returns>TransformRate</returns>
public static TransformRate Add(TransformRate rate1, TransformRate rate2)
{
TransformRate result = new TransformRate();
Vector3.Add(ref rate1.Velocity, ref rate2.Velocity, out result.Velocity);
Vector3.Add(ref rate1.AngularVelocity, ref rate2.AngularVelocity, out result.AngularVelocity);
return result;
}
/// <summary>
/// Add
/// </summary>
/// <param name="rate1"></param>
/// <param name="rate2"></param>
/// <param name="result"></param>
public static void Add(ref TransformRate rate1, ref TransformRate rate2 ,out TransformRate result)
{
Vector3.Add(ref rate1.Velocity, ref rate2.Velocity, out result.Velocity);
Vector3.Add(ref rate1.AngularVelocity, ref rate2.AngularVelocity, out result.AngularVelocity);
}
//public static TransformRate operator +(TransformRate rate1, TransformRate rate2)
//{
// return new TransformRate(rate1.Velocity + rate2.Velocity, rate1.AngularVelocity + rate2.AngularVelocity);
//}
}
#endregion
}
| |
//
// mdsetup.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Collections;
using Mono.Addins;
using Mono.Addins.Setup.ProgressMonitoring;
using Mono.Addins.Setup;
using System.IO;
using Mono.Addins.Description;
using System.Linq;
using System.Collections.Generic;
namespace Mono.Addins.Setup
{
/// <summary>
/// A command line add-in manager.
/// </summary>
/// <remarks>
/// This class can be used to provide an add-in management command line tool to applications.
/// </remarks>
public class SetupTool
{
Hashtable options = new Hashtable ();
string[] arguments;
string applicationName = "Mono";
SetupService service;
AddinRegistry registry;
ArrayList commands = new ArrayList ();
string setupAppName = "";
int uniqueId = 0;
int verbose = 1;
/// <summary>
/// Creates a new instance
/// </summary>
/// <param name="registry">
/// Add-in registry to manage.
/// </param>
public SetupTool (AddinRegistry registry)
{
this.registry = registry;
service = new SetupService (registry);
CreateCommands ();
}
/// <summary>
/// Display name of the host application
/// </summary>
public string ApplicationName {
get { return applicationName; }
set { applicationName = value; }
}
/// <summary>
/// Default add-in namespace of the application (optional). If set, only add-ins that belong to that namespace
/// will be shown in add-in lists.
/// </summary>
public string ApplicationNamespace {
get { return service.ApplicationNamespace; }
set { service.ApplicationNamespace = value; }
}
/// <summary>
/// Enables or disables verbose output
/// </summary>
public bool VerboseOutput {
get { return verbose > 1; }
set { verbose = value ? 2 : 1; }
}
/// <summary>
/// Sets or gets the verbose output level (0: normal output, 1:verbose, 2+:extra verbose)
/// </summary>
public int VerboseOutputLevel {
get { return verbose; }
set { verbose = value; }
}
/// <summary>
/// Runs the command line tool.
/// </summary>
/// <param name="args">
/// Array that contains the command line arguments
/// </param>
/// <param name="firstArgumentIndex">
/// Index of the arguments array that has the first argument for the management tool
/// </param>
/// <returns>
/// 0 if it succeeds. != 0 otherwise
/// </returns>
public int Run (string[] args, int firstArgumentIndex)
{
string[] aa = new string [args.Length - firstArgumentIndex];
Array.Copy (args, firstArgumentIndex, aa, 0, aa.Length);
return Run (aa);
}
/// <summary>
/// Runs the command line tool.
/// </summary>
/// <param name="args">
/// Command line arguments
/// </param>
/// <returns>
/// 0 if it succeeds. != 0 otherwise
/// </returns>
public int Run (string[] args)
{
if (args.Length == 0) {
PrintHelp ();
return 0;
}
string[] parms = new string [args.Length - 1];
Array.Copy (args, 1, parms, 0, args.Length - 1);
try {
ReadOptions (parms);
if (HasOption ("v"))
verbose++;
return RunCommand (args [0], parms);
} catch (InstallException ex) {
Console.WriteLine (ex.Message);
return -1;
}
}
int RunCommand (string cmd, string[] parms)
{
SetupCommand cc = FindCommand (cmd);
if (cc != null) {
cc.Handler (parms);
return 0;
}
else {
Console.WriteLine ("Unknown command: " + cmd);
return 1;
}
}
void Install (string[] args)
{
bool prompt = !args.Any (a => a == "-y");
var addins = args.Where (a => a != "-y");
if (!addins.Any ()) {
PrintHelp ("install");
return;
}
PackageCollection packs = new PackageCollection ();
foreach (string arg in addins) {
if (File.Exists (arg)) {
packs.Add (AddinPackage.FromFile (arg));
} else {
string aname = Addin.GetIdName (GetFullId (arg));
string aversion = Addin.GetIdVersion (arg);
if (aversion.Length == 0) aversion = null;
AddinRepositoryEntry[] ads = service.Repositories.GetAvailableAddin (aname, aversion);
if (ads.Length == 0)
throw new InstallException ("The addin '" + arg + "' is not available for install.");
packs.Add (AddinPackage.FromRepository (ads[ads.Length-1]));
}
}
Install (packs, prompt);
}
void CheckInstall (string[] args)
{
if (args.Length < 1) {
PrintHelp ("check-install");
return;
}
PackageCollection packs = new PackageCollection ();
for (int n=0; n<args.Length; n++) {
Addin addin = registry.GetAddin (GetFullId (args[n]));
if (addin != null) {
if (!addin.Enabled)
addin.Enabled = true;
continue;
}
string aname = Addin.GetIdName (GetFullId (args[n]));
string aversion = Addin.GetIdVersion (args[n]);
if (aversion.Length == 0) aversion = null;
AddinRepositoryEntry[] ads = service.Repositories.GetAvailableAddin (aname, aversion);
if (ads.Length == 0)
throw new InstallException ("The addin '" + args[n] + "' is not available for install.");
packs.Add (AddinPackage.FromRepository (ads[ads.Length-1]));
}
Install (packs, false);
}
void Install (PackageCollection packs, bool prompt)
{
PackageCollection toUninstall;
DependencyCollection unresolved;
IProgressStatus m = new ConsoleProgressStatus (verbose);
int n = packs.Count;
if (!service.Store.ResolveDependencies (m, packs, out toUninstall, out unresolved))
throw new InstallException ("Not all dependencies could be resolved.");
bool ask = false;
if (prompt && (packs.Count != n || toUninstall.Count != 0)) {
Console.WriteLine ("The following packages will be installed:");
foreach (Package p in packs)
Console.WriteLine (" - " + p.Name);
ask = true;
}
if (prompt && (toUninstall.Count != 0)) {
Console.WriteLine ("The following packages need to be uninstalled:");
foreach (Package p in toUninstall)
Console.WriteLine (" - " + p.Name);
ask = true;
}
if (ask) {
Console.WriteLine ();
Console.Write ("Are you sure you want to continue? (y/N): ");
string res = Console.ReadLine ();
if (res != "y" && res != "Y")
return;
}
if (!service.Store.Install (m, packs)) {
Console.WriteLine ("Install operation failed.");
}
}
void Uninstall (string[] args)
{
bool prompt = !args.Any (a => a == "-y");
var addins = args.Where (a => a != "-y");
if (!addins.Any ())
throw new InstallException ("The add-in id is required.");
if (addins.Count () > 1)
throw new InstallException ("Only one add-in id can be provided.");
string id = addins.First ();
Addin ads = registry.GetAddin (GetFullId (id));
if (ads == null)
throw new InstallException ("The add-in '" + id + "' is not installed.");
if (!ads.Description.CanUninstall)
throw new InstallException ("The add-in '" + id + "' is protected and can't be uninstalled.");
if (prompt) {
Console.WriteLine ("The following add-ins will be uninstalled:");
Console.WriteLine (" - " + ads.Description.Name);
foreach (Addin si in service.GetDependentAddins (id, true))
Console.WriteLine (" - " + si.Description.Name);
Console.WriteLine ();
Console.Write ("Are you sure you want to continue? (y/N): ");
string res = Console.ReadLine ();
if (res != "y" && res != "Y")
return;
}
service.Uninstall (new ConsoleProgressStatus (verbose), ads.Id);
}
bool IsHidden (Addin ainfo)
{
return service.ApplicationNamespace != null && !(ainfo.Namespace + ".").StartsWith (service.ApplicationNamespace + ".") || ainfo.Description.IsHidden;
}
bool IsHidden (AddinHeader ainfo)
{
return service.ApplicationNamespace != null && !(ainfo.Namespace + ".").StartsWith (service.ApplicationNamespace + ".");
}
string GetId (AddinHeader ainfo)
{
if (service.ApplicationNamespace != null && (ainfo.Namespace + ".").StartsWith (service.ApplicationNamespace + "."))
return ainfo.Id.Substring (service.ApplicationNamespace.Length + 1);
else
return ainfo.Id;
}
string GetFullId (string id)
{
if (service.ApplicationNamespace != null)
return service.ApplicationNamespace + "." + id;
else
return id;
}
void ListInstalled (string[] args)
{
IList alist = args;
bool showAll = alist.Contains ("-a");
Console.WriteLine ("Installed add-ins:");
ArrayList list = new ArrayList ();
list.AddRange (registry.GetAddins ());
if (alist.Contains ("-r"))
list.AddRange (registry.GetAddinRoots ());
foreach (Addin addin in list) {
if (!showAll && IsHidden (addin))
continue;
Console.WriteLine("[{0}] {1} {2} {3}", addin.Enabled ? "Enabled" : "Disabled", addin.Id, addin.Name, showAll ? $"({addin.AddinFile})": string.Empty);
}
}
void ListAvailable (string[] args)
{
bool showAll = args.Length > 0 && args [0] == "-a";
Console.WriteLine ("Available add-ins:");
AddinRepositoryEntry[] addins = service.Repositories.GetAvailableAddins ();
foreach (PackageRepositoryEntry addin in addins) {
if (!showAll && IsHidden (addin.Addin))
continue;
Console.WriteLine (" - " + GetId (addin.Addin) + " (" + addin.Repository.Name + ")");
}
}
void ListUpdates (string[] args)
{
bool showAll = args.Length > 0 && args [0] == "-a";
Console.WriteLine ("Looking for updates...");
service.Repositories.UpdateAllRepositories (null);
Console.WriteLine ("Available add-in updates:");
AddinRepositoryEntry[] addins = service.Repositories.GetAvailableAddins ();
bool found = false;
foreach (PackageRepositoryEntry addin in addins) {
Addin sinfo = registry.GetAddin (addin.Addin.LocalId);
if (sinfo != null && !showAll && IsHidden(sinfo))
continue;
if (sinfo != null && Addin.CompareVersions (sinfo.Version, addin.Addin.Version) == 1) {
Console.WriteLine (" - " + addin.Addin.Id + " " + addin.Addin.Version + " (" + addin.Repository.Name + ")");
found = true;
}
}
if (!found)
Console.WriteLine ("No updates found.");
}
void Update (string [] args)
{
bool showAll = args.Length > 0 && args [0] == "-a";
Console.WriteLine ("Looking for updates...");
service.Repositories.UpdateAllRepositories (null);
PackageCollection packs = new PackageCollection ();
AddinRepositoryEntry[] addins = service.Repositories.GetAvailableAddins ();
foreach (PackageRepositoryEntry addin in addins) {
Addin sinfo = registry.GetAddin (addin.Addin.LocalId);
if (sinfo != null && !showAll && IsHidden(sinfo))
continue;
if (sinfo != null && Addin.CompareVersions (sinfo.Version, addin.Addin.Version) == 1)
packs.Add (AddinPackage.FromRepository (addin));
}
if (packs.Count > 0)
Install (packs, true);
else
Console.WriteLine ("No updates found.");
}
void UpdateAvailableAddins (string[] args)
{
service.Repositories.UpdateAllRepositories (new ConsoleProgressStatus (verbose));
}
void EnableAddins (string[] args)
{
var addins = args.Where(a => a != "-y");
foreach (string addinId in addins)
{
registry.EnableAddin (addinId);
}
}
void DisableAddins(string[] args)
{
var addins = args.Where(a => a != "-y");
foreach (string addinId in addins)
{
registry.DisableAddin(addinId);
}
}
void AddRepository (string[] args)
{
foreach (string rep in args)
service.Repositories.RegisterRepository (new ConsoleProgressStatus (verbose), rep);
}
string GetRepositoryUrl (string url)
{
AddinRepository[] reps = GetRepositoryList ();
int nr;
if (int.TryParse (url, out nr)) {
if (nr < 0 || nr >= reps.Length)
throw new InstallException ("Invalid repository number.");
return reps[nr].Url;
} else {
if (!service.Repositories.ContainsRepository (url))
throw new InstallException ("Repository not registered.");
return url;
}
}
void RemoveRepository (string[] args)
{
foreach (string rep in args) {
service.Repositories.RemoveRepository (GetRepositoryUrl (rep));
}
}
void EnableRepository (string[] args)
{
foreach (string rep in args)
service.Repositories.SetRepositoryEnabled (GetRepositoryUrl(rep), true);
}
void DisableRepository (string[] args)
{
foreach (string rep in args)
service.Repositories.SetRepositoryEnabled (GetRepositoryUrl(rep), false);
}
AddinRepository[] GetRepositoryList ()
{
AddinRepository[] reps = service.Repositories.GetRepositories ();
Array.Sort (reps, (r1,r2) => r1.Title.CompareTo(r2.Title));
return reps;
}
void ListRepositories (string[] args)
{
AddinRepository[] reps = GetRepositoryList ();
if (reps.Length == 0) {
Console.WriteLine ("No repositories have been registered.");
return;
}
int n = 0;
Console.WriteLine ("Registered repositories:");
foreach (RepositoryRecord rep in reps) {
string num = n.ToString ();
Console.Write (num + ") ");
if (!rep.Enabled)
Console.Write ("(Disabled) ");
Console.WriteLine (rep.Title);
if (rep.Title != rep.Url)
Console.WriteLine (new string (' ', num.Length + 2) + rep.Url);
n++;
}
}
void BuildRepository (string[] args)
{
if (args.Length < 1)
throw new InstallException ("A directory name is required.");
service.BuildRepository (new ConsoleProgressStatus (verbose), args[0]);
}
void BuildPackage (string [] args)
{
if (args.Length < 1)
throw new InstallException ("A file name is required.");
var formatString = GetOption ("format", "mpack");
PackageFormat format;
switch (formatString) {
case "mpack":
format = PackageFormat.Mpack;
break;
case "vsix":
format = PackageFormat.Vsix;
break;
case "nupkg":
format = PackageFormat.NuGet;
break;
default:
throw new ArgumentException ($"Unsupported package format \"{formatString}\", supported formats are mpack and vsix.");
}
service.BuildPackage (new ConsoleProgressStatus (verbose), bool.Parse (GetOption ("debugSymbols", "false")), GetOption ("d", "."), format, GetArguments ());
}
void PrintLibraries (string[] args)
{
if (GetArguments ().Length < 1)
throw new InstallException ("An add-in id is required.");
bool refFormat = HasOption ("r");
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
foreach (string id in GetArguments ()) {
Addin addin = service.Registry.GetAddin (id);
if (addin != null) {
foreach (string asm in addin.Description.MainModule.Assemblies) {
string file = Path.Combine (addin.Description.BasePath, asm);
if (sb.Length > 0)
sb.Append (' ');
if (refFormat)
sb.Append ("-r:");
sb.Append (file);
}
}
}
Console.WriteLine (sb);
}
void PrintApplications (string[] args)
{
foreach (Application app in SetupService.GetExtensibleApplications ()) {
string line = app.Name;
if (!string.IsNullOrEmpty (app.Description))
line += " - " + app.Description;
Console.WriteLine (line);
}
}
void UpdateRegistry (string[] args)
{
registry.Update (new ConsoleProgressStatus (verbose));
}
void RepairRegistry (string[] args)
{
registry.Rebuild (new ConsoleProgressStatus (verbose));
}
void GenerateAddinScanDataFiles (string[] args)
{
bool recursive = false;
int i = 0;
if (args.Length > 0 && args [0] == "-r") {
recursive = true;
i = 1;
}
if (i >= args.Length)
registry.GenerateAddinScanDataFiles (new ConsoleProgressStatus (verbose), recursive:recursive);
else
registry.GenerateAddinScanDataFiles (new ConsoleProgressStatus (verbose), args[0], recursive);
}
void DumpRegistryFile (string[] args)
{
if (args.Length < 1)
throw new InstallException ("A file name is required.");
registry.DumpFile (args[0]);
}
void PrintAddinInfo (string[] args)
{
bool generateXml = false;
bool pickNamespace = false;
bool extensionModel = true;
ArrayList addins = new ArrayList ();
ArrayList namespaces = new ArrayList ();
bool generateAll = args [0] == "--all";
if (!generateAll) {
AddinDescription desc = null;
if (File.Exists (args [0]))
desc = registry.GetAddinDescription (new ConsoleProgressStatus (verbose), args [0]);
else {
Addin addin = registry.GetAddin (args [0]);
if (addin != null)
desc = addin.Description;
}
if (desc == null)
throw new InstallException (string.Format ("Add-in '{0}' not found.", args [0]));
if (desc != null)
addins.Add (desc);
}
for (int i = 1; i < args.Length; i++) {
string a = args [i];
if (a == "--all")
throw new InstallException (string.Format ("--all needs to be the first parameter"));
if (pickNamespace) {
namespaces.Add (a);
pickNamespace = false;
continue;
}
if (a == "--xml") {
generateXml = true;
continue;
}
if (a == "--namespace" || a == "-n") {
pickNamespace = true;
continue;
}
if (a == "--full") {
extensionModel = false;
continue;
}
}
if (generateAll) {
ArrayList list = new ArrayList ();
list.AddRange (registry.GetAddinRoots ());
list.AddRange (registry.GetAddins ());
foreach (Addin addin in list) {
if (namespaces.Count > 0) {
foreach (string ns in namespaces) {
if (addin.Id.StartsWith (ns + ".")) {
addins.Add (addin.Description);
break;
}
}
} else {
addins.Add (addin.Description);
}
}
}
if (addins.Count == 0)
throw new InstallException ("A file name or add-in ID is required.");
if (generateXml) {
XmlTextWriter tw = new XmlTextWriter (Console.Out);
tw.Formatting = Formatting.Indented;
tw.WriteStartElement ("Addins");
foreach (AddinDescription desc in addins) {
if (extensionModel && desc.ExtensionPoints.Count == 0)
continue;
PrintAddinXml (tw, desc);
}
tw.Close ();
}
else {
foreach (AddinDescription des in addins)
PrintAddin (des);
}
}
void PrintAddinXml (XmlWriter tw, AddinDescription desc)
{
tw.WriteStartElement ("Addin");
tw.WriteAttributeString ("name", desc.Name);
tw.WriteAttributeString ("addinId", desc.LocalId);
tw.WriteAttributeString ("fullId", desc.AddinId);
tw.WriteAttributeString ("id", "addin_" + uniqueId);
uniqueId++;
if (desc.Namespace.Length > 0)
tw.WriteAttributeString ("namespace", desc.Namespace);
tw.WriteAttributeString ("isroot", desc.IsRoot.ToString ());
tw.WriteAttributeString ("version", desc.Version);
if (desc.CompatVersion.Length > 0)
tw.WriteAttributeString ("compatVersion", desc.CompatVersion);
if (desc.Author.Length > 0)
tw.WriteAttributeString ("author", desc.Author);
if (desc.Category.Length > 0)
tw.WriteAttributeString ("category", desc.Category);
if (desc.Copyright.Length > 0)
tw.WriteAttributeString ("copyright", desc.Copyright);
if (desc.Url.Length > 0)
tw.WriteAttributeString ("url", desc.Url);
if (desc.Description.Length > 0)
tw.WriteElementString ("Description", desc.Description);
if (desc.ExtensionPoints.Count > 0) {
ArrayList list = new ArrayList ();
Hashtable visited = new Hashtable ();
foreach (ExtensionPoint ep in desc.ExtensionPoints) {
tw.WriteStartElement ("ExtensionPoint");
tw.WriteAttributeString ("path", ep.Path);
if (ep.Name.Length > 0)
tw.WriteAttributeString ("name", ep.Name);
else
tw.WriteAttributeString ("name", ep.Path);
if (ep.Description.Length > 0)
tw.WriteElementString ("Description", ep.Description);
PrintExtensionNodeSetXml (tw, desc, ep.NodeSet, list, visited);
tw.WriteEndElement ();
}
for (int n=0; n<list.Count; n++) {
ExtensionNodeType nt = (ExtensionNodeType) list [n];
tw.WriteStartElement ("ExtensionNodeType");
tw.WriteAttributeString ("name", nt.Id);
tw.WriteAttributeString ("id", visited [nt.Id + " " + nt.TypeName].ToString ());
if (nt.Description.Length > 0)
tw.WriteElementString ("Description", nt.Description);
if (nt.Attributes.Count > 0) {
tw.WriteStartElement ("Attributes");
foreach (NodeTypeAttribute att in nt.Attributes) {
tw.WriteStartElement ("Attribute");
tw.WriteAttributeString ("name", att.Name);
tw.WriteAttributeString ("type", att.Type);
tw.WriteAttributeString ("required", att.Required.ToString ());
tw.WriteAttributeString ("localizable", att.Localizable.ToString ());
if (att.Description.Length > 0)
tw.WriteElementString ("Description", att.Description);
tw.WriteEndElement ();
}
tw.WriteEndElement ();
}
if (nt.NodeTypes.Count > 0 || nt.NodeSets.Count > 0) {
tw.WriteStartElement ("ChildNodes");
PrintExtensionNodeSetXml (tw, desc, nt, list, visited);
tw.WriteEndElement ();
}
tw.WriteEndElement ();
}
}
tw.WriteEndElement ();
}
void PrintExtensionNodeSetXml (XmlWriter tw, AddinDescription desc, ExtensionNodeSet nset, ArrayList list, Hashtable visited)
{
foreach (ExtensionNodeType nt in nset.GetAllowedNodeTypes ()) {
tw.WriteStartElement ("ExtensionNode");
tw.WriteAttributeString ("name", nt.Id);
string id = RegisterNodeXml (nt, list, visited);
tw.WriteAttributeString ("id", id.ToString ());
if (nt.Description.Length > 0)
tw.WriteElementString ("Description", nt.Description);
tw.WriteEndElement ();
}
}
string RegisterNodeXml (ExtensionNodeType nt, ArrayList list, Hashtable visited)
{
string key = nt.Id + " " + nt.TypeName;
if (visited.Contains (key))
return (string) visited [key];
string k = "ntype_" + uniqueId;
uniqueId++;
visited [key] = k;
list.Add (nt);
return k;
}
void PrintAddin (AddinDescription desc)
{
Console.WriteLine ();
Console.WriteLine ("Addin Header");
Console.WriteLine ("------------");
Console.WriteLine ();
Console.WriteLine ("Name: " + desc.Name);
Console.WriteLine ("Id: " + desc.LocalId);
if (desc.Namespace.Length > 0)
Console.WriteLine ("Namespace: " + desc.Namespace);
Console.Write ("Version: " + desc.Version);
if (desc.CompatVersion.Length > 0)
Console.WriteLine (" (compatible with: " + desc.CompatVersion + ")");
else
Console.WriteLine ();
if (desc.AddinFile.Length > 0)
Console.WriteLine ("File: " + desc.AddinFile);
if (desc.Author.Length > 0)
Console.WriteLine ("Author: " + desc.Author);
if (desc.Category.Length > 0)
Console.WriteLine ("Category: " + desc.Category);
if (desc.Copyright.Length > 0)
Console.WriteLine ("Copyright: " + desc.Copyright);
if (desc.Url.Length > 0)
Console.WriteLine ("Url: " + desc.Url);
if (desc.Description.Length > 0) {
Console.WriteLine ();
Console.WriteLine ("Description: \n" + desc.Description);
}
if (desc.ExtensionPoints.Count > 0) {
Console.WriteLine ();
Console.WriteLine ("Extenstion Points");
Console.WriteLine ("-----------------");
foreach (ExtensionPoint ep in desc.ExtensionPoints)
PrintExtensionPoint (desc, ep);
}
}
void PrintExtensionPoint (AddinDescription desc, ExtensionPoint ep)
{
Console.WriteLine ();
Console.WriteLine ("* Extension Point: " + ep.Path);
if (ep.Description.Length > 0)
Console.WriteLine (ep.Description);
var list = new List<ExtensionNodeType> ();
Hashtable visited = new Hashtable ();
Console.WriteLine ();
Console.WriteLine (" Extension nodes:");
GetNodes (desc, ep.NodeSet, list, new Hashtable ());
foreach (ExtensionNodeType nt in list)
Console.WriteLine (" - " + nt.Id + ": " + nt.Description);
Console.WriteLine ();
Console.WriteLine (" Node description:");
string sind = " ";
for (int n=0; n<list.Count; n++) {
ExtensionNodeType nt = (ExtensionNodeType) list [n];
if (visited.Contains (nt.Id + " " + nt.TypeName))
continue;
visited.Add (nt.Id + " " + nt.TypeName, nt);
Console.WriteLine ();
Console.WriteLine (sind + "- " + nt.Id + ": " + nt.Description);
string nsind = sind + " ";
if (nt.Attributes.Count > 0) {
Console.WriteLine (nsind + "Attributes:");
foreach (NodeTypeAttribute att in nt.Attributes) {
string req = att.Required ? " (required)" : "";
Console.WriteLine (nsind + " " + att.Name + " (" + att.Type + "): " + att.Description + req);
}
}
if (nt.NodeTypes.Count > 0 || nt.NodeSets.Count > 0) {
Console.WriteLine (nsind + "Child nodes:");
var newList = new List<ExtensionNodeType> ();
GetNodes (desc, nt, newList, new Hashtable ());
list.AddRange (newList);
foreach (ExtensionNodeType cnt in newList)
Console.WriteLine (" " + cnt.Id + ": " + cnt.Description);
}
}
Console.WriteLine ();
}
void GetNodes (AddinDescription desc, ExtensionNodeSet nset, List<ExtensionNodeType> list, Hashtable visited)
{
if (visited.Contains (nset))
return;
visited.Add (nset, nset);
foreach (ExtensionNodeType nt in nset.NodeTypes) {
if (!visited.Contains (nt.Id + " " + nt.TypeName)) {
list.Add (nt);
visited.Add (nt.Id + " " + nt.TypeName, nt);
}
}
foreach (string nsid in nset.NodeSets) {
ExtensionNodeSet rset = desc.ExtensionNodeSets [nsid];
if (rset != null)
GetNodes (desc, rset, list, visited);
}
}
string[] GetArguments ()
{
return arguments;
}
bool HasOption (string key)
{
return options.Contains (key);
}
string GetOption (string key, string defValue)
{
object val = options [key];
if (val == null || val == (object) this)
return defValue;
else
return (string) val;
}
void ReadOptions (string[] args)
{
options = new Hashtable ();
ArrayList list = new ArrayList ();
foreach (string arg in args) {
if (arg.StartsWith ("-")) {
int i = arg.IndexOf (':');
if (i == -1)
options [arg.Substring (1)] = this;
else
options [arg.Substring (1, i-1)] = arg.Substring (i+1);
} else
list.Add (arg);
}
arguments = (string[]) list.ToArray (typeof(string));
}
/// <summary>
/// Adds a custom command to the add-in manager
/// </summary>
/// <param name="category">
/// Category under which the command has to be shown in the help text
/// </param>
/// <param name="command">
/// Name of the command
/// </param>
/// <param name="shortName">
/// Short name of the command (it's an alias of the normal name)
/// </param>
/// <param name="arguments">
/// Formal description of the arguments that the command accepts. For example: "[addin-id|addin-file] [--xml] [--all] [--full] [--namespace <namespace>]"
/// </param>
/// <param name="description">
/// Short description of the command
/// </param>
/// <param name="longDescription">
/// Long description of the command
/// </param>
/// <param name="handler">
/// Delegate to be invoked to run the command
/// </param>
public void AddCommand (string category, string command, string shortName, string arguments, string description, string longDescription, SetupCommandHandler handler)
{
SetupCommand cmd = new SetupCommand (category, command, shortName, handler);
cmd.Usage = arguments;
cmd.Description = description;
cmd.LongDescription = longDescription;
int lastCatPos = -1;
for (int n=0; n<commands.Count; n++) {
SetupCommand ec = (SetupCommand) commands [n];
if (ec.Category == category)
lastCatPos = n;
}
if (lastCatPos == -1)
commands.Add (cmd);
else
commands.Insert (lastCatPos+1, cmd);
}
SetupCommand FindCommand (string id)
{
foreach (SetupCommand cmd in commands)
if (cmd.Command == id || cmd.ShortCommand == id)
return cmd;
return null;
}
/// <summary>
/// Prints help about the add-in management tool, or about a specific command
/// </summary>
/// <param name="parms">
/// Optional command name and arguments
/// </param>
public void PrintHelp (params string[] parms)
{
if (parms.Length == 0) {
string lastCat = null;
foreach (SetupCommand cmd in commands) {
if (cmd.Command == "help")
continue;
if (lastCat != cmd.Category) {
Console.WriteLine ();
Console.WriteLine (cmd.Category + ":");
lastCat = cmd.Category;
}
string cc = cmd.CommandDesc;
if (cc.Length < 16)
cc += new string (' ', 16 - cc.Length);
Console.WriteLine (" " + cc + " " + cmd.Description);
}
Console.WriteLine ();
Console.WriteLine ("Run '" + setupAppName + "help <command>' to get help about a specific command.");
Console.WriteLine ();
return;
}
else {
Console.WriteLine ();
SetupCommand cmd = FindCommand (parms [0]);
if (cmd != null) {
Console.WriteLine ("{0}: {1}", cmd.CommandDesc, cmd.Description);
Console.WriteLine ();
Console.WriteLine ("Usage: {0}{1}", setupAppName, cmd.Usage);
Console.WriteLine ();
TextFormatter fm = new TextFormatter ();
fm.Wrap = WrappingType.Word;
fm.Append (cmd.LongDescription);
Console.WriteLine (fm.ToString ());
}
else
Console.WriteLine ("Unknown command: " + parms [0]);
Console.WriteLine ();
}
}
void CreateCommands ()
{
SetupCommand cmd;
string cat = "Add-in commands";
cmd = new SetupCommand (cat, "install", "i", new SetupCommandHandler (Install));
cmd.Description = "Installs add-ins.";
cmd.Usage = "[-y] [package-name|package-file] ...";
cmd.AppendDesc ("Installs an add-in or set of addins. The command argument is a list");
cmd.AppendDesc ("of files and/or package names. If a package name is provided");
cmd.AppendDesc ("the package will be looked up in the registered repositories.");
cmd.AppendDesc ("A specific add-in version can be specified by appending it to.");
cmd.AppendDesc ("the package name using '/' as a separator, like in this example:");
cmd.AppendDesc ("MonoDevelop.SourceEditor/0.9.1\n");
cmd.AppendDesc ("-y: Don't ask for confirmation.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "uninstall", "u", new SetupCommandHandler (Uninstall));
cmd.Description = "Uninstalls add-ins.";
cmd.Usage = "[-y] <package-name>";
cmd.AppendDesc ("Uninstalls an add-in. The command argument is the name");
cmd.AppendDesc ("of the add-in to uninstall.\n");
cmd.AppendDesc ("-y: Don't ask for confirmation.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "check-install", "ci", new SetupCommandHandler (CheckInstall));
cmd.Description = "Checks installed add-ins.";
cmd.Usage = "[package-name|package-file] ...";
cmd.AppendDesc ("Checks if a package is installed. If it is not, it looks for");
cmd.AppendDesc ("the package in the registered repositories, and if found");
cmd.AppendDesc ("the package is downloaded and installed, including all");
cmd.AppendDesc ("needed dependencies.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "update", "up", new SetupCommandHandler (Update));
cmd.Description = "Updates installed add-ins.";
cmd.AppendDesc ("Downloads and installs available updates for installed add-ins.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "list", "l", new SetupCommandHandler (ListInstalled));
cmd.Description = "Lists installed add-ins.";
cmd.AppendDesc ("Prints a list of all installed add-ins.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "list-av", "la", new SetupCommandHandler (ListAvailable));
cmd.Description = "Lists add-ins available in registered repositories.";
cmd.AppendDesc ("Prints a list of add-ins available to install in the");
cmd.AppendDesc ("registered repositories.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "list-update", "lu", new SetupCommandHandler (ListUpdates));
cmd.Description = "Lists available add-in updates.";
cmd.AppendDesc ("Prints a list of available add-in updates in the registered repositories.");
commands.Add (cmd);
cmd = new SetupCommand(cat, "enable", "e", new SetupCommandHandler (EnableAddins));
cmd.Description = "Enables addins.";
cmd.Usage = "<id> ...";
cmd.AppendDesc("Enables an add-in which has been disabled");
commands.Add(cmd);
cmd = new SetupCommand(cat, "disable", "d", new SetupCommandHandler(DisableAddins));
cmd.Description = "Disables addins.";
cmd.Usage = "<id> ...";
cmd.AppendDesc("Disables an add-in which has been enabled");
commands.Add(cmd);
cat = "Repository Commands";
cmd = new SetupCommand (cat, "rep-add", "ra", new SetupCommandHandler (AddRepository));
cmd.Description = "Registers repositories.";
cmd.Usage = "<url> ...";
cmd.AppendDesc ("Registers an add-in repository. Several URLs can be provided.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-remove", "rr", new SetupCommandHandler (RemoveRepository));
cmd.Description = "Unregisters repositories.";
cmd.Usage = "<url or number> ...";
cmd.AppendDesc ("Unregisters an add-in repository. Several URLs can be provided.");
cmd.AppendDesc ("Instead of an url, a repository number can be used (repository numbers are");
cmd.AppendDesc ("shown by the rep-list command.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-enable", "re", new SetupCommandHandler (EnableRepository));
cmd.Description = "Enables repositories.";
cmd.Usage = "<url or number> ...";
cmd.AppendDesc ("Enables an add-in repository which has been disabled. Several URLs can be");
cmd.AppendDesc ("provided. Instead of an url, a repository number can be used (repository");
cmd.AppendDesc ("numbers are shown by the rep-list command.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-disable", "rd", new SetupCommandHandler (DisableRepository));
cmd.Description = "Disables repositories.";
cmd.Usage = "<url> ...";
cmd.AppendDesc ("Disables an add-in repository. Several URLs can be provided");
cmd.AppendDesc ("When a repository is disabled, it will be ignored when using the update and");
cmd.AppendDesc ("install commands.");
cmd.AppendDesc ("Instead of an url, a repository number can be used (repository numbers are");
cmd.AppendDesc ("shown by the rep-list command.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-update", "ru", new SetupCommandHandler (UpdateAvailableAddins));
cmd.Description = "Updates the lists of available addins.";
cmd.AppendDesc ("Updates the lists of addins available in all registered repositories.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-list", "rl", new SetupCommandHandler (ListRepositories));
cmd.Description = "Lists registered repositories.";
cmd.AppendDesc ("Shows a list of all registered repositories.");
commands.Add (cmd);
cat = "Add-in Registry Commands";
cmd = new SetupCommand (cat, "reg-update", "rgu", new SetupCommandHandler (UpdateRegistry));
cmd.Description = "Updates the add-in registry.";
cmd.AppendDesc ("Looks for changes in add-in directories and updates the registry.");
cmd.AppendDesc ("New add-ins will be added and deleted add-ins will be removed.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "reg-build", "rgb", new SetupCommandHandler (RepairRegistry));
cmd.Description = "Rebuilds the add-in registry.";
cmd.AppendDesc ("Regenerates the add-in registry.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "reg-gen-data", "rgd", new SetupCommandHandler (GenerateAddinScanDataFiles));
cmd.Usage = "[-r] <path>";
cmd.Description = "Generates add-in scan data files.";
cmd.AppendDesc ("Generates binary add-in scan data files next to each");
cmd.AppendDesc ("add-in file. When such a file is present for an");
cmd.AppendDesc ("add-in, the add-in scanner will load the information");
cmd.AppendDesc ("from the data file instead of doing a full scan.");
cmd.AppendDesc ("Data files will be generated only add-ins located");
cmd.AppendDesc ("in the provided folder.");
cmd.AppendDesc ("Options:");
cmd.AppendDesc ("-r: Recursively look in subdirectories.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "info", null, new SetupCommandHandler (PrintAddinInfo));
cmd.Usage = "[addin-id|addin-file|--all] [--xml] [--full] [--namespace <namespace>]";
cmd.Description = "Prints information about add-ins.";
cmd.AppendDesc ("Prints information about add-ins. Options:\n");
cmd.AppendDesc (" --xml: Dump the information using an XML format.\n");
cmd.AppendDesc (" --full: Include add-ins which don't define extension points.\n");
cmd.AppendDesc (" --namespace ns: Include only add-ins from the specified 'ns' namespace.");
commands.Add (cmd);
cat = "Packaging Commands";
cmd = new SetupCommand (cat, "rep-build", "rb", new SetupCommandHandler (BuildRepository));
cmd.Description = "Creates a repository index file for a directory structure.";
cmd.Usage = "<path>";
cmd.AppendDesc ("Scans the provided directory and generates a set of index files with entries");
cmd.AppendDesc ("for all add-in packages found in the directory tree. The resulting file");
cmd.AppendDesc ("structure is an add-in repository that can be published in a web site or a");
cmd.AppendDesc ("shared directory.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "pack", "p", new SetupCommandHandler (BuildPackage));
cmd.Description = "Creates a package from an add-in configuration file.";
cmd.Usage = "<file-path> [-d:output-directory] [-format:(mpack|vsix|nupkg)] [-debugSymbols:(true|false)]";
cmd.AppendDesc ("Creates an add-in package (.mpack, .vsix or .nupkg file) which includes all files ");
cmd.AppendDesc ("needed to deploy an add-in. The command parameter is the path to");
cmd.AppendDesc ("the add-in's configuration file. If 'debugSymbols' is set to true");
cmd.AppendDesc ("then pdb or mdb debug symbols will automatically be included in the");
cmd.AppendDesc ("final package.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "help", "h", new SetupCommandHandler (PrintHelp));
cmd.Description = "Shows help about a command.";
cmd.Usage = "<command>";
commands.Add (cmd);
cat = "Build Commands";
cmd = new SetupCommand (cat, "libraries", "libs", new SetupCommandHandler (PrintLibraries));
cmd.Description = "Lists add-in assemblies.";
cmd.Usage = "[-r] <addin-id> ...";
cmd.AppendDesc ("Prints a list of assemblies exported by the add-in or add-ins provided");
cmd.AppendDesc ("as arguments. This list of assemblies can be used as references for");
cmd.AppendDesc ("building add-ins that depend on them. If the -r option is specified,");
cmd.AppendDesc ("each assembly is prefixed with '-r:'.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "applications", "apps", new SetupCommandHandler (PrintApplications));
cmd.Description = "Lists extensible applications.";
cmd.AppendDesc ("Prints a list of registered extensible applications.");
commands.Add (cmd);
cat = "Debug Commands";
cmd = new SetupCommand (cat, "dump-file", null, new SetupCommandHandler (DumpRegistryFile));
cmd.Description = "Prints the contents of a registry file.";
cmd.Usage = "<file-path>";
cmd.AppendDesc ("Prints the contents of a registry file for debugging.");
commands.Add (cmd);
}
}
class SetupCommand
{
string usage;
public SetupCommand (string cat, string cmd, string shortCmd, SetupCommandHandler handler)
{
Category = cat;
Command = cmd;
ShortCommand = shortCmd;
Handler = handler;
}
public void AppendDesc (string s)
{
LongDescription += s + " ";
}
public string Category;
public string Command;
public string ShortCommand;
public SetupCommandHandler Handler;
public string Usage {
get { return usage != null ? Command + " " + usage : Command; }
set { usage = value; }
}
public string CommandDesc {
get {
if (ShortCommand != null && ShortCommand.Length > 0)
return Command + " (" + ShortCommand + ")";
else
return Command;
}
}
public string Description = "";
public string LongDescription = "";
}
/// <summary>
/// A command handler
/// </summary>
public delegate void SetupCommandHandler (string[] args);
}
| |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for FailoverGroupsOperations.
/// </summary>
public static partial class FailoverGroupsOperationsExtensions
{
/// <summary>
/// Gets a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static FailoverGroup Get(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.GetAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> GetAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
public static FailoverGroup CreateOrUpdate(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> CreateOrUpdateAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static void Delete(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
operations.DeleteAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
public static FailoverGroup Update(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters)
{
return operations.UpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> UpdateAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the failover groups in a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
public static IPage<FailoverGroup> ListByServer(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName)
{
return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the failover groups in a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<FailoverGroup>> ListByServerAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Fails over from the current primary server to this server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static FailoverGroup Failover(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.FailoverAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Fails over from the current primary server to this server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> FailoverAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FailoverWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Fails over from the current primary server to this server. This operation
/// might result in data loss.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static FailoverGroup ForceFailoverAllowDataLoss(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.ForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Fails over from the current primary server to this server. This operation
/// might result in data loss.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> ForceFailoverAllowDataLossAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ForceFailoverAllowDataLossWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
public static FailoverGroup BeginCreateOrUpdate(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> BeginCreateOrUpdateAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static void BeginDelete(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
operations.BeginDeleteAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
public static FailoverGroup BeginUpdate(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters)
{
return operations.BeginUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a failover group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='parameters'>
/// The failover group parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> BeginUpdateAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Fails over from the current primary server to this server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static FailoverGroup BeginFailover(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.BeginFailoverAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Fails over from the current primary server to this server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> BeginFailoverAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginFailoverWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Fails over from the current primary server to this server. This operation
/// might result in data loss.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
public static FailoverGroup BeginForceFailoverAllowDataLoss(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.BeginForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Fails over from the current primary server to this server. This operation
/// might result in data loss.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server containing the failover group.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the failover group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FailoverGroup> BeginForceFailoverAllowDataLossAsync(this IFailoverGroupsOperations operations, string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginForceFailoverAllowDataLossWithHttpMessagesAsync(resourceGroupName, serverName, failoverGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the failover groups in a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<FailoverGroup> ListByServerNext(this IFailoverGroupsOperations operations, string nextPageLink)
{
return operations.ListByServerNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the failover groups in a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<FailoverGroup>> ListByServerNextAsync(this IFailoverGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
[CanEditMultipleObjects, CustomEditor(typeof(TonemappingColorGrading))]
public class TonemappingColorGradingEditor : Editor
{
#region Property drawers
[CustomPropertyDrawer(typeof(TonemappingColorGrading.ColorWheelGroup))]
private class ColorWheelGroupDrawer : PropertyDrawer
{
int m_RenderSizePerWheel;
int m_NumberOfWheels;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
var wheelAttribute = (TonemappingColorGrading.ColorWheelGroup)attribute;
property.isExpanded = true;
m_NumberOfWheels = property.CountInProperty() - 1;
if (m_NumberOfWheels == 0)
return 0f;
m_RenderSizePerWheel = Mathf.FloorToInt((EditorGUIUtility.currentViewWidth) / m_NumberOfWheels) - 30;
m_RenderSizePerWheel = Mathf.Clamp(m_RenderSizePerWheel, wheelAttribute.minSizePerWheel, wheelAttribute.maxSizePerWheel);
m_RenderSizePerWheel = Mathf.FloorToInt(pixelRatio * m_RenderSizePerWheel);
return ColorWheel.GetColorWheelHeight(m_RenderSizePerWheel);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (m_NumberOfWheels == 0)
return;
var width = position.width;
Rect newPosition = new Rect(position.x, position.y, width / m_NumberOfWheels, position.height);
foreach (SerializedProperty prop in property)
{
if (prop.propertyType == SerializedPropertyType.Color)
prop.colorValue = ColorWheel.DoGUI(newPosition, prop.displayName, prop.colorValue, m_RenderSizePerWheel);
newPosition.x += width / m_NumberOfWheels;
}
}
}
[CustomPropertyDrawer(typeof(TonemappingColorGrading.IndentedGroup))]
private class IndentedGroupDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 0f;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
foreach (SerializedProperty prop in property)
EditorGUILayout.PropertyField(prop);
EditorGUI.indentLevel--;
}
}
[CustomPropertyDrawer(typeof(TonemappingColorGrading.ChannelMixer))]
private class ChannelMixerDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 0f;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.type != "ChannelMixerSettings")
return;
SerializedProperty currentChannel = property.FindPropertyRelative("currentChannel");
int intCurrentChannel = currentChannel.intValue;
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel("Channel");
if (GUILayout.Toggle(intCurrentChannel == 0, "Red", EditorStyles.miniButtonLeft)) intCurrentChannel = 0;
if (GUILayout.Toggle(intCurrentChannel == 1, "Green", EditorStyles.miniButtonMid)) intCurrentChannel = 1;
if (GUILayout.Toggle(intCurrentChannel == 2, "Blue", EditorStyles.miniButtonRight)) intCurrentChannel = 2;
}
EditorGUILayout.EndHorizontal();
SerializedProperty serializedChannel = property.FindPropertyRelative("channels").GetArrayElementAtIndex(intCurrentChannel);
currentChannel.intValue = intCurrentChannel;
Vector3 v = serializedChannel.vector3Value;
v.x = EditorGUILayout.Slider("Red", v.x, -2f, 2f);
v.y = EditorGUILayout.Slider("Green", v.y, -2f, 2f);
v.z = EditorGUILayout.Slider("Blue", v.z, -2f, 2f);
serializedChannel.vector3Value = v;
EditorGUI.indentLevel--;
}
}
[CustomPropertyDrawer(typeof(TonemappingColorGrading.Curve))]
private class CurveDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
TonemappingColorGrading.Curve attribute = (TonemappingColorGrading.Curve)base.attribute;
if (property.propertyType != SerializedPropertyType.AnimationCurve)
{
EditorGUI.LabelField(position, label.text, "Use ClampCurve with an AnimationCurve.");
return;
}
property.animationCurveValue = EditorGUI.CurveField(position, label, property.animationCurveValue, attribute.color, new Rect(0f, 0f, 1f, 1f));
}
}
#endregion
#region Styling
private static Styles s_Styles;
private class Styles
{
public GUIStyle thumb2D = "ColorPicker2DThumb";
public Vector2 thumb2DSize;
internal Styles()
{
thumb2DSize = new Vector2(
!Mathf.Approximately(thumb2D.fixedWidth, 0f) ? thumb2D.fixedWidth : thumb2D.padding.horizontal,
!Mathf.Approximately(thumb2D.fixedHeight, 0f) ? thumb2D.fixedHeight : thumb2D.padding.vertical
);
}
}
public static readonly Color masterCurveColor = new Color(1f, 1f, 1f, 2f);
public static readonly Color redCurveColor = new Color(1f, 0f, 0f, 2f);
public static readonly Color greenCurveColor = new Color(0f, 1f, 0f, 2f);
public static readonly Color blueCurveColor = new Color(0f, 1f, 1f, 2f);
#endregion
private TonemappingColorGrading concreteTarget
{
get { return target as TonemappingColorGrading; }
}
private static float pixelRatio
{
get
{
#if !(UNITY_3 || UNITY_4 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
return EditorGUIUtility.pixelsPerPoint;
#else
return 1f;
#endif
}
}
private bool isHistogramSupported
{
get
{
return concreteTarget.histogramComputeShader != null
&& ImageEffectHelper.supportsDX11
&& concreteTarget.histogramShader != null
&& concreteTarget.histogramShader.isSupported;
}
}
private enum HistogramMode
{
Red = 0,
Green = 1,
Blue = 2,
Luminance = 3,
RGB,
}
private HistogramMode m_HistogramMode = HistogramMode.RGB;
private Rect m_HistogramRect;
private Material m_HistogramMaterial;
private ComputeBuffer m_HistogramBuffer;
private RenderTexture m_HistogramTexture;
// settings group <setting, property reference>
private Dictionary<FieldInfo, List<SerializedProperty>> m_GroupFields = new Dictionary<FieldInfo, List<SerializedProperty>>();
private void PopulateMap(FieldInfo group)
{
var searchPath = group.Name + ".";
foreach (var setting in group.FieldType.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
List<SerializedProperty> settingsGroup;
if (!m_GroupFields.TryGetValue(group, out settingsGroup))
{
settingsGroup = new List<SerializedProperty>();
m_GroupFields[group] = settingsGroup;
}
var property = serializedObject.FindProperty(searchPath + setting.Name);
if (property != null)
settingsGroup.Add(property);
}
}
private void OnEnable()
{
var settingsGroups = typeof(TonemappingColorGrading).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(TonemappingColorGrading.SettingsGroup), false).Any());
foreach (var settingGroup in settingsGroups)
PopulateMap(settingGroup);
concreteTarget.onFrameEndEditorOnly = OnFrameEnd;
}
private void OnDisable()
{
concreteTarget.onFrameEndEditorOnly = null;
if (m_HistogramMaterial != null)
DestroyImmediate(m_HistogramMaterial);
if (m_HistogramTexture != null)
DestroyImmediate(m_HistogramTexture);
if (m_HistogramBuffer != null)
m_HistogramBuffer.Release();
}
private void SetLUTImportSettings(TextureImporter importer)
{
#if UNITY_5_5_OR_NEWER
importer.textureType = TextureImporterType.Default;
importer.sRGBTexture = false;
importer.textureCompression = TextureImporterCompression.Uncompressed;
#else
importer.textureType = TextureImporterType.Advanced;
importer.linearTexture = true;
importer.textureFormat = TextureImporterFormat.RGB24;
#endif
importer.anisoLevel = 0;
importer.mipmapEnabled = false;
importer.SaveAndReimport();
}
private void DrawFields()
{
foreach (var group in m_GroupFields)
{
var enabledField = group.Value.FirstOrDefault(x => x.propertyPath == group.Key.Name + ".enabled");
var groupProperty = serializedObject.FindProperty(group.Key.Name);
GUILayout.Space(5);
bool display = EditorGUIHelper.Header(groupProperty, enabledField);
if (!display)
continue;
GUILayout.BeginHorizontal();
{
GUILayout.Space(10);
GUILayout.BeginVertical();
{
GUILayout.Space(3);
foreach (var field in group.Value.Where(x => x.propertyPath != group.Key.Name + ".enabled"))
{
// Special case for the tonemapping curve field
//if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) &&
// field.propertyType == SerializedPropertyType.AnimationCurve &&
// concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Curve)
// continue;
// Special case for the neutral tonemapper
bool neutralParam = field.name.StartsWith("neutral");
//if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) &&
// concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Neutral &&
// neutralParam)
// continue;
if (neutralParam)
EditorGUILayout.PropertyField(field, new GUIContent(ObjectNames.NicifyVariableName(field.name.Substring(7))));
else
EditorGUILayout.PropertyField(field);
}
// Bake button
if (group.Key.FieldType == typeof(TonemappingColorGrading.ColorGradingSettings))
{
EditorGUI.BeginDisabledGroup(!enabledField.boolValue);
if (GUILayout.Button("Export LUT as PNG", EditorStyles.miniButton))
{
string path = EditorUtility.SaveFilePanelInProject("Export LUT as PNG", "LUT.png", "png", "Please enter a file name to save the LUT texture to");
if (!string.IsNullOrEmpty(path))
{
Texture2D lut = concreteTarget.BakeLUT();
if (!concreteTarget.isGammaColorSpace)
{
var pixels = lut.GetPixels();
for (int i = 0; i < pixels.Length; i++)
pixels[i] = pixels[i].linear;
lut.SetPixels(pixels);
lut.Apply();
}
byte[] bytes = lut.EncodeToPNG();
System.IO.File.WriteAllBytes(path, bytes);
DestroyImmediate(lut);
AssetDatabase.Refresh();
TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path);
SetLUTImportSettings(importer);
}
}
EditorGUI.EndDisabledGroup();
}
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
}
}
public override void OnInspectorGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
serializedObject.Update();
GUILayout.Label("All following effects will use LDR color buffers.", EditorStyles.miniBoldLabel);
//if (concreteTarget.tonemapping.enabled)
//{
// Camera camera = concreteTarget.GetComponent<Camera>();
// if (camera != null && !camera.hdr)
// EditorGUILayout.HelpBox("The camera is not HDR enabled. This will likely break the tonemapper.", MessageType.Warning);
// else if (!concreteTarget.validRenderTextureFormat)
// EditorGUILayout.HelpBox("The input to tonemapper is not in HDR. Make sure that all effects prior to this are executed in HDR.", MessageType.Warning);
//}
if (concreteTarget.lut.enabled && concreteTarget.lut.texture != null)
{
if (!concreteTarget.validUserLutSize)
{
EditorGUILayout.HelpBox("Invalid LUT size. Should be \"height = sqrt(width)\" (e.g. 256x16).", MessageType.Error);
}
else
{
// Checks import settings on the lut, offers to fix them if invalid
TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(concreteTarget.lut.texture));
#if UNITY_5_5_OR_NEWER
bool valid = importer.anisoLevel == 0
&& importer.mipmapEnabled == false
&& importer.sRGBTexture == false
&& (importer.textureCompression == TextureImporterCompression.Uncompressed);
#else
bool valid = importer.anisoLevel == 0
&& importer.mipmapEnabled == false
&& importer.linearTexture == true
&& (importer.textureFormat == TextureImporterFormat.RGB24 || importer.textureFormat == TextureImporterFormat.AutomaticTruecolor);
#endif
if (!valid)
{
EditorGUILayout.HelpBox("Invalid LUT import settings.", MessageType.Warning);
GUILayout.Space(-32);
EditorGUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Fix", GUILayout.Width(60)))
{
SetLUTImportSettings(importer);
AssetDatabase.Refresh();
}
GUILayout.Space(8);
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(11);
}
}
}
DrawFields();
serializedObject.ApplyModifiedProperties();
}
private static readonly GUIContent k_HistogramTitle = new GUIContent("Histogram");
public override GUIContent GetPreviewTitle()
{
return k_HistogramTitle;
}
public override bool HasPreviewGUI()
{
return isHistogramSupported && targets.Length == 1 && concreteTarget != null && concreteTarget.enabled;
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
serializedObject.Update();
if (Event.current.type == EventType.Repaint)
{
// If m_HistogramRect isn't set the preview was just opened so refresh the render to get the histogram data
if (m_HistogramRect.width == 0 && m_HistogramRect.height == 0)
InternalEditorUtility.RepaintAllViews();
// Sizing
float width = Mathf.Min(512f, r.width);
float height = Mathf.Min(128f, r.height);
m_HistogramRect = new Rect(
Mathf.Floor(r.x + r.width / 2f - width / 2f),
Mathf.Floor(r.y + r.height / 2f - height / 2f),
width, height
);
if (m_HistogramTexture != null)
GUI.DrawTexture(m_HistogramRect, m_HistogramTexture);
}
// Toolbar
GUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
{
concreteTarget.histogramRefreshOnPlay = GUILayout.Toggle(concreteTarget.histogramRefreshOnPlay, new GUIContent("Refresh on Play", "Keep refreshing the histogram in play mode; this may impact performances."), EditorStyles.miniButton);
GUILayout.FlexibleSpace();
m_HistogramMode = (HistogramMode)EditorGUILayout.EnumPopup(m_HistogramMode);
}
GUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck())
InternalEditorUtility.RepaintAllViews();
}
private void OnFrameEnd(RenderTexture source)
{
if (Application.isPlaying && !concreteTarget.histogramRefreshOnPlay)
return;
if (Mathf.Approximately(m_HistogramRect.width, 0) || Mathf.Approximately(m_HistogramRect.height, 0) || !isHistogramSupported)
return;
// No need to process the full frame to get an histogram, resize the input to a max-size of 512
int rw = Mathf.Min(Mathf.Max(source.width, source.height), 512);
RenderTexture rt = RenderTexture.GetTemporary(rw, rw, 0);
Graphics.Blit(source, rt);
UpdateHistogram(rt, m_HistogramRect, m_HistogramMode);
Repaint();
RenderTexture.ReleaseTemporary(rt);
RenderTexture.active = null;
}
private static readonly int[] k_EmptyBuffer = new int[256 << 2];
void UpdateHistogram(RenderTexture source, Rect rect, HistogramMode mode)
{
if (m_HistogramMaterial == null)
m_HistogramMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(concreteTarget.histogramShader);
if (m_HistogramBuffer == null)
m_HistogramBuffer = new ComputeBuffer(256, sizeof(uint) << 2);
m_HistogramBuffer.SetData(k_EmptyBuffer);
ComputeShader cs = concreteTarget.histogramComputeShader;
int kernel = cs.FindKernel("KHistogramGather");
cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer);
cs.SetTexture(kernel, "_Source", source);
int[] channels = null;
switch (mode)
{
case HistogramMode.Luminance:
channels = new[] { 0, 0, 0, 1 };
break;
case HistogramMode.RGB:
channels = new[] { 1, 1, 1, 0 };
break;
case HistogramMode.Red:
channels = new[] { 1, 0, 0, 0 };
break;
case HistogramMode.Green:
channels = new[] { 0, 1, 0, 0 };
break;
case HistogramMode.Blue:
channels = new[] { 0, 0, 1, 0 };
break;
}
cs.SetInts("_Channels", channels);
cs.SetInt("_IsLinear", concreteTarget.isGammaColorSpace ? 0 : 1);
cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1);
kernel = cs.FindKernel("KHistogramScale");
cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer);
cs.SetFloat("_Height", rect.height);
cs.Dispatch(kernel, 1, 1, 1);
if (m_HistogramTexture == null)
{
DestroyImmediate(m_HistogramTexture);
m_HistogramTexture = new RenderTexture((int)rect.width, (int)rect.height, 0, RenderTextureFormat.ARGB32);
m_HistogramTexture.hideFlags = HideFlags.HideAndDontSave;
}
m_HistogramMaterial.SetBuffer("_Histogram", m_HistogramBuffer);
m_HistogramMaterial.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height));
m_HistogramMaterial.SetColor("_ColorR", redCurveColor);
m_HistogramMaterial.SetColor("_ColorG", greenCurveColor);
m_HistogramMaterial.SetColor("_ColorB", blueCurveColor);
m_HistogramMaterial.SetColor("_ColorL", masterCurveColor);
m_HistogramMaterial.SetInt("_Channel", (int)mode);
Graphics.Blit(m_HistogramTexture, m_HistogramTexture, m_HistogramMaterial, (mode == HistogramMode.RGB) ? 1 : 0);
}
public static class ColorWheel
{
// Constants
private const float PI_2 = Mathf.PI / 2f;
private const float PI2 = Mathf.PI * 2f;
// hue Wheel
private static Texture2D s_WheelTexture;
private static float s_LastDiameter;
private static GUIStyle s_CenteredStyle;
public static Color DoGUI(Rect area, string title, Color color, float diameter)
{
var labelrect = area;
labelrect.height = EditorGUIUtility.singleLineHeight;
if (s_CenteredStyle == null)
{
s_CenteredStyle = new GUIStyle(GUI.skin.GetStyle("Label"))
{
alignment = TextAnchor.UpperCenter
};
}
GUI.Label(labelrect, title, s_CenteredStyle);
// Figure out the wheel draw area
var wheelDrawArea = area;
wheelDrawArea.y += EditorGUIUtility.singleLineHeight;
wheelDrawArea.height = diameter;
if (wheelDrawArea.width > wheelDrawArea.height)
{
wheelDrawArea.x += (wheelDrawArea.width - wheelDrawArea.height) / 2.0f;
wheelDrawArea.width = area.height;
}
wheelDrawArea.width = wheelDrawArea.height;
var radius = diameter / 2.0f;
Vector3 hsv;
Color.RGBToHSV(color, out hsv.x, out hsv.y, out hsv.z);
// Retina/HDPI screens handling
wheelDrawArea.width /= pixelRatio;
wheelDrawArea.height /= pixelRatio;
float scaledRadius = radius / pixelRatio;
if (Event.current.type == EventType.Repaint)
{
if (!Mathf.Approximately(diameter, s_LastDiameter))
{
s_LastDiameter = diameter;
UpdateHueWheel((int)diameter);
}
// Wheel
GUI.DrawTexture(wheelDrawArea, s_WheelTexture);
// Thumb
Vector2 thumbPos = Vector2.zero;
float theta = hsv.x * PI2;
float len = hsv.y * scaledRadius;
thumbPos.x = Mathf.Cos(theta + PI_2);
thumbPos.y = Mathf.Sin(theta - PI_2);
thumbPos *= len;
Vector2 thumbSize = s_Styles.thumb2DSize;
Color oldColor = GUI.color;
GUI.color = Color.black;
Vector2 thumbSizeH = thumbSize / 2f;
Handles.color = Color.white;
Handles.DrawAAPolyLine(new Vector2(wheelDrawArea.x + scaledRadius + thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbSizeH.y), new Vector2(wheelDrawArea.x + scaledRadius + thumbPos.x, wheelDrawArea.y + scaledRadius + thumbPos.y));
s_Styles.thumb2D.Draw(new Rect(wheelDrawArea.x + scaledRadius + thumbPos.x - thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
GUI.color = oldColor;
}
hsv = GetInput(wheelDrawArea, hsv, scaledRadius);
var sliderDrawArea = wheelDrawArea;
sliderDrawArea.y = sliderDrawArea.yMax;
sliderDrawArea.height = EditorGUIUtility.singleLineHeight;
hsv.y = GUI.HorizontalSlider(sliderDrawArea, hsv.y, 1e-04f, 1f);
color = Color.HSVToRGB(hsv.x, hsv.y, hsv.z);
return color;
}
private static readonly int k_ThumbHash = "colorWheelThumb".GetHashCode();
private static Vector3 GetInput(Rect bounds, Vector3 hsv, float radius)
{
Event e = Event.current;
var id = GUIUtility.GetControlID(k_ThumbHash, FocusType.Passive, bounds);
Vector2 mousePos = e.mousePosition;
Vector2 relativePos = mousePos - new Vector2(bounds.x, bounds.y);
if (e.type == EventType.MouseDown && e.button == 0 && GUIUtility.hotControl == 0)
{
if (bounds.Contains(mousePos))
{
Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius);
float dist = Vector2.Distance(center, mousePos);
if (dist <= radius)
{
e.Use();
GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y);
GUIUtility.hotControl = id;
}
}
}
else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id)
{
Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius);
float dist = Vector2.Distance(center, mousePos);
if (dist <= radius)
{
e.Use();
GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y);
}
}
else if (e.type == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id)
{
e.Use();
GUIUtility.hotControl = 0;
}
return hsv;
}
private static void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation)
{
float dx = (x - radius) / radius;
float dy = (y - radius) / radius;
float d = Mathf.Sqrt(dx * dx + dy * dy);
hue = Mathf.Atan2(dx, -dy);
hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2;
saturation = Mathf.Clamp01(d);
}
private static void UpdateHueWheel(int diameter)
{
CleanTexture(s_WheelTexture);
s_WheelTexture = MakeTexture(diameter);
var radius = diameter / 2.0f;
Color[] pixels = s_WheelTexture.GetPixels();
for (int y = 0; y < diameter; y++)
{
for (int x = 0; x < diameter; x++)
{
int index = y * diameter + x;
float dx = (x - radius) / radius;
float dy = (y - radius) / radius;
float d = Mathf.Sqrt(dx * dx + dy * dy);
// Out of the wheel, early exit
if (d >= 1f)
{
pixels[index] = new Color(0f, 0f, 0f, 0f);
continue;
}
// red (0) on top, counter-clockwise (industry standard)
float saturation = d;
float hue = Mathf.Atan2(dx, dy);
hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2;
Color color = Color.HSVToRGB(hue, saturation, 1f);
// Quick & dirty antialiasing
color.a = (saturation > 0.99) ? (1f - saturation) * 100f : 1f;
pixels[index] = color;
}
}
s_WheelTexture.SetPixels(pixels);
s_WheelTexture.Apply();
}
private static Texture2D MakeTexture(int dimension)
{
return new Texture2D(dimension, dimension, TextureFormat.ARGB32, false, true)
{
filterMode = FilterMode.Point,
wrapMode = TextureWrapMode.Clamp,
hideFlags = HideFlags.HideAndDontSave,
alphaIsTransparency = true
};
}
private static void CleanTexture(Texture2D texture)
{
if (texture != null)
DestroyImmediate(texture);
}
public static float GetColorWheelHeight(int renderSizePerWheel)
{
// wheel height + title label + alpha slider
return renderSizePerWheel + 2 * EditorGUIUtility.singleLineHeight;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using P3Net.Kraken.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using P3Net.Kraken.ComponentModel;
namespace Tests.P3Net.Kraken.ComponentModel
{
[TestClass]
public class EnumTypeConverterTests : UnitTest
{
#region CanConvertFrom
[TestMethod]
public void CanConvertFrom_IsString ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.CanConvertFrom(typeof(string));
actual.Should().BeTrue();
}
[TestMethod]
public void CanConvertFrom_IsType ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.CanConvertFrom(typeof(DateTimeKind));
actual.Should().BeTrue();
}
[TestMethod]
public void CanConvertFrom_IsInvalid ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.CanConvertFrom(typeof(UnitTest));
actual.Should().BeFalse();
}
#endregion
#region CanConvertTo
[TestMethod]
public void CanConvertTo_IsString ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.CanConvertTo(typeof(string));
actual.Should().BeTrue();
}
[TestMethod]
public void CanConvertTo_IsType ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.CanConvertTo(typeof(DateTimeKind));
actual.Should().BeTrue();
}
[TestMethod]
public void CanConvertTo_IsInvalid ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.CanConvertTo(typeof(UnitTest));
actual.Should().BeFalse();
}
#endregion
#region ConvertFrom
[TestMethod]
public void ConvertFrom_IsValidString ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.ConvertFrom("Utc");
actual.Should().Be(DateTimeKind.Utc);
}
[TestMethod]
public void ConvertFrom_IsInvalidString ()
{
var target = new EnumTypeConverter<DateTimeKind>();
Action action = () => target.ConvertFrom("abc");
action.Should().Throw<FormatException>();
}
[TestMethod]
public void ConvertFrom_IsOfType ()
{
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.ConvertFrom(DateTimeKind.Local);
actual.Should().Be(DateTimeKind.Local);
}
[TestMethod]
public void ConvertFrom_CallsBase ()
{
var target = new DoNothingEnumTypeConverter();
var actual = target.ConvertFrom("Second");
actual.Should().Be(SimpleEnum.Second);
}
[TestMethod]
public void ConvertFrom_HasCustomConversion ()
{
var target = new TestEnumTypeConverter();
var actual = target.ConvertFrom("Two");
actual.Should().Be(SimpleEnum.Second);
}
#endregion
#region ConvertTo
[TestMethod]
public void ConvertTo_ToType ()
{
var expected = DateTimeKind.Local;
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.ConvertTo(expected, typeof(DateTimeKind));
actual.Should().Be(expected);
}
[TestMethod]
public void ConvertTo_ToString ()
{
var expected = DateTimeKind.Local;
var target = new EnumTypeConverter<DateTimeKind>();
var actual = target.ConvertTo(expected, typeof(string));
actual.Should().Be(expected.ToString());
}
[TestMethod]
public void ConvertTo_CallsBase ()
{
var target = new DoNothingEnumTypeConverter();
var actual = target.ConvertTo(SimpleEnum.Second, typeof(string));
actual.Should().Be("Second");
}
[TestMethod]
public void ConvertTo_HasCustomConverter ()
{
var target = new TestEnumTypeConverter();
var actual = target.ConvertTo(SimpleEnum.Third, typeof(string));
actual.Should().Be("Three");
}
#endregion
#region Private Members
private enum SimpleEnum { First, Second, Third }
private sealed class TestEnumTypeConverter : EnumTypeConverter<SimpleEnum>
{
protected override bool FromString ( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, string str, out SimpleEnum result )
{
if (String.Compare(str, "One", true) == 0)
{
result = SimpleEnum.First;
return true;
} else if (String.Compare(str, "Two", true) == 0)
{
result = SimpleEnum.Second;
return true;
} else if (String.Compare(str, "Three", true) == 0)
{
result = SimpleEnum.Third;
return true;
};
return base.FromString(context, culture, str, out result);
}
protected override bool ToString ( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, SimpleEnum value, out string result )
{
switch (value)
{
case SimpleEnum.First: result = "One"; return true;
case SimpleEnum.Second: result = "Two"; return true;
case SimpleEnum.Third: result = "Three"; return true;
};
return base.ToString(context, culture, value, out result);
}
}
private sealed class DoNothingEnumTypeConverter : EnumTypeConverter<SimpleEnum>
{
protected override bool FromString ( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, string str, out SimpleEnum result )
{
result = SimpleEnum.First;
return false;
}
protected override bool ToString ( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, SimpleEnum value, out string result )
{
result = null;
return false;
}
}
#endregion
}
}
| |
/*
* Author: Chase Barnes ("Wheffle")
* <[email protected]>
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrbitalSurveyPlus
{
public class ModuleOrbitalSurveyorPlus : ModuleOrbitalSurveyor, IAnimatedModule, IResourceConsumer
{
[KSPField(guiActive = true, guiName = "Survey Progress", guiFormat = "P0", isPersistant = true)]
float scanPercent = 0;
[KSPField(guiActive = true, guiName = "Status")]
string scanStatus = "standby";
[KSPField(isPersistant = true)]
string currentBody = "";
[KSPField(isPersistant = true)]
double lastUpdate = -1;
private bool freshLoaded = false;
private float orbitsToScan = 1f;
//private int defaultOrbitMin = 25000; //in meters above sea level
//private int defaultOrbitMax = 1500000; //in meters above sea level
private bool requirePolarOrbit = true;
private float electricDrain = 0.75f; //per second
private PartResourceDefinition resType = PartResourceLibrary.Instance.GetDefinition("ElectricCharge");
private int polarIncTolerance = 10;
private int orbitMin = 25000;
private int orbitMax = 1500000;
private bool extendedSurvey = true;
private bool biomeMapRequiresScan = true;
private bool activeScanner = true;
private Orbit orbit = null;
private CelestialBody body = null;
public override void OnStart(StartState state)
{
base.OnStart(state);
//load settings
extendedSurvey = OrbitalSurveyPlus.ExtendedSurvey;
biomeMapRequiresScan = OrbitalSurveyPlus.BiomeMapRequiresScan;
orbitsToScan = OrbitalSurveyPlus.OrbitsToScan;
minThreshold = OrbitalSurveyPlus.OrbitMinimum;
maxThreshold = OrbitalSurveyPlus.OrbitMaximum;
requirePolarOrbit = OrbitalSurveyPlus.RequirePolarOrbit;
electricDrain = OrbitalSurveyPlus.ScannerElectricDrain;
//change "Perform orbital survey" button name to make more sense with this mod
if (extendedSurvey)
{
Events["PerformSurvey"].guiName = "Transmit survey data";
}
else
{
//somehow it's getting changed even when "extendedSurvey" is clearly false,
//I don't feel like looking into why
Events["PerformSurvey"].guiName = "Perform orbital survey";
}
//vessel load flags
activeScanner = CheckScannerShouldBeActive();
SetScannerActive(activeScanner);
freshLoaded = true;
}
public override void OnFixedUpdate()
{
base.OnFixedUpdate();
//get orbit and body
orbit = vessel.GetOrbit();
body = orbit.referenceBody;
//check to see if body is same as currentBody,
//otherwise reset scan progress to 0
if (body.RevealName() != currentBody)
{
//new body encountered: reset scanner and update orbit parameters
scanPercent = 0;
lastUpdate = -1;
currentBody = body.RevealName();
//update orbit cutoffs here
UpdateOrbitParameters();
//appropriately activate scanner
activeScanner = CheckScannerShouldBeActive();
SetScannerActive(activeScanner);
}
if (activeScanner)
{
//check to see if scan is done
if (CheckPlanetScanned())
{
//scan is done, shut down scanning portion of module
SetScannerActive(false);
}
else
{
//perform scan
Scan();
}
}
freshLoaded = false;
}
private void UpdateOrbitParameters()
{
orbitMin = Math.Max(minThreshold, ((int)body.Radius) / 10);
orbitMax = Math.Min(maxThreshold, ((int)body.Radius) * 5);
//Pe under atmosphere doesn't count as stable orbit, but that is
//checked "on the fly" to mimic how the stock surveyor works
}
private void Scan()
{
//check to see if scan is needed
if (scanPercent < 1)
{
//check suitable orbit
if (ConditionsMet())
{
//get time since last update
double ut = Planetarium.GetUniversalTime();
if (lastUpdate == -1)
{
//first update: do nothing
lastUpdate = ut;
}
else if (ut - lastUpdate > 0)
{
//time lapse has occurred: update
double timeElapsed = ut - lastUpdate;
lastUpdate = ut;
//if vessel was freshly loaded and in the middle of a scan, decide what to do
bool skipDrain = false;
if (freshLoaded)
{
if (!HasElectricChargeGenerator())
{
//if no power generator exists, put scan update on hold
ScreenMessages.PostScreenMessage("Survey Scan Was Idle: No power generator detected", 6.0f, ScreenMessageStyle.UPPER_CENTER);
return;
}
else
{
//power generator onboard, but skip electrical drain for next update (could be huge)
skipDrain = true;
}
}
//drain electric charge
double drain = electricDrain * timeElapsed;
Vessel.ActiveResource ar = vessel.GetActiveResource(resType);
if (skipDrain || ar.amount >= drain)
{
//calculate scan percentage completed
double period = orbit.period;
double pct_scanned = timeElapsed / period * orbitsToScan;
scanPercent += (float)pct_scanned;
if (scanPercent >= 1)
{
scanPercent = 1;
ScreenMessages.PostScreenMessage("Survey Scan Completed", 6.0f, ScreenMessageStyle.UPPER_CENTER);
}
scanStatus = "scanning";
}
else
{
scanStatus = "not enough " + resType.name;
}
if (!skipDrain) part.RequestResource(resType.id, drain);
}
}
else
{
//orbit is not suitable
scanStatus = "unsuitable orbit";
}
}
else
{
//scan is completed
scanStatus = "survey completed";
}
}
private bool ConditionsMet()
{
if (orbit == null || body == null) return false;
double pe = orbit.PeA;
double ap = orbit.ApA;
double inc = orbit.inclination;
//check Pe and Ap are within parameters
bool orbitCheck = pe > orbitMin && ap < orbitMax && ap > 0;
//if planet has atmosphere, Pe under atmosphere doesn't count as stable orbit
if (body.atmosphere) orbitCheck = orbitCheck && pe > body.atmosphereDepth;
//check inclination
bool incCheck = !requirePolarOrbit ||
(inc > 90 - polarIncTolerance && inc < 90 + polarIncTolerance);
if (orbitCheck && incCheck)
{
return true;
}
return false;
}
private void SetScannerActive(bool active)
{
if (active)
{
activeScanner = true;
Fields["scanPercent"].guiActive = true;
Fields["scanStatus"].guiActive = true;
}
else
{
activeScanner = false;
Fields["scanPercent"].guiActive = false;
Fields["scanStatus"].guiActive = false;
}
}
private bool CheckPlanetScanned()
{
if (body == null) return false;
return ResourceMap.Instance.IsPlanetScanned(body.flightGlobalsIndex);
}
private bool HasElectricChargeGenerator()
{
//determine whether vessel has power generation
//This only
foreach (Part p in vessel.GetActiveParts())
{
foreach (PartModule module in p.Modules)
{
if (module.moduleName == "ModuleDeployableSolarPanel")
{
ModuleDeployableSolarPanel panel = (ModuleDeployableSolarPanel)module;
if (panel.panelState == ModuleDeployableSolarPanel.panelStates.EXTENDED) return true;
}
if (module.moduleName == "ModuleGenerator")
{
ModuleGenerator gen = (ModuleGenerator)module;
if (gen.generatorIsActive)
{
foreach (ModuleGenerator.GeneratorResource genRes in gen.outputList)
{
if (genRes.name == resType.name && genRes.rate > 0) return true;
}
}
}
}
}
return false;
}
private bool CheckScannerShouldBeActive()
{
return extendedSurvey && !CheckPlanetScanned();
}
public new void PerformSurvey()
{
//block stock "PerformSurvey" event from firing unless scan is at 100%
if (extendedSurvey && scanPercent < 1)
{
if (!ConditionsMet())
{
ScreenMessages.PostScreenMessage(
String.Format("Survey Scan Incomplete: You must be in a stable {0} between {1}km and {2}km",
requirePolarOrbit ? "polar orbit" : "orbit", orbitMin / 1000, orbitMax / 1000),
5.0f, ScreenMessageStyle.UPPER_CENTER);
}
else
{
ScreenMessages.PostScreenMessage("Survey Scan Incomplete (" + Math.Round(scanPercent * 100) + "%)", 3.0f, ScreenMessageStyle.UPPER_CENTER);
}
}
else
{
base.PerformSurvey();
}
}
public override string GetInfo()
{
//show electric charge info
String s = base.GetInfo();
if (extendedSurvey && electricDrain > 0)
{
s += "\n\n<b><color=#99ff00ff>Requires (while scanning):</color></b>";
s += "\nElectric Charge: " + electricDrain + "/sec.";
}
return s;
}
public List<PartResourceDefinition> GetConsumedResources()
{
List<PartResourceDefinition> list = new List<PartResourceDefinition>();
list.Add(resType);
return list;
}
public new void EnableModule()
{
base.EnableModule();
lastUpdate = -1;
freshLoaded = false;
}
}//end ModuleOrbitalSurveyorPlus
public class ModuleOrbitalScannerPlus : ModuleOrbitalScanner, IAnimatedModule
{
public override void OnStart(PartModule.StartState state)
{
base.OnStart(state);
//rename "toggle overlay" to be more descriptive
Events["ToggleOverlay"].guiName = "Toggle Resource Overlay";
//all events seem to get hidden except stock ToggleOVerlay - fix this for ToggleBiomeOverlay
BaseEvent biomeButton = Events["ToggleBiomeOverlay"];
biomeButton.guiActive = true;
//rearrange order of events to make UI nicer
int idx = Events.IndexOf(Events["ToggleOverlay"]);
Events.Remove(biomeButton);
Events.Insert(idx-1, biomeButton);
CopycatOverlayEvents();
}
public override void OnFixedUpdate()
{
base.OnFixedUpdate();
//Stupid Hack! (can't figure out when or where this gets checked for stock functions)
CopycatOverlayEvents();
}
[KSPEvent(guiName = "Toggle Biome Overlay", guiActive = true, guiActiveUnfocused = true, unfocusedRange = 3)]
public void ToggleBiomeOverlay()
{
OrbitalSurveyPlus.ToggleBiomeOverlay();
}
private void CopycatOverlayEvents()
{
//Copycat active state of stock Toggle Overlay event
Events["ToggleBiomeOverlay"].active = Events["ToggleOverlay"].active;
}
}//end ModuleOrbitalScannerPlus
}
| |
//
// AssemblyNameReference.cs
//
// Author:
// Jb Evain ([email protected])
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
using System.Collections;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Mono.Cecil.Metadata;
public class AssemblyNameReference : IMetadataScope, IAnnotationProvider, IReflectionStructureVisitable {
string m_name;
string m_culture;
Version m_version;
AssemblyFlags m_flags;
byte [] m_publicKey;
byte [] m_publicKeyToken;
AssemblyHashAlgorithm m_hashAlgo;
byte [] m_hash;
MetadataToken m_token;
IDictionary m_annotations;
bool m_fullNameDiscarded = true;
string m_fullName;
public string Name {
get { return m_name; }
set {
m_name = value;
m_fullNameDiscarded = true;
}
}
public string Culture {
get { return m_culture; }
set {
m_culture = value;
m_fullNameDiscarded = true;
}
}
public Version Version {
get { return m_version; }
set {
m_version = value;
m_fullNameDiscarded = true;
}
}
public AssemblyFlags Flags {
get { return m_flags; }
set { m_flags = value; }
}
public bool HasPublicKey {
get { return (m_flags & AssemblyFlags.PublicKey) != 0; }
set {
if (value)
m_flags |= AssemblyFlags.PublicKey;
else
m_flags &= ~AssemblyFlags.PublicKey;
}
}
public bool IsSideBySideCompatible {
get { return (m_flags & AssemblyFlags.SideBySideCompatible) != 0; }
set {
if (value)
m_flags |= AssemblyFlags.SideBySideCompatible;
else
m_flags &= ~AssemblyFlags.SideBySideCompatible;
}
}
public bool IsRetargetable {
get { return (m_flags & AssemblyFlags.Retargetable) != 0; }
set {
if (value)
m_flags |= AssemblyFlags.Retargetable;
else
m_flags &= ~AssemblyFlags.Retargetable;
}
}
public byte [] PublicKey {
get { return m_publicKey; }
set {
m_publicKey = value;
m_publicKeyToken = null;
m_fullNameDiscarded = true;
}
}
public byte [] PublicKeyToken {
get {
#if !CF_1_0
if ((m_publicKeyToken == null || m_publicKeyToken.Length == 0) && (m_publicKey != null && m_publicKey.Length > 0)) {
HashAlgorithm ha;
switch (m_hashAlgo) {
case AssemblyHashAlgorithm.Reserved:
ha = MD5.Create (); break;
default:
// None default to SHA1
ha = SHA1.Create (); break;
}
byte [] hash = ha.ComputeHash (m_publicKey);
// we need the last 8 bytes in reverse order
m_publicKeyToken = new byte [8];
Array.Copy (hash, (hash.Length - 8), m_publicKeyToken, 0, 8);
Array.Reverse (m_publicKeyToken, 0, 8);
}
#endif
return m_publicKeyToken;
}
set {
m_publicKeyToken = value;
m_fullNameDiscarded = true;
}
}
public string FullName {
get {
if (m_fullName != null && !m_fullNameDiscarded)
return m_fullName;
StringBuilder sb = new StringBuilder ();
string sep = ", ";
sb.Append (m_name);
if (m_version != null) {
sb.Append (sep);
sb.Append ("Version=");
sb.Append (m_version.ToString ());
}
sb.Append (sep);
sb.Append ("Culture=");
sb.Append (m_culture == string.Empty ? "neutral" : m_culture);
sb.Append (sep);
sb.Append ("PublicKeyToken=");
if (this.PublicKeyToken != null && m_publicKeyToken.Length > 0) {
for (int i = 0 ; i < m_publicKeyToken.Length ; i++) {
sb.Append (m_publicKeyToken [i].ToString ("x2"));
}
} else {
sb.Append ("null");
}
m_fullName = sb.ToString ();
m_fullNameDiscarded = false;
return m_fullName;
}
}
public static AssemblyNameReference Parse (string fullName)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
if (fullName.Length == 0)
throw new ArgumentException ("Name can not be empty");
AssemblyNameReference name = new AssemblyNameReference ();
string [] tokens = fullName.Split (',');
for (int i = 0; i < tokens.Length; i++) {
string token = tokens [i].Trim ();
if (i == 0) {
name.Name = token;
continue;
}
string [] parts = token.Split ('=');
if (parts.Length != 2)
throw new ArgumentException ("Malformed name");
switch (parts [0]) {
case "Version":
name.Version = new Version (parts [1]);
break;
case "Culture":
name.Culture = parts [1];
break;
case "PublicKeyToken":
string pkToken = parts [1];
if (pkToken == "null")
break;
name.PublicKeyToken = new byte [pkToken.Length / 2];
for (int j = 0; j < name.PublicKeyToken.Length; j++) {
name.PublicKeyToken [j] = Byte.Parse (pkToken.Substring (j * 2, 2), NumberStyles.HexNumber);
}
break;
}
}
return name;
}
public AssemblyHashAlgorithm HashAlgorithm
{
get { return m_hashAlgo; }
set { m_hashAlgo = value; }
}
public virtual byte [] Hash {
get { return m_hash; }
set { m_hash = value; }
}
public MetadataToken MetadataToken {
get { return m_token; }
set { m_token = value; }
}
IDictionary IAnnotationProvider.Annotations {
get {
if (m_annotations == null)
m_annotations = new Hashtable ();
return m_annotations;
}
}
public AssemblyNameReference () : this (string.Empty, string.Empty, new Version (0, 0, 0, 0))
{
}
public AssemblyNameReference (string name, string culture, Version version)
{
if (name == null)
throw new ArgumentNullException ("name");
if (culture == null)
throw new ArgumentNullException ("culture");
m_name = name;
m_culture = culture;
m_version = version;
m_hashAlgo = AssemblyHashAlgorithm.None;
}
public override string ToString ()
{
return this.FullName;
}
public virtual void Accept (IReflectionStructureVisitor visitor)
{
visitor.VisitAssemblyNameReference (this);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AutoUpdater.cs" company="The Watcher">
// Copyright (c) The Watcher Partial Rights Reserved.
// This software is licensed under the MIT license. See license.txt for details.
// </copyright>
// <summary>
// Code Named: VG-Ripper
// Function : Extracts Images posted on RiP forums and attempts to fetch them to disk.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
//#if (!RIPRIPPERX)
namespace Ripper.Core.Components
{
#region
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
#endregion
/// <summary>
/// Class to download Update and restart the app
/// </summary>
public class AutoUpdater
{
#region Public Methods
/// <summary>
/// TryUpdate: Invoke this method when you are ready to run the update checking thread
/// </summary>
/// <param name="programName">Name of the program.</param>
/// <param name="assembly">The assembly.</param>
public static void TryUpdate(string programName, Assembly assembly)
{
var backgroundThread = programName.Equals("Ripper.Services")
? new Thread(() => UpdateServicesDll(assembly)) { IsBackground = true }
: new Thread(() => UpdateProgram(programName, assembly)) { IsBackground = true };
backgroundThread.Start();
}
/// <summary>
/// Cleanup after the update.
/// </summary>
/// <param name="programName">Name of the program.</param>
public static void CleanupAfterUpdate(string programName)
{
var tempFolder = Path.Combine(Application.StartupPath, "temp");
// Delete Backup Files From AutoUpdate
if (File.Exists(Path.Combine(Application.StartupPath, $"{programName}.bak")))
{
File.Delete(Path.Combine(Application.StartupPath, $"{programName}.bak"));
}
if (File.Exists(Path.Combine(Application.StartupPath, "Ripper.Services.bak")))
{
File.Delete(Path.Combine(Application.StartupPath, "Ripper.Services.bak"));
}
if (File.Exists(Path.Combine(Application.StartupPath, "Ripper.Core.bak")))
{
File.Delete(Path.Combine(Application.StartupPath, "Ripper.Core.bak"));
}
// Finally Delete Temp Directory
DeleteFolder(tempFolder);
}
#endregion
#region Methods
/// <summary>
/// Auto Updater, download latest version and restart it.
/// </summary>
/// <param name="programName">Name of the program.</param>
/// <param name="assembly">The assembly.</param>
private static void UpdateProgram(string programName, Assembly assembly)
{
var tempFolder = Path.Combine(Application.StartupPath, "temp");
try
{
// Download Update
var downloadURL = $"http://www.watchersnet.de/rip-ripper/{programName}{VersionCheck.OnlineVersion}.zip";
var tempZIP = Path.Combine(Application.StartupPath, "temp.zip");
var client = new WebClient();
client.DownloadFile(downloadURL, tempZIP);
client.Dispose();
if (!File.Exists(tempZIP))
{
return;
}
// Extract Zip file
var fastZip = new FastZip();
fastZip.ExtractZip(tempZIP, tempFolder, null);
File.Delete(tempZIP);
if (programName.Equals("PG-Ripper"))
{
programName = "PGRipper";
}
if (!File.Exists(Path.Combine(tempFolder, $"{programName}.exe")))
{
return;
}
// Check for Microsoft.WindowsAPICodePack.dll
if (!File.Exists(Path.Combine(Application.StartupPath, "Microsoft.WindowsAPICodePack.dll")))
{
File.Copy(
Path.Combine(tempFolder, "Microsoft.WindowsAPICodePack.dll"),
Path.Combine(Application.StartupPath, "Microsoft.WindowsAPICodePack.dll"));
}
// Check for Microsoft.WindowsAPICodePack.Shell.dll
if (!File.Exists(Path.Combine(Application.StartupPath, "Microsoft.WindowsAPICodePack.Shell.dll")))
{
File.Copy(
Path.Combine(tempFolder, "Microsoft.WindowsAPICodePack.Shell.dll"),
Path.Combine(Application.StartupPath, "Microsoft.WindowsAPICodePack.Shell.dll"));
}
// Check for Ripper.Services.dll
if (!File.Exists(Path.Combine(Application.StartupPath, "Ripper.Services.dll")))
{
File.Copy(
Path.Combine(tempFolder, "Ripper.Services.dll"),
Path.Combine(Application.StartupPath, "Ripper.Services.dll"));
}
else
{
File.Replace(
Path.Combine(tempFolder, "Ripper.Services.dll"),
Path.Combine(Application.StartupPath, "Ripper.Services.dll"),
"Ripper.Services.bak");
}
// Check for Ripper.Core.dll
if (!File.Exists(Path.Combine(Application.StartupPath, "Ripper.Core.dll")))
{
File.Copy(
Path.Combine(tempFolder, "Ripper.Core.dll"),
Path.Combine(Application.StartupPath, "Ripper.Core.dll"));
}
else
{
File.Replace(
Path.Combine(tempFolder, "Ripper.Core.dll"),
Path.Combine(Application.StartupPath, "Ripper.Core.dll"),
"Ripper.Core.bak");
}
if (!File.Exists(Path.Combine(Application.StartupPath, $"{programName}.exe")))
{
return;
}
// Replace Exe
File.Replace(
Path.Combine(tempFolder, $"{programName}.exe"),
assembly.Location,
$"{programName}.bak");
DeleteFolder(tempFolder);
var upgradeProcess = new ProcessStartInfo(assembly.Location);
Process.Start(upgradeProcess);
Environment.Exit(0);
}
catch (Exception ex)
{
Utility.SaveOnCrash(ex.Message, ex.StackTrace, null);
}
finally
{
// Finally Delete Temp Directory
DeleteFolder(tempFolder);
}
}
/// <summary>
/// Auto Updater, download latest version and restart it.
/// </summary>
/// <param name="assembly">The assembly.</param>
private static void UpdateServicesDll(Assembly assembly)
{
var tempFolder = Path.Combine(Application.StartupPath, "temp");
try
{
// Download Update
const string DownloadURL = "http://www.watchersnet.de/rip-ripper/Ripper.Services.dll";
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
var client = new WebClient();
client.DownloadFile(DownloadURL, Path.Combine(tempFolder, "Ripper.Services.dll"));
client.Dispose();
if (!File.Exists(Path.Combine(tempFolder, "Ripper.Services.dll")))
{
return;
}
if (!File.Exists(Path.Combine(Application.StartupPath, "Ripper.Services.dll")))
{
File.Copy(
Path.Combine(tempFolder, "Ripper.Services.dll"),
Path.Combine(Application.StartupPath, "Ripper.Services.dll"));
}
else
{
File.Replace(
Path.Combine(tempFolder, "Ripper.Services.dll"),
Path.Combine(Application.StartupPath, "Ripper.Services.dll"),
"Ripper.Services.bak");
}
var upgradeProcess = new ProcessStartInfo(assembly.Location);
Process.Start(upgradeProcess);
Environment.Exit(0);
}
catch (Exception ex)
{
Utility.SaveOnCrash(ex.Message, ex.StackTrace, null);
}
finally
{
// Finally Delete Temp Directory
DeleteFolder(tempFolder);
}
}
/// <summary>
/// Deletes the folder.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Returns if Folder was deleted</returns>
private static bool DeleteFolder(string path)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
}
catch (Exception)
{
return false;
}
return true;
}
#endregion
}
}
//#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;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
#if FEATURE_LEGACYNETCF
public
#else
internal
#endif
class JavaScriptObjectDeserializer
{
private const string DateTimePrefix = @"""\/Date(";
private const int DateTimePrefixLength = 8;
internal JavaScriptString _s;
private bool _isDataContract;
#if FEATURE_LEGACYNETCF
public
#else
internal
#endif
object BasicDeserialize()
{
object result = this.DeserializeInternal(0);
if (this._s.GetNextNonEmptyChar() != null)
{
throw new SerializationException(SR.Format(SR.ObjectDeserializer_IllegalPrimitive, this._s.ToString()));
}
return result;
}
internal JavaScriptObjectDeserializer(string input)
: this(input, true)
{
}
#if FEATURE_LEGACYNETCF
public
#else
internal
#endif
JavaScriptObjectDeserializer(string input, bool isDataContract)
{
_s = new JavaScriptString(input);
_isDataContract = isDataContract;
}
private object DeserializeInternal(int depth)
{
Nullable<Char> c = _s.GetNextNonEmptyChar();
if (c == null)
{
return null;
}
_s.MovePrev();
if (IsNextElementDateTime())
{
return DeserializeStringIntoDateTime();
}
if (IsNextElementObject(c))
{
IDictionary<string, object> dict = DeserializeDictionary(depth);
return dict;
}
if (IsNextElementArray(c))
{
return DeserializeList(depth);
}
if (IsNextElementString(c))
{
return DeserializeString();
}
return DeserializePrimitiveObject();
}
private IList DeserializeList(int depth)
{
IList list = new List<object>();
Nullable<Char> c = _s.MoveNext();
if (c != '[')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, '[')));
}
bool expectMore = false;
while ((c = _s.GetNextNonEmptyChar()) != null && c != ']')
{
_s.MovePrev();
object o = DeserializeInternal(depth);
list.Add(o);
expectMore = false;
c = _s.GetNextNonEmptyChar();
if (c == ']')
{
break;
}
expectMore = true;
if (c != ',')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ',')));
}
}
if (expectMore)
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_InvalidArrayExtraComma)));
}
if (c != ']')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ']')));
}
return list;
}
private IDictionary<string, object> DeserializeDictionary(int depth)
{
IDictionary<string, object> dictionary = null;
Nullable<Char> c = _s.MoveNext();
if (c != '{')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, '{')));
}
bool encounteredFirstMember = false;
while ((c = _s.GetNextNonEmptyChar()) != null)
{
_s.MovePrev();
if (c == ':')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_InvalidMemberName)));
}
string memberName = null;
if (c != '}')
{
memberName = DeserializeMemberName();
if (String.IsNullOrEmpty(memberName))
{
throw new SerializationException
(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_InvalidMemberName)));
}
c = _s.GetNextNonEmptyChar();
if (c != ':')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ':')));
}
}
if (dictionary == null)
{
dictionary = new Dictionary<string, object>();
if (String.IsNullOrEmpty(memberName))
{
c = _s.GetNextNonEmptyChar();
break;
}
}
object propVal = DeserializeInternal(depth);
//Ignore the __type attribute when its not the first element in the dictionary
if (!encounteredFirstMember || (memberName != null && !memberName.Equals(JsonGlobals.ServerTypeString)))
{
if (dictionary.ContainsKey(memberName))
{
throw new SerializationException(SR.Format(SR.JsonDuplicateMemberInInput, memberName));
}
dictionary[memberName] = propVal;
//Added the first member from the dictionary
encounteredFirstMember = true;
}
c = _s.GetNextNonEmptyChar();
if (c == '}')
{
break;
}
if (c != ',')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ',')));
}
}
if (c != '}')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, '}')));
}
return dictionary;
}
private string DeserializeMemberName()
{
Nullable<Char> c = _s.GetNextNonEmptyChar();
if (c == null)
{
return null;
}
_s.MovePrev();
if (IsNextElementString(c))
{
return DeserializeString();
}
return DeserializePrimitiveToken();
}
private object DeserializePrimitiveObject()
{
string input = DeserializePrimitiveToken();
if (input.Equals("null"))
{
return null;
}
if (input.Equals(Globals.True))
{
return true;
}
if (input.Equals(Globals.False))
{
return false;
}
if (input.Equals(JsonGlobals.PositiveInf))
{
return float.PositiveInfinity;
}
if (input.Equals(JsonGlobals.NegativeInf))
{
return float.NegativeInfinity;
}
bool hasDecimalPoint = input.IndexOfAny(JsonGlobals.FloatingPointCharacters) >= 0;
if (!hasDecimalPoint)
{
int parseInt;
if (Int32.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseInt))
{
return parseInt;
}
long parseLong;
if (Int64.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseLong))
{
return parseLong;
}
if (_isDataContract)
{
return JavaScriptObjectDeserializer.ParseJsonNumberAsDoubleOrDecimal(input);
}
}
//Ensure that the number is a valid JSON number.
object ret = JavaScriptObjectDeserializer.ParseJsonNumberAsDoubleOrDecimal(input);
if (ret.GetType() == Globals.TypeOfString)
{
throw new SerializationException(SR.Format(SR.ObjectDeserializer_IllegalPrimitive, input));
}
// return floating point number as string in DataContract case.
return _isDataContract ? input : ret;
}
private string DeserializePrimitiveToken()
{
StringBuilder sb = new StringBuilder();
Nullable<Char> c = null;
while ((c = _s.MoveNext()) != null)
{
if (Char.IsLetterOrDigit(c.Value) || c.Value == '.' ||
c.Value == '-' || c.Value == '_' || c.Value == '+')
{
sb.Append(c);
}
else
{
_s.MovePrev();
break;
}
}
return sb.ToString();
}
internal string DeserializeString()
{
StringBuilder sb = new StringBuilder();
bool escapedChar = false;
Nullable<Char> c = _s.MoveNext();
Char quoteChar = CheckQuoteChar(c);
while ((c = _s.MoveNext()) != null)
{
if (c == '\\')
{
if (escapedChar)
{
sb.Append('\\');
escapedChar = false;
}
else
{
escapedChar = true;
}
continue;
}
if (escapedChar)
{
AppendCharToBuilder(c, sb);
escapedChar = false;
}
else
{
if (c == quoteChar)
{
return sb.ToString();
}
sb.Append(c);
}
}
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnterminatedString)));
}
private void AppendCharToBuilder(char? c, StringBuilder sb)
{
if (c == '"' || c == '\'' || c == '/')
{
sb.Append(c);
}
else if (c == 'b')
{
sb.Append('\b');
}
else if (c == 'f')
{
sb.Append('\f');
}
else if (c == 'n')
{
sb.Append('\n');
}
else if (c == 'r')
{
sb.Append('\r');
}
else if (c == 't')
{
sb.Append('\t');
}
else if (c == 'u')
{
sb.Append((char)int.Parse(_s.MoveNext(4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
}
else
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_BadEscape)));
}
}
private char CheckQuoteChar(char? c)
{
Char quoteChar = '"';
if (c == '\'')
{
quoteChar = c.Value;
}
else if (c != '"')
{
throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_StringNotQuoted)));
}
return quoteChar;
}
private object DeserializeStringIntoDateTime()
{
string dateTimeValue = DeserializeString();
string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8);
long millisecondsSinceUnixEpoch;
DateTimeKind dateTimeKind = DateTimeKind.Utc;
int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1);
if (indexOfTimeZoneOffset == -1)
{
indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1);
}
if (indexOfTimeZoneOffset != -1)
{
dateTimeKind = DateTimeKind.Local;
ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset);
}
try
{
millisecondsSinceUnixEpoch = Int64.Parse(ticksvalue, NumberStyles.Integer, CultureInfo.InvariantCulture);
}
catch (ArgumentException exception)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
}
catch (FormatException exception)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
}
catch (OverflowException exception)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
}
// Convert from # millseconds since epoch to # of 100-nanosecond units, which is what DateTime understands
long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks;
try
{
DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc);
switch (dateTimeKind)
{
case DateTimeKind.Local:
dateTime = dateTime.ToLocalTime();
break;
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified);
break;
case DateTimeKind.Utc:
default:
break;
}
// This string could be serialized from DateTime or String, keeping both until DataContract information is available
return Tuple.Create<DateTime, string>(dateTime, dateTimeValue);
}
catch (ArgumentException exception)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception));
}
}
private static bool IsNextElementArray(Nullable<Char> c)
{
return c == '[';
}
private bool IsNextElementDateTime()
{
String next = _s.MoveNext(DateTimePrefixLength);
if (next != null)
{
_s.MovePrev(DateTimePrefixLength);
return String.Equals(next, DateTimePrefix, StringComparison.Ordinal);
}
return false;
}
private static bool IsNextElementObject(Nullable<Char> c)
{
return c == '{';
}
private static bool IsNextElementString(Nullable<Char> c)
{
return c == '"' || c == '\'';
}
internal static object ParseJsonNumberAsDoubleOrDecimal(string input)
{
decimal parseDecimal;
if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseDecimal) && parseDecimal != 0)
{
return parseDecimal;
}
double parseDouble;
if (Double.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseDouble))
{
return parseDouble;
}
return input;
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocInfo
// ObjectType: DocInfo
// CSLAType: ReadOnlyObject
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using DocStore.Business.Admin;
namespace DocStore.Business
{
/// <summary>
/// Document basic information (read only object).<br/>
/// This is a generated <see cref="DocInfo"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="DocList"/> collection.
/// </remarks>
[Serializable]
public partial class DocInfo : ReadOnlyBase<DocInfo>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocID"/> property.
/// </summary>
public static readonly PropertyInfo<int> DocIDProperty = RegisterProperty<int>(p => p.DocID, "Doc ID", -1);
/// <summary>
/// Gets the Doc ID.
/// </summary>
/// <value>The Doc ID.</value>
public int DocID
{
get { return GetProperty(DocIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocClassID"/> property.
/// </summary>
public static readonly PropertyInfo<int> DocClassIDProperty = RegisterProperty<int>(p => p.DocClassID, "Doc Class ID");
/// <summary>
/// Gets the Doc Class ID.
/// </summary>
/// <value>The Doc Class ID.</value>
protected int DocClassID
{
get { return GetProperty(DocClassIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocTypeID"/> property.
/// </summary>
public static readonly PropertyInfo<int> DocTypeIDProperty = RegisterProperty<int>(p => p.DocTypeID, "Doc Type ID");
/// <summary>
/// Gets the Doc Type ID.
/// </summary>
/// <value>The Doc Type ID.</value>
protected int DocTypeID
{
get { return GetProperty(DocTypeIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SenderID"/> property.
/// </summary>
public static readonly PropertyInfo<int> SenderIDProperty = RegisterProperty<int>(p => p.SenderID, "Sender ID");
/// <summary>
/// Gets the Sender ID.
/// </summary>
/// <value>The Sender ID.</value>
protected int SenderID
{
get { return GetProperty(SenderIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RecipientID"/> property.
/// </summary>
public static readonly PropertyInfo<int> RecipientIDProperty = RegisterProperty<int>(p => p.RecipientID, "Recipient ID");
/// <summary>
/// Gets the Recipient ID.
/// </summary>
/// <value>The Recipient ID.</value>
protected int RecipientID
{
get { return GetProperty(RecipientIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocRef"/> property.
/// </summary>
public static readonly PropertyInfo<string> DocRefProperty = RegisterProperty<string>(p => p.DocRef, "Doc Ref", null);
/// <summary>
/// Gets the Doc Ref.
/// </summary>
/// <value>The Doc Ref.</value>
public string DocRef
{
get { return GetProperty(DocRefProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> DocDateProperty = RegisterProperty<SmartDate>(p => p.DocDate, "Doc Date");
/// <summary>
/// Gets the Doc Date.
/// </summary>
/// <value>The Doc Date.</value>
public string DocDate
{
get { return GetPropertyConvert<SmartDate, string>(DocDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Subject"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject");
/// <summary>
/// Gets the Subject.
/// </summary>
/// <value>The Subject.</value>
public string Subject
{
get { return GetProperty(SubjectProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocStatusID"/> property.
/// </summary>
public static readonly PropertyInfo<int> DocStatusIDProperty = RegisterProperty<int>(p => p.DocStatusID, "Doc Status ID");
/// <summary>
/// Gets the Doc Status ID.
/// </summary>
/// <value>The Doc Status ID.</value>
protected int DocStatusID
{
get { return GetProperty(DocStatusIDProperty); }
}
/// <summary>
/// Gets the Doc Class Name.
/// </summary>
/// <value>The Doc Class Name.</value>
public string DocClassName
{
get
{
var result = string.Empty;
if (DocClassNVL.GetDocClassNVL().ContainsKey(DocClassID))
result = DocClassNVL.GetDocClassNVL().GetItemByKey(DocClassID).Value;
return result;
}
}
/// <summary>
/// Gets the Doc Type Name.
/// </summary>
/// <value>The Doc Type Name.</value>
public string DocTypeName
{
get
{
var result = string.Empty;
if (DocTypeNVL.GetDocTypeNVL().ContainsKey(DocTypeID))
result = DocTypeNVL.GetDocTypeNVL().GetItemByKey(DocTypeID).Value;
return result;
}
}
/// <summary>
/// Gets the Sender Name.
/// </summary>
/// <value>The Sender Name.</value>
public string SenderName
{
get
{
var result = string.Empty;
if (UserNVL.GetUserNVL().ContainsKey(SenderID))
result = UserNVL.GetUserNVL().GetItemByKey(SenderID).Value;
return result;
}
}
/// <summary>
/// Gets the Recipient Name.
/// </summary>
/// <value>The Recipient Name.</value>
public string RecipientName
{
get
{
var result = string.Empty;
if (UserNVL.GetUserNVL().ContainsKey(RecipientID))
result = UserNVL.GetUserNVL().GetItemByKey(RecipientID).Value;
return result;
}
}
/// <summary>
/// Gets the Doc Status Name.
/// </summary>
/// <value>The Doc Status Name.</value>
public string DocStatusName
{
get
{
var result = string.Empty;
if (DocStatusNVL.GetDocStatusNVL().ContainsKey(DocStatusID))
result = DocStatusNVL.GetDocStatusNVL().GetItemByKey(DocStatusID).Value;
return result;
}
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="DocInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocInfo"/> object.</returns>
internal static DocInfo GetDocInfo(SafeDataReader dr)
{
DocInfo obj = new DocInfo();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocInfo"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocInfo()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Update properties on saved object event
/// <summary>
/// Existing <see cref="DocInfo"/> object is updated by <see cref="Doc"/> Saved event.
/// </summary>
internal static DocInfo LoadInfo(Doc doc)
{
var info = new DocInfo();
info.UpdatePropertiesOnSaved(doc);
return info;
}
/// <summary>
/// Properties on <see cref="DocInfo"/> object are updated by <see cref="Doc"/> Saved event.
/// </summary>
internal void UpdatePropertiesOnSaved(Doc doc)
{
LoadProperty(DocIDProperty, doc.DocID);
LoadProperty(DocClassIDProperty, doc.DocClassID);
LoadProperty(DocTypeIDProperty, doc.DocTypeID);
LoadProperty(SenderIDProperty, doc.SenderID);
LoadProperty(RecipientIDProperty, doc.RecipientID);
LoadProperty(DocRefProperty, doc.DocRef);
LoadProperty(DocDateProperty, (SmartDate)doc.DocDate);
LoadProperty(SubjectProperty, doc.Subject);
LoadProperty(DocStatusIDProperty, doc.DocStatusID);
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="DocInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocIDProperty, dr.GetInt32("DocID"));
LoadProperty(DocClassIDProperty, dr.GetInt32("DocClassID"));
LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID"));
LoadProperty(SenderIDProperty, dr.GetInt32("SenderID"));
LoadProperty(RecipientIDProperty, dr.GetInt32("RecipientID"));
LoadProperty(DocRefProperty, dr.IsDBNull("DocRef") ? null : dr.GetString("DocRef"));
LoadProperty(DocDateProperty, dr.GetSmartDate("DocDate", true));
LoadProperty(SubjectProperty, dr.GetString("Subject"));
LoadProperty(DocStatusIDProperty, dr.GetInt32("DocStatusID"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#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.Collections.Generic;
using System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
public abstract class HttpClientHandler_Proxy_Test : HttpClientHandlerTestBase
{
public HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { }
[Fact]
public async Task Dispose_HandlerWithProxy_ProxyNotDisposed()
{
var proxy = new TrackDisposalProxy();
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.UseProxy = true;
handler.Proxy = proxy;
using (HttpClient client = CreateHttpClient(handler))
{
Assert.Equal("hello", await client.GetStringAsync(uri));
}
}
}, async server =>
{
await server.HandleRequestAsync(content: "hello");
});
Assert.True(proxy.ProxyUsed);
Assert.False(proxy.Disposed);
}
[ActiveIssue(32809)]
[OuterLoop("Uses external server")]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[InlineData(AuthenticationSchemes.Ntlm, true, false)]
[InlineData(AuthenticationSchemes.Negotiate, true, false)]
[InlineData(AuthenticationSchemes.Basic, false, false)]
[InlineData(AuthenticationSchemes.Basic, true, false)]
[InlineData(AuthenticationSchemes.Digest, false, false)]
[InlineData(AuthenticationSchemes.Digest, true, false)]
[InlineData(AuthenticationSchemes.Ntlm, false, false)]
[InlineData(AuthenticationSchemes.Negotiate, false, false)]
[InlineData(AuthenticationSchemes.Basic, false, true)]
[InlineData(AuthenticationSchemes.Basic, true, true)]
[InlineData(AuthenticationSchemes.Digest, false, true)]
[InlineData(AuthenticationSchemes.Digest, true, true)]
public async Task AuthProxy__ValidCreds_ProxySendsRequestToServer(
AuthenticationSchemes proxyAuthScheme,
bool secureServer,
bool proxyClosesConnectionAfterFirst407Response)
{
if (PlatformDetection.IsFedora && IsCurlHandler)
{
// CurlHandler seems unstable on Fedora26 and returns error
// "System.Net.Http.CurlException : Failure when receiving data from the peer".
return;
}
if (PlatformDetection.IsWindowsNanoServer && IsWinHttpHandler && proxyAuthScheme == AuthenticationSchemes.Digest)
{
// WinHTTP doesn't support Digest very well and is disabled on Nano.
return;
}
if (!PlatformDetection.IsWindows &&
(proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm))
{
// CI machines don't have GSSAPI module installed and will fail with error from
// System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle():
// "GSSAPI operation failed with error - An invalid status code was supplied
// Configuration file does not specify default realm)."
return;
}
if (IsCurlHandler && proxyAuthScheme != AuthenticationSchemes.Basic)
{
// Issue #27870 curl HttpHandler can only do basic auth to proxy.
return;
}
Uri serverUri = secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer;
var options = new LoopbackProxyServer.Options
{ AuthenticationSchemes = proxyAuthScheme,
ConnectionCloseAfter407 = proxyClosesConnectionAfterFirst407Response
};
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.Proxy = new WebProxy(proxyServer.Uri);
handler.Proxy.Credentials = new NetworkCredential("username", "password");
using (HttpResponseMessage response = await client.GetAsync(serverUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
}
[OuterLoop("Uses external server")]
[ConditionalFact]
public void Proxy_UseEnvironmentVariableToSetSystemProxy_RequestGoesThruProxy()
{
if (!UseSocketsHttpHandler)
{
throw new SkipTestException("Test needs SocketsHttpHandler");
}
RemoteExecutor.Invoke(async (useSocketsHttpHandlerString, useHttp2String) =>
{
var options = new LoopbackProxyServer.Options { AddViaRequestHeader = true };
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
Environment.SetEnvironmentVariable("http_proxy", proxyServer.Uri.AbsoluteUri.ToString());
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string body = await response.Content.ReadAsStringAsync();
Assert.Contains(proxyServer.ViaHeader, body);
}
return RemoteExecutor.SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
[ActiveIssue(32809)]
[OuterLoop("Uses external server")]
[Theory]
[MemberData(nameof(CredentialsForProxy))]
public async Task Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
var options = new LoopbackProxyServer.Options
{ AuthenticationSchemes = creds != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None
};
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
const string BasicAuth = "Basic";
if (wrapCredsInCache)
{
Assert.IsAssignableFrom<NetworkCredential>(creds);
var cache = new CredentialCache();
cache.Add(proxyServer.Uri, BasicAuth, (NetworkCredential)creds);
creds = cache;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = creds };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
if (options.AuthenticationSchemes != AuthenticationSchemes.None)
{
NetworkCredential nc = creds?.GetCredential(proxyServer.Uri, BasicAuth);
Assert.NotNull(nc);
string expectedAuth =
string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
$"{nc.Domain}\\{nc.UserName}:{nc.Password}";
_output.WriteLine($"expectedAuth={expectedAuth}");
string expectedAuthHash = Convert.ToBase64String(Encoding.UTF8.GetBytes(expectedAuth));
// Check last request to proxy server. CurlHandler will use pre-auth for Basic proxy auth,
// so there might only be 1 request received by the proxy server. Other handlers won't use
// pre-auth for proxy so there would be 2 requests.
int requestCount = proxyServer.Requests.Count;
_output.WriteLine($"proxyServer.Requests.Count={requestCount}");
Assert.Equal(BasicAuth, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueScheme);
Assert.Equal(expectedAuthHash, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueToken);
}
}
}
}
}
[OuterLoop("Uses external server")]
[Theory]
[MemberData(nameof(BypassedProxies))]
public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = proxy;
using (HttpClient client = CreateHttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode()
{
var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic };
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new WebProxy(proxyServer.Uri);
using (HttpClient client = CreateHttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode);
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)]
public async Task Proxy_SslProxyUnsupported_Throws()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.Proxy = new WebProxy("https://" + Guid.NewGuid().ToString("N"));
Type expectedType = IsNetfxHandler || UseSocketsHttpHandler ?
typeof(NotSupportedException) :
typeof(HttpRequestException);
await Assert.ThrowsAsync(expectedType, () => client.GetAsync("http://" + Guid.NewGuid().ToString("N")));
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task Proxy_SendSecureRequestThruProxy_ConnectTunnelUsed()
{
if (PlatformDetection.IsFedora && IsCurlHandler)
{
// CurlHandler seems unstable on Fedora26 and returns error
// "System.Net.Http.CurlException : Failure when receiving data from the peer".
return;
}
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create())
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new WebProxy(proxyServer.Uri);
using (HttpClient client = CreateHttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
_output.WriteLine($"Proxy request line: {proxyServer.Requests[0].RequestLine}");
Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine);
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
public async Task ProxyAuth_Digest_Succeeds()
{
if (IsCurlHandler)
{
// Issue #27870 CurlHandler can only do basic auth to proxy.
return;
}
const string expectedUsername = "testusername";
const string expectedPassword = "testpassword";
const string authHeader = "Proxy-Authenticate: Digest realm=\"NetCore\", nonce=\"PwOnWgAAAAAAjnbW438AAJSQi1kAAAAA\", qop=\"auth\", stale=false\r\n";
LoopbackServer.Options options = new LoopbackServer.Options { IsProxy = true, Username = expectedUsername, Password = expectedPassword };
var proxyCreds = new NetworkCredential(expectedUsername, expectedPassword);
await LoopbackServer.CreateServerAsync(async (proxyServer, proxyUrl) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.Proxy = new WebProxy(proxyUrl) { Credentials = proxyCreds };
// URL does not matter. We will get response from "proxy" code below.
Task<HttpResponseMessage> clientTask = client.GetAsync($"http://notarealserver.com/");
// Send Digest challenge.
Task<List<string>> serverTask = proxyServer.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.ProxyAuthenticationRequired, authHeader);
if (clientTask == await Task.WhenAny(clientTask, serverTask).TimeoutAfter(TestHelper.PassingTestTimeoutMilliseconds))
{
// Client task shouldn't have completed successfully; propagate failure.
Assert.NotEqual(TaskStatus.RanToCompletion, clientTask.Status);
await clientTask;
}
// Verify user & password.
serverTask = proxyServer.AcceptConnectionPerformAuthenticationAndCloseAsync("");
await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask }, TestHelper.PassingTestTimeoutMilliseconds);
Assert.Equal(HttpStatusCode.OK, clientTask.Result.StatusCode);
}
}, options);
}
public static IEnumerable<object[]> BypassedProxies()
{
yield return new object[] { null };
yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) };
}
public static IEnumerable<object[]> CredentialsForProxy()
{
yield return new object[] { null, false };
foreach (bool wrapCredsInCache in new[] { true, false })
{
yield return new object[] { new NetworkCredential("username", "password"), wrapCredsInCache };
yield return new object[] { new NetworkCredential("username", "password", "domain"), wrapCredsInCache };
}
}
private sealed class TrackDisposalProxy : IWebProxy, IDisposable
{
public bool Disposed;
public bool ProxyUsed;
public void Dispose() => Disposed = true;
public Uri GetProxy(Uri destination)
{
ProxyUsed = true;
return null;
}
public bool IsBypassed(Uri host)
{
ProxyUsed = true;
return true;
}
public ICredentials Credentials { get => null; set { } }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
public class Signature
{
private string _id;
private SignedInfo _signedInfo;
private byte[] _signatureValue;
private string _signatureValueId;
private KeyInfo _keyInfo;
private IList _embeddedObjects;
private readonly CanonicalXmlNodeList _referencedItems;
private SignedXml _signedXml = null;
internal SignedXml SignedXml
{
get { return _signedXml; }
set { _signedXml = value; }
}
//
// public constructors
//
public Signature()
{
_embeddedObjects = new ArrayList();
_referencedItems = new CanonicalXmlNodeList();
}
//
// public properties
//
public string Id
{
get { return _id; }
set { _id = value; }
}
public SignedInfo SignedInfo
{
get { return _signedInfo; }
set
{
_signedInfo = value;
if (SignedXml != null && _signedInfo != null)
_signedInfo.SignedXml = SignedXml;
}
}
public byte[] SignatureValue
{
get { return _signatureValue; }
set { _signatureValue = value; }
}
public KeyInfo KeyInfo
{
get
{
if (_keyInfo == null)
_keyInfo = new KeyInfo();
return _keyInfo;
}
set { _keyInfo = value; }
}
public IList ObjectList
{
get { return _embeddedObjects; }
set { _embeddedObjects = value; }
}
internal CanonicalXmlNodeList ReferencedItems
{
get { return _referencedItems; }
}
//
// public methods
//
public XmlElement GetXml()
{
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true;
return GetXml(document);
}
internal XmlElement GetXml(XmlDocument document)
{
// Create the Signature
XmlElement signatureElement = (XmlElement)document.CreateElement("Signature", SignedXml.XmlDsigNamespaceUrl);
if (!string.IsNullOrEmpty(_id))
signatureElement.SetAttribute("Id", _id);
// Add the SignedInfo
if (_signedInfo == null)
throw new CryptographicException(SR.Cryptography_Xml_SignedInfoRequired);
signatureElement.AppendChild(_signedInfo.GetXml(document));
// Add the SignatureValue
if (_signatureValue == null)
throw new CryptographicException(SR.Cryptography_Xml_SignatureValueRequired);
XmlElement signatureValueElement = document.CreateElement("SignatureValue", SignedXml.XmlDsigNamespaceUrl);
signatureValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(_signatureValue)));
if (!string.IsNullOrEmpty(_signatureValueId))
signatureValueElement.SetAttribute("Id", _signatureValueId);
signatureElement.AppendChild(signatureValueElement);
// Add the KeyInfo
if (KeyInfo.Count > 0)
signatureElement.AppendChild(KeyInfo.GetXml(document));
// Add the Objects
foreach (object obj in _embeddedObjects)
{
DataObject dataObj = obj as DataObject;
if (dataObj != null)
{
signatureElement.AppendChild(dataObj.GetXml(document));
}
}
return signatureElement;
}
public void LoadXml(XmlElement value)
{
// Make sure we don't get passed null
if (value == null)
throw new ArgumentNullException(nameof(value));
// Signature
XmlElement signatureElement = value;
if (!signatureElement.LocalName.Equals("Signature"))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature");
// Id attribute -- optional
_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl);
if (!Utils.VerifyAttributes(signatureElement, "Id"))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature");
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
int expectedChildNodes = 0;
// SignedInfo
XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm);
if (signedInfoNodes == null || signedInfoNodes.Count == 0 || signedInfoNodes.Count > 1)
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo");
XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement;
expectedChildNodes += signedInfoNodes.Count;
SignedInfo = new SignedInfo();
SignedInfo.LoadXml(signedInfoElement);
// SignatureValue
XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm);
if (signatureValueNodes == null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1)
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue");
XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement;
expectedChildNodes += signatureValueNodes.Count;
_signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText));
_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl);
if (!Utils.VerifyAttributes(signatureValueElement, "Id"))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue");
// KeyInfo - optional single element
XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);
_keyInfo = new KeyInfo();
if (keyInfoNodes != null)
{
if (keyInfoNodes.Count > 1)
{
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo");
}
foreach (XmlNode node in keyInfoNodes)
{
XmlElement keyInfoElement = node as XmlElement;
if (keyInfoElement != null)
_keyInfo.LoadXml(keyInfoElement);
}
expectedChildNodes += keyInfoNodes.Count;
}
// Object - zero or more elements allowed
XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);
_embeddedObjects.Clear();
if (objectNodes != null)
{
foreach (XmlNode node in objectNodes)
{
XmlElement objectElement = node as XmlElement;
if (objectElement != null)
{
DataObject dataObj = new DataObject();
dataObj.LoadXml(objectElement);
_embeddedObjects.Add(dataObj);
}
}
expectedChildNodes += objectNodes.Count;
}
// Select all elements that have Id attributes
XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);
if (nodeList != null)
{
foreach (XmlNode node in nodeList)
{
_referencedItems.Add(node);
}
}
// Verify that there aren't any extra nodes that aren't allowed
if (signatureElement.SelectNodes("*").Count != expectedChildNodes)
{
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature");
}
}
public void AddObject(DataObject dataObject)
{
_embeddedObjects.Add(dataObject);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace ParquetColumnTests.Io
{
using System.Collections.Generic;
using Column.Page.Mem;
using ParquetSharp.Column;
using ParquetSharp.Column.Impl;
using ParquetSharp.Example.Data;
using ParquetSharp.Example.Data.Simple.Convert;
using ParquetSharp.Filter2.Compat;
using ParquetSharp.IO;
using ParquetSharp.IO.Api;
using Xunit;
using static ParquetSharp.Example.Paper;
using static ParquetSharp.Filter.AndRecordFilter;
using static ParquetSharp.Filter.ColumnPredicates;
using static ParquetSharp.Filter.ColumnRecordFilter;
using static ParquetSharp.Filter.OrRecordFilter;
using static ParquetSharp.Filter.PagedRecordFilter;
using static ParquetSharp.Filter.NotRecordFilter;
public class TestFiltered
{
/* Class that : applyFunction filter for long. Checks for long greater than 15. */
public class LongGreaterThan15Predicate : LongPredicateFunction
{
public bool functionToApply(long input)
{
return input > 15;
}
}
/* Class that : applyFunction filter for string. Checks for string ending in 'A'. */
public class StringEndsWithAPredicate : PredicateFunction<string>
{
public bool functionToApply(string input)
{
return input.EndsWith("A");
}
}
private List<Group> readAll(RecordReader<Group> reader)
{
List<Group> result = new List<Group>();
Group g;
while ((g = reader.read()) != null)
{
result.Add(g);
}
return result;
}
private void readOne(RecordReader<Group> reader, string message, Group expected)
{
List<Group> result = readAll(reader);
Assert.Equal(1, result.Count);
Assert.Equal(expected.ToString(), result[0].ToString());
}
[Fact]
public void testFilterOnInteger()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 1);
// Get first record
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter, FilterCompat.get(column("DocId", equalTo(10L))));
readOne(recordReader, "r2 filtered out", r1);
// Get second record
recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("DocId", equalTo(20L))));
readOne(recordReader, "r1 filtered out", r2);
}
[Fact]
public void testApplyFunctionFilterOnLong()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 1);
// Get first record
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("DocId", equalTo(10L))));
readOne(recordReader, "r2 filtered out", r1);
// Get second record
recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("DocId", applyFunctionToLong(new LongGreaterThan15Predicate()))));
readOne(recordReader, "r1 filtered out", r2);
}
[Fact]
public void testFilterOnString()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 1);
// First try matching against the A url in record 1
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("Name.Url", equalTo("http://A"))));
readOne(recordReader, "r2 filtered out", r1);
// Second try matching against the B url in record 1 - it should fail as we only match
// against the first instance of a
recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("Name.Url", equalTo("http://B"))));
List<Group> all = readAll(recordReader);
Assert.Equal(0, all.Count);
// Finally try matching against the C url in record 2
recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("Name.Url", equalTo("http://C"))));
readOne(recordReader, "r1 filtered out", r2);
}
[Fact]
public void testApplyFunctionFilterOnString()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 1);
// First try matching against the A url in record 1
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("Name.Url", applyFunctionToString(new StringEndsWithAPredicate()))));
readOne(recordReader, "r2 filtered out", r1);
// Second try matching against the B url in record 1 - it should fail as we only match
// against the first instance of a
recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("Name.Url", equalTo("http://B"))));
List<Group> all = readAll(recordReader);
Assert.Equal(0, all.Count);
// Finally try matching against the C url in record 2
recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(column("Name.Url", equalTo("http://C"))));
readOne(recordReader, "r1 filtered out", r2);
}
[Fact]
public void testPaged()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 6);
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(page(4, 4)));
List<Group> all = readAll(recordReader);
Assert.Equal(4, all.Count);
for (int i = 0; i < all.Count; i++)
{
Assert.Equal((i % 2 == 0 ? r2 : r1).ToString(), all[i].ToString());
}
}
[Fact]
public void testFilteredAndPaged()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 8);
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(and(column("DocId", equalTo(10L)), page(2, 4))));
List<Group> all = readAll(recordReader);
Assert.Equal(4, all.Count);
for (int i = 0; i < all.Count; i++)
{
Assert.Equal(r1.ToString(), all[i].ToString());
}
}
[Fact]
public void testFilteredOrPaged()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 8);
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(or(column("DocId", equalTo(10L)),
column("DocId", equalTo(20L)))));
List<Group> all = readAll(recordReader);
Assert.Equal(16, all.Count);
for (int i = 0; i < all.Count / 2; i++)
{
Assert.Equal(r1.ToString(), all[2 * i].ToString());
Assert.Equal(r2.ToString(), all[2 * i + 1].ToString());
}
}
[Fact]
public void testFilteredNotPaged()
{
MessageColumnIO columnIO = new ColumnIOFactory(true).getColumnIO(schema);
MemPageStore memPageStore = writeTestRecords(columnIO, 8);
RecordMaterializer<Group> recordConverter = new GroupRecordConverter(schema);
RecordReaderImplementation<Group> recordReader = (RecordReaderImplementation<Group>)
columnIO.getRecordReader(memPageStore, recordConverter,
FilterCompat.get(not(column("DocId", equalTo(10L)))));
List<Group> all = readAll(recordReader);
Assert.Equal(8, all.Count);
for (int i = 0; i < all.Count; i++)
{
Assert.Equal(r2.ToString(), all[i].ToString());
}
}
private MemPageStore writeTestRecords(MessageColumnIO columnIO, int number)
{
MemPageStore memPageStore = new MemPageStore(number * 2);
ColumnWriteStoreV1 columns = new ColumnWriteStoreV1(
memPageStore,
ParquetProperties.builder()
.withPageSize(800)
.withDictionaryEncoding(false)
.build());
RecordConsumer recordWriter = columnIO.getRecordWriter(columns);
GroupWriter groupWriter = new GroupWriter(recordWriter, schema);
for (int i = 0; i < number; i++)
{
groupWriter.write(r1);
groupWriter.write(r2);
}
recordWriter.flush();
columns.flush();
return memPageStore;
}
}
}
| |
namespace SLeek
{
partial class FriendsConsole
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lbxFriends = new System.Windows.Forms.ListBox();
this.lblFriendName = new System.Windows.Forms.Label();
this.btnIM = new System.Windows.Forms.Button();
this.btnProfile = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnOfferTeleport = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.chkSeeMeOnline = new System.Windows.Forms.CheckBox();
this.chkSeeMeOnMap = new System.Windows.Forms.CheckBox();
this.chkModifyMyObjects = new System.Windows.Forms.CheckBox();
this.timInitDelay = new System.Windows.Forms.Timer(this.components);
this.btnPay = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// lbxFriends
//
this.lbxFriends.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.lbxFriends.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lbxFriends.IntegralHeight = false;
this.lbxFriends.ItemHeight = 20;
this.lbxFriends.Location = new System.Drawing.Point(3, 3);
this.lbxFriends.Name = "lbxFriends";
this.lbxFriends.Size = new System.Drawing.Size(200, 460);
this.lbxFriends.Sorted = true;
this.lbxFriends.TabIndex = 0;
this.lbxFriends.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.lbxFriends_DrawItem);
this.lbxFriends.SelectedIndexChanged += new System.EventHandler(this.lbxFriends_SelectedIndexChanged);
//
// lblFriendName
//
this.lblFriendName.AutoSize = true;
this.lblFriendName.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblFriendName.Location = new System.Drawing.Point(6, 17);
this.lblFriendName.Name = "lblFriendName";
this.lblFriendName.Size = new System.Drawing.Size(120, 13);
this.lblFriendName.TabIndex = 1;
this.lblFriendName.Text = "Getting friends list...";
//
// btnIM
//
this.btnIM.Enabled = false;
this.btnIM.Location = new System.Drawing.Point(6, 47);
this.btnIM.Name = "btnIM";
this.btnIM.Size = new System.Drawing.Size(75, 23);
this.btnIM.TabIndex = 2;
this.btnIM.Text = "IM";
this.btnIM.UseVisualStyleBackColor = true;
this.btnIM.Click += new System.EventHandler(this.btnIM_Click);
//
// btnProfile
//
this.btnProfile.Enabled = false;
this.btnProfile.Location = new System.Drawing.Point(87, 46);
this.btnProfile.Name = "btnProfile";
this.btnProfile.Size = new System.Drawing.Size(75, 23);
this.btnProfile.TabIndex = 3;
this.btnProfile.Text = "Profile";
this.btnProfile.UseVisualStyleBackColor = true;
this.btnProfile.Click += new System.EventHandler(this.btnProfile_Click);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.btnPay);
this.groupBox1.Controls.Add(this.btnOfferTeleport);
this.groupBox1.Controls.Add(this.lblFriendName);
this.groupBox1.Controls.Add(this.btnProfile);
this.groupBox1.Controls.Add(this.btnIM);
this.groupBox1.Location = new System.Drawing.Point(209, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(470, 76);
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
//
// btnOfferTeleport
//
this.btnOfferTeleport.Enabled = false;
this.btnOfferTeleport.Location = new System.Drawing.Point(168, 46);
this.btnOfferTeleport.Name = "btnOfferTeleport";
this.btnOfferTeleport.Size = new System.Drawing.Size(112, 23);
this.btnOfferTeleport.TabIndex = 4;
this.btnOfferTeleport.Text = "Offer Teleport";
this.btnOfferTeleport.UseVisualStyleBackColor = true;
this.btnOfferTeleport.Click += new System.EventHandler(this.btnOfferTeleport_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(209, 92);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(81, 13);
this.label1.TabIndex = 5;
this.label1.Text = "This friend can:";
//
// chkSeeMeOnline
//
this.chkSeeMeOnline.AutoSize = true;
this.chkSeeMeOnline.Enabled = false;
this.chkSeeMeOnline.Location = new System.Drawing.Point(218, 117);
this.chkSeeMeOnline.Name = "chkSeeMeOnline";
this.chkSeeMeOnline.Size = new System.Drawing.Size(125, 17);
this.chkSeeMeOnline.TabIndex = 6;
this.chkSeeMeOnline.Text = "See my online status";
this.chkSeeMeOnline.UseVisualStyleBackColor = true;
this.chkSeeMeOnline.CheckedChanged += new System.EventHandler(this.chkSeeMeOnline_CheckedChanged);
//
// chkSeeMeOnMap
//
this.chkSeeMeOnMap.AutoSize = true;
this.chkSeeMeOnMap.Enabled = false;
this.chkSeeMeOnMap.Location = new System.Drawing.Point(218, 140);
this.chkSeeMeOnMap.Name = "chkSeeMeOnMap";
this.chkSeeMeOnMap.Size = new System.Drawing.Size(118, 17);
this.chkSeeMeOnMap.TabIndex = 7;
this.chkSeeMeOnMap.Text = "See me on the map";
this.chkSeeMeOnMap.UseVisualStyleBackColor = true;
this.chkSeeMeOnMap.CheckedChanged += new System.EventHandler(this.chkSeeMeOnMap_CheckedChanged);
//
// chkModifyMyObjects
//
this.chkModifyMyObjects.AutoSize = true;
this.chkModifyMyObjects.Enabled = false;
this.chkModifyMyObjects.Location = new System.Drawing.Point(218, 163);
this.chkModifyMyObjects.Name = "chkModifyMyObjects";
this.chkModifyMyObjects.Size = new System.Drawing.Size(113, 17);
this.chkModifyMyObjects.TabIndex = 8;
this.chkModifyMyObjects.Text = "Modify my objects";
this.chkModifyMyObjects.UseVisualStyleBackColor = true;
this.chkModifyMyObjects.CheckedChanged += new System.EventHandler(this.chkModifyMyObjects_CheckedChanged);
//
// timInitDelay
//
this.timInitDelay.Enabled = true;
this.timInitDelay.Interval = 3000;
this.timInitDelay.Tick += new System.EventHandler(this.timInitDelay_Tick);
//
// btnPay
//
this.btnPay.Enabled = false;
this.btnPay.Location = new System.Drawing.Point(286, 46);
this.btnPay.Name = "btnPay";
this.btnPay.Size = new System.Drawing.Size(75, 23);
this.btnPay.TabIndex = 5;
this.btnPay.Text = "Pay...";
this.btnPay.UseVisualStyleBackColor = true;
this.btnPay.Click += new System.EventHandler(this.btnPay_Click);
//
// FriendsConsole
//
this.Controls.Add(this.chkModifyMyObjects);
this.Controls.Add(this.chkSeeMeOnMap);
this.Controls.Add(this.chkSeeMeOnline);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.lbxFriends);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "FriendsConsole";
this.Size = new System.Drawing.Size(682, 466);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox lbxFriends;
private System.Windows.Forms.Label lblFriendName;
private System.Windows.Forms.Button btnIM;
private System.Windows.Forms.Button btnProfile;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox chkSeeMeOnline;
private System.Windows.Forms.CheckBox chkSeeMeOnMap;
private System.Windows.Forms.CheckBox chkModifyMyObjects;
private System.Windows.Forms.Button btnOfferTeleport;
private System.Windows.Forms.Timer timInitDelay;
private System.Windows.Forms.Button btnPay;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Runtime.InteropServices;
using System.Management.Automation.ComInterop;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;
using COM = System.Runtime.InteropServices.ComTypes;
// Stops compiler from warning about unknown warnings. Prefast warning numbers are not recognized by C# compiler
#pragma warning disable 1634, 1691
namespace System.Management.Automation
{
/// <summary>
/// Defines a utility class that is used by COM adapter.
/// </summary>
internal class ComUtil
{
// HResult error code '-2147352573' - Member not found.
internal const int DISP_E_MEMBERNOTFOUND = unchecked((int)0x80020003);
// HResult error code '-2147352570' - Unknown Name.
internal const int DISP_E_UNKNOWNNAME = unchecked((int)0x80020006);
// HResult error code '-2147319765' - Element not found.
internal const int TYPE_E_ELEMENTNOTFOUND = unchecked((int)0x8002802b);
/// <summary>
/// Gets Method Signature from FuncDesc describing the method.
/// </summary>
/// <param name="typeinfo">ITypeInfo interface of the object.</param>
/// <param name="funcdesc">FuncDesc which defines the method.</param>
/// <param name="isPropertyPut">True if this is a property put; these properties take their return type from their first parameter.</param>
/// <returns>Signature of the method.</returns>
internal static string GetMethodSignatureFromFuncDesc(COM.ITypeInfo typeinfo, COM.FUNCDESC funcdesc, bool isPropertyPut)
{
StringBuilder builder = new StringBuilder();
string name = GetNameFromFuncDesc(typeinfo, funcdesc);
if (!isPropertyPut)
{
// First get the string for return type.
string retstring = GetStringFromTypeDesc(typeinfo, funcdesc.elemdescFunc.tdesc);
builder.Append(retstring + " ");
}
// Append the function name
builder.Append(name);
builder.Append(" (");
IntPtr ElementDescriptionArrayPtr = funcdesc.lprgelemdescParam;
int ElementDescriptionSize = Marshal.SizeOf<COM.ELEMDESC>();
for (int i = 0; i < funcdesc.cParams; i++)
{
COM.ELEMDESC ElementDescription;
int ElementDescriptionArrayByteOffset;
IntPtr ElementDescriptionPointer;
ElementDescription = new COM.ELEMDESC();
ElementDescriptionArrayByteOffset = i * ElementDescriptionSize;
// Disable PRefast warning for converting to int32 and converting back into intptr.
// Code below takes into account 32 bit vs 64 bit conversions
#pragma warning disable 56515
if (IntPtr.Size == 4)
{
ElementDescriptionPointer = (IntPtr)(ElementDescriptionArrayPtr.ToInt32() + ElementDescriptionArrayByteOffset);
}
else
{
ElementDescriptionPointer = (IntPtr)(ElementDescriptionArrayPtr.ToInt64() + ElementDescriptionArrayByteOffset);
}
#pragma warning restore 56515
ElementDescription = Marshal.PtrToStructure<COM.ELEMDESC>(ElementDescriptionPointer);
string paramstring = GetStringFromTypeDesc(typeinfo, ElementDescription.tdesc);
if (i == 0 && isPropertyPut) // use the type of the first argument as the return type
{
builder.Insert(0, paramstring + " ");
}
else
{
builder.Append(paramstring);
if (i < funcdesc.cParams - 1)
{
builder.Append(", ");
}
}
}
builder.Append(")");
return builder.ToString();
}
/// <summary>
/// Gets the name of the method or property defined by funcdesc.
/// </summary>
/// <param name="typeinfo">ITypeInfo interface of the type.</param>
/// <param name="funcdesc">FuncDesc of property of method.</param>
/// <returns>Name of the method or property.</returns>
internal static string GetNameFromFuncDesc(COM.ITypeInfo typeinfo, COM.FUNCDESC funcdesc)
{
// Get the method or property name.
string strName, strDoc, strHelp;
int id;
typeinfo.GetDocumentation(funcdesc.memid, out strName, out strDoc, out id, out strHelp);
return strName;
}
/// <summary>
/// Gets the name of the custom type defined in the type library.
/// </summary>
/// <param name="typeinfo">ITypeInfo interface of the type.</param>
/// <param name="refptr">Reference to the custom type.</param>
/// <returns>Name of the custom type.</returns>
private static string GetStringFromCustomType(COM.ITypeInfo typeinfo, IntPtr refptr)
{
COM.ITypeInfo custtypeinfo;
int reftype = unchecked((int)(long)refptr); // note that we cast to long first to prevent overflows; this cast is OK since we are only interested in the lower word
typeinfo.GetRefTypeInfo(reftype, out custtypeinfo);
if (custtypeinfo != null)
{
string strName, strDoc, strHelp;
int id;
custtypeinfo.GetDocumentation(-1, out strName, out strDoc, out id, out strHelp);
return strName;
}
return "UnknownCustomtype";
}
// Disable obsolete warning about VarEnum in CoreCLR
#pragma warning disable 618
/// <summary>
/// This function gets a string representation of the Type Descriptor
/// This is used in generating signature for Properties and Methods.
/// </summary>
/// <param name="typeinfo">Reference to the type info to which the type descriptor belongs.</param>
/// <param name="typedesc">Reference to type descriptor which is being converted to string from.</param>
/// <returns>String representation of the type descriptor.</returns>
private static string GetStringFromTypeDesc(COM.ITypeInfo typeinfo, COM.TYPEDESC typedesc)
{
if ((VarEnum)typedesc.vt == VarEnum.VT_PTR)
{
COM.TYPEDESC refdesc = Marshal.PtrToStructure<COM.TYPEDESC>(typedesc.lpValue);
return GetStringFromTypeDesc(typeinfo, refdesc);
}
if ((VarEnum)typedesc.vt == VarEnum.VT_SAFEARRAY)
{
COM.TYPEDESC refdesc = Marshal.PtrToStructure<COM.TYPEDESC>(typedesc.lpValue);
return "SAFEARRAY(" + GetStringFromTypeDesc(typeinfo, refdesc) + ")";
}
if ((VarEnum)typedesc.vt == VarEnum.VT_USERDEFINED)
{
return GetStringFromCustomType(typeinfo, typedesc.lpValue);
}
switch ((VarEnum)typedesc.vt)
{
case VarEnum.VT_I1:
return "char";
case VarEnum.VT_I2:
return "short";
case VarEnum.VT_I4:
case VarEnum.VT_INT:
case VarEnum.VT_HRESULT:
return "int";
case VarEnum.VT_I8:
return "int64";
case VarEnum.VT_R4:
return "float";
case VarEnum.VT_R8:
return "double";
case VarEnum.VT_UI1:
return "byte";
case VarEnum.VT_UI2:
return "ushort";
case VarEnum.VT_UI4:
case VarEnum.VT_UINT:
return "uint";
case VarEnum.VT_UI8:
return "uint64";
case VarEnum.VT_BSTR:
case VarEnum.VT_LPSTR:
case VarEnum.VT_LPWSTR:
return "string";
case VarEnum.VT_DATE:
return "Date";
case VarEnum.VT_BOOL:
return "bool";
case VarEnum.VT_CY:
return "currency";
case VarEnum.VT_DECIMAL:
return "decimal";
case VarEnum.VT_CLSID:
return "clsid";
case VarEnum.VT_DISPATCH:
return "IDispatch";
case VarEnum.VT_UNKNOWN:
return "IUnknown";
case VarEnum.VT_VARIANT:
return "Variant";
case VarEnum.VT_VOID:
return "void";
case VarEnum.VT_ARRAY:
return "object[]";
case VarEnum.VT_EMPTY:
return string.Empty;
default:
return "Unknown!";
}
}
/// <summary>
/// Determine .net type for the given type descriptor.
/// </summary>
/// <param name="typedesc">COM type descriptor to convert.</param>
/// <returns>Type represented by the typedesc.</returns>
internal static Type GetTypeFromTypeDesc(COM.TYPEDESC typedesc)
{
VarEnum vt = (VarEnum)typedesc.vt;
return VarEnumSelector.GetTypeForVarEnum(vt);
}
#pragma warning restore 618
/// <summary>
/// Converts a FuncDesc out of GetFuncDesc into a MethodInformation.
/// </summary>
private static ComMethodInformation GetMethodInformation(COM.FUNCDESC funcdesc, bool skipLastParameter)
{
Type returntype = GetTypeFromTypeDesc(funcdesc.elemdescFunc.tdesc);
ParameterInformation[] parameters = GetParameterInformation(funcdesc, skipLastParameter);
bool hasOptional = false;
foreach (ParameterInformation p in parameters)
{
if (p.isOptional)
{
hasOptional = true;
break;
}
}
return new ComMethodInformation(false, hasOptional, parameters, returntype, funcdesc.memid, funcdesc.invkind);
}
/// <summary>
/// Obtains the parameter information for a given FuncDesc.
/// </summary>
internal static ParameterInformation[] GetParameterInformation(COM.FUNCDESC funcdesc, bool skipLastParameter)
{
int cParams = funcdesc.cParams;
if (skipLastParameter)
{
Diagnostics.Assert(cParams > 0, "skipLastParameter is only true for property setters where there is at least one parameter");
cParams--;
}
ParameterInformation[] parameters = new ParameterInformation[cParams];
IntPtr ElementDescriptionArrayPtr = funcdesc.lprgelemdescParam;
int ElementDescriptionSize = Marshal.SizeOf<COM.ELEMDESC>();
for (int i = 0; i < cParams; i++)
{
COM.ELEMDESC ElementDescription;
int ElementDescriptionArrayByteOffset;
IntPtr ElementDescriptionPointer;
bool fOptional = false;
ElementDescription = new COM.ELEMDESC();
ElementDescriptionArrayByteOffset = i * ElementDescriptionSize;
// Disable PRefast warning for converting to int32 and converting back into intptr.
// Code below takes into account 32 bit vs 64 bit conversions
#pragma warning disable 56515
if (IntPtr.Size == 4)
{
ElementDescriptionPointer = (IntPtr)(ElementDescriptionArrayPtr.ToInt32() + ElementDescriptionArrayByteOffset);
}
else
{
ElementDescriptionPointer = (IntPtr)(ElementDescriptionArrayPtr.ToInt64() + ElementDescriptionArrayByteOffset);
}
#pragma warning enable 56515
ElementDescription = Marshal.PtrToStructure<COM.ELEMDESC>(ElementDescriptionPointer);
// get the type of parameter
Type type = ComUtil.GetTypeFromTypeDesc(ElementDescription.tdesc);
object defaultvalue = null;
// check is this parameter is optional.
if ((ElementDescription.desc.paramdesc.wParamFlags & COM.PARAMFLAG.PARAMFLAG_FOPT) != 0)
{
fOptional = true;
defaultvalue = Type.Missing;
}
bool fByRef = (ElementDescription.desc.paramdesc.wParamFlags & COM.PARAMFLAG.PARAMFLAG_FOUT) != 0;
parameters[i] = new ParameterInformation(type, fOptional, defaultvalue, fByRef);
}
return parameters;
}
/// <summary>
/// Converts a MethodBase[] into a MethodInformation[]
/// </summary>
/// <returns>The ComMethodInformation[] corresponding to methods.</returns>
internal static ComMethodInformation[] GetMethodInformationArray(COM.ITypeInfo typeInfo, Collection<int> methods, bool skipLastParameters)
{
int methodCount = methods.Count;
int count = 0;
ComMethodInformation[] returnValue = new ComMethodInformation[methodCount];
foreach (int index in methods)
{
IntPtr pFuncDesc;
typeInfo.GetFuncDesc(index, out pFuncDesc);
COM.FUNCDESC funcdesc = Marshal.PtrToStructure<COM.FUNCDESC>(pFuncDesc);
returnValue[count++] = ComUtil.GetMethodInformation(funcdesc, skipLastParameters);
typeInfo.ReleaseFuncDesc(pFuncDesc);
}
return returnValue;
}
}
/// <summary>
/// Defines an enumerator that represent a COM collection object.
/// </summary>
internal class ComEnumerator : IEnumerator
{
private COM.IEnumVARIANT _enumVariant;
private object[] _element;
private ComEnumerator(COM.IEnumVARIANT enumVariant)
{
_enumVariant = enumVariant;
_element = new object[1];
}
public object Current
{
get { return _element[0]; }
}
public bool MoveNext()
{
_element[0] = null;
int result = _enumVariant.Next(1, _element, IntPtr.Zero);
return result == 0;
}
public void Reset()
{
_element[0] = null;
_enumVariant.Reset();
}
/// <summary>
/// Try to create an enumerator for a COM object.
/// </summary>
/// <returns>
/// A 'ComEnumerator' instance, or null if we cannot create an enumerator for the COM object.
/// </returns>
internal static ComEnumerator Create(object comObject)
{
if (comObject == null || !comObject.GetType().IsCOMObject) { return null; }
// The passed-in COM object could already be a IEnumVARIANT interface.
// e.g. user call '_NewEnum()' on a COM collection interface.
var enumVariant = comObject as COM.IEnumVARIANT;
if (enumVariant != null)
{
return new ComEnumerator(enumVariant);
}
// The passed-in COM object could be a collection.
var enumerable = comObject as IEnumerable;
var target = comObject as IDispatch;
if (enumerable != null && target != null)
{
try
{
var comTypeInfo = ComTypeInfo.GetDispatchTypeInfo(comObject);
if (comTypeInfo != null && comTypeInfo.NewEnumInvokeKind.HasValue)
{
// The COM object is a collection and also a IDispatch interface, so we try to get a
// IEnumVARIANT interface out of it by invoking its '_NewEnum (DispId: -4)' function.
var result = ComInvoker.Invoke(target, ComTypeInfo.DISPID_NEWENUM,
args: Utils.EmptyArray<object>(), byRef: null,
invokeKind: comTypeInfo.NewEnumInvokeKind.Value);
enumVariant = result as COM.IEnumVARIANT;
if (enumVariant != null)
{
return new ComEnumerator(enumVariant);
}
}
}
catch (Exception)
{
// Ignore exceptions. In case of exception, no enumerator can be created
// for the passed-in COM object, and we will return null eventually.
}
}
return null;
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Linq;
using NUnit.Framework;
using TimeAndDate.Services.Tests;
using TimeAndDate.Services;
using TimeAndDate.Services.DataTypes.DST;
using TimeAndDate.Services.DataTypes;
namespace TimeAndDate.Services.Tests.IntegrationTests
{
[TestFixture()]
public class DSTServiceTestsAsync
{
[Test()]
public async Task Calling_DstService_Should_ReturnAllDst ()
{
// Arrage
var expectedReturnedCount = 121;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = await service.GetDaylightSavingTimeAsync ();
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.AreEqual (expectedReturnedCount, result.Count);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithYear_Should_ReturnAllDst ()
{
// Arrage
var year = 2014;
var expectedReturnedCount = 132;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = await service.GetDaylightSavingTimeAsync (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.AreEqual (expectedReturnedCount, result.Count);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithCountry_Should_ReturnAllDst ()
{
// Arrage
var countryCode = "no";
var country = "Norway";
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = await service.GetDaylightSavingTimeAsync (countryCode);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeOnlyDstCountries);
Assert.AreEqual (country, sampleCountry.Region.Country.Name);
Assert.IsTrue (result.Count == 1);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithCountry_And_WithYear_Should_ReturnAllDst ()
{
// Arrage
var countryCode = "no";
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = await service.GetDaylightSavingTimeAsync (countryCode, year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeOnlyDstCountries);
Assert.IsTrue (result.Count == 1);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithoutPlacesForEveryCountry_Should_ReturnAllDstWithoutPlaces ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludePlacesForEveryCountry = false;
var result = await service.GetDaylightSavingTimeAsync (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludePlacesForEveryCountry);
Assert.IsTrue (result.All (x => x.Region.Locations.ToList().Count == 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithPlacesForEveryCountry_Should_ReturnAnyDstWithPlaces ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = await service.GetDaylightSavingTimeAsync (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsTrue (service.IncludePlacesForEveryCountry);
Assert.IsTrue (result.Any (x => x.Region.Locations.ToList().Count > 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithoutTimeChanges_Should_NotReturnAnyTimeChanges ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeTimeChanges = false;
var result = await service.GetDaylightSavingTimeAsync (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeTimeChanges);
Assert.IsTrue (result.All (x => x.TimeChanges.ToList().Count == 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithTimeChanges_Should_ReturnAnyTimeChanges ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeTimeChanges = true;
var result = await service.GetDaylightSavingTimeAsync (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsTrue (service.IncludeTimeChanges);
Assert.IsTrue (result.Any (x => x.TimeChanges.ToList().Count > 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithOnlyDstCountries_Should_ReturnOnlyDstCountries ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeOnlyDstCountries = true;
var result = await service.GetDaylightSavingTimeAsync (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsTrue (service.IncludeOnlyDstCountries);
Assert.AreEqual(132, result.Count);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public async Task Calling_DstService_WithoutOnlyDstCountries_Should_ReturnAllCountries ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeOnlyDstCountries = false;
var result = await service.GetDaylightSavingTimeAsync (year);
var noDstAllYear = result.Where (x => x.Special == DSTSpecialType.NoDaylightSavingTime);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeOnlyDstCountries);
Assert.AreEqual(348, result.Count);
Assert.Greater (noDstAllYear.Count(), 0);
HasValidSampleCountry (sampleCountry);
}
public void HasValidSampleCountry (DST norway)
{
Assert.AreEqual ("Oslo", norway.Region.BiggestPlace);
Assert.AreEqual ("no", norway.Region.Country.Id);
Assert.Greater (norway.DstEnd.Year, 1);
Assert.Greater (norway.DstStart.Year, 1);
Assert.AreEqual ("CEST", norway.DstTimezone.Abbrevation);
Assert.AreEqual (3600, norway.DstTimezone.BasicOffset);
Assert.AreEqual (3600, norway.DstTimezone.DSTOffset);
Assert.AreEqual (7200, norway.DstTimezone.TotalOffset);
Assert.AreEqual ("Central European Summer Time", norway.DstTimezone.Name);
Assert.AreEqual (2, norway.DstTimezone.Offset.Hours);
Assert.AreEqual (0, norway.DstTimezone.Offset.Minutes);
Assert.AreEqual ("CET", norway.StandardTimezone.Abbrevation);
Assert.AreEqual (3600, norway.StandardTimezone.BasicOffset);
Assert.AreEqual (0, norway.StandardTimezone.DSTOffset);
Assert.AreEqual (3600, norway.StandardTimezone.TotalOffset);
Assert.AreEqual ("Central European Time", norway.StandardTimezone.Name);
Assert.AreEqual (1, norway.StandardTimezone.Offset.Hours);
Assert.AreEqual (0, norway.StandardTimezone.Offset.Minutes);
Assert.IsNotNull (norway.Region.Description);
Assert.IsNotEmpty (norway.Region.Description);
}
}
}
| |
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 spa2.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;
}
}
}
| |
namespace Loon.Java
{
using System;
using System.IO;
using System.Text;
public interface DataInput
{
bool ReadBoolean();
sbyte ReadByte();
char ReadChar();
double ReadDouble();
float ReadFloat();
void ReadFully(byte[] buffer);
void ReadFully(byte[] buffer, int offset, int count);
int Read();
int ReadInt();
string ReadLine();
long ReadLong();
short ReadShort();
int ReadUnsignedByte();
int ReadUnsignedShort();
string ReadUTF();
int SkipBytes(int count);
long Skip(long cnt);
}
public class DataInputStream : DataInput
{
private byte[] buff;
private int limit = -1;
private long marked = -1L;
private Stream stream;
public DataInputStream(Stream stream)
{
this.stream = stream;
this.buff = new byte[8];
}
public int Available()
{
return (int)(this.stream.Length - this.stream.Position);
}
public static string ConvertUTF8WithBuf(byte[] buf, char[] outb, int offset, int utfSize)
{
int num = 0;
int index = 0;
while (num < utfSize)
{
if ((outb[index] = (char)buf[offset + num++]) < '\x0080')
{
index++;
}
else
{
int num3;
if (((num3 = outb[index]) & '\x00e0') == 0xc0)
{
if (num >= utfSize)
{
throw new Exception("K0062");
}
int num4 = buf[num++];
if ((num4 & 0xc0) != 0x80)
{
throw new Exception("K0062");
}
outb[index++] = (char)(((num3 & 0x1f) << 6) | (num4 & 0x3f));
}
else
{
if ((num3 & 240) != 0xe0)
{
throw new Exception("K0065");
}
if ((num + 1) >= utfSize)
{
throw new Exception("K0063");
}
int num5 = buf[num++];
int num6 = buf[num++];
if (((num5 & 0xc0) != 0x80) || ((num6 & 0xc0) != 0x80))
{
throw new Exception("K0064");
}
outb[index++] = (char)((((num3 & 15) << 12) | ((num5 & 0x3f) << 6)) | (num6 & 0x3f));
}
continue;
}
}
return new string(outb, 0, index);
}
private string DecodeUTF(int utfSize)
{
return DecodeUTF(utfSize, this);
}
private static string DecodeUTF(int utfSize, DataInput stream)
{
byte[] buffer = new byte[utfSize];
char[] outb = new char[utfSize];
stream.ReadFully(buffer, 0, utfSize);
return ConvertUTF8WithBuf(buffer, outb, 0, utfSize);
}
public void Mark(int limit)
{
this.marked = this.stream.Position;
this.limit = limit;
}
public int Read()
{
return stream.ReadByte();
}
public int Read(byte[] buffer)
{
return this.stream.Read(buffer, 0, buffer.Length);
}
public int Read(byte[] buffer, int offset, int length)
{
return this.stream.Read(buffer, offset, length);
}
public int Limit(){
return this.limit;
}
public bool ReadBoolean()
{
int num = this.stream.ReadByte();
if (num < 0)
{
throw new EndOfStreamException();
}
return (num != 0);
}
public sbyte ReadByte()
{
int num = this.stream.ReadByte();
if (num < 0)
{
throw new EndOfStreamException();
}
return (sbyte)num;
}
public char ReadChar()
{
if (this.ReadToBuff(2) < 0)
{
throw new EndOfStreamException();
}
return (char)(((this.buff[0] & 0xff) << 8) | (this.buff[1] & 0xff));
}
public double ReadDouble()
{
return BitConverter.Int64BitsToDouble(this.ReadLong());
}
public float ReadFloat()
{
return (float)BitConverter.DoubleToInt64Bits((double)this.ReadInt());
}
public void ReadFully(byte[] buffer)
{
this.ReadFully(buffer, 0, buffer.Length);
}
public void ReadFully(sbyte[] buffer)
{
this.ReadFully(buffer, 0, buffer.Length);
}
public void ReadFully(byte[] buffer, int offset, int length)
{
if (length < 0)
{
throw new IndexOutOfRangeException();
}
if (length != 0)
{
if (this.stream == null)
{
throw new NullReferenceException("Stream is null");
}
if (buffer == null)
{
throw new NullReferenceException("buffer is null");
}
if ((offset < 0) || (offset > (buffer.Length - length)))
{
throw new IndexOutOfRangeException();
}
while (length > 0)
{
int num = this.stream.Read(buffer, offset, length);
if (num == 0)
{
throw new EndOfStreamException();
}
offset += num;
length -= num;
}
}
}
public void ReadFully(sbyte[] buffer, int offset, int length)
{
int num = offset;
if (length < 0)
{
throw new IndexOutOfRangeException();
}
if (length != 0)
{
if (this.stream == null)
{
throw new NullReferenceException("Stream is null");
}
if (buffer == null)
{
throw new NullReferenceException("buffer is null");
}
if ((offset < 0) || (offset > (buffer.Length - length)))
{
throw new IndexOutOfRangeException();
}
byte[] buffer2 = new byte[buffer.Length];
while (length > 0)
{
int num2 = this.stream.Read(buffer2, offset, length);
if (num2 == 0)
{
throw new EndOfStreamException();
}
offset += num2;
length -= num2;
}
for (int i = num; i < buffer.Length; i++)
{
buffer[i] = (sbyte)buffer2[i];
}
}
}
public int ReadInt()
{
if (this.ReadToBuff(4) < 0)
{
throw new EndOfStreamException();
}
return (((((this.buff[0] & 0xff) << 0x18) | ((this.buff[1] & 0xff) << 0x10)) | ((this.buff[2] & 0xff) << 8)) | (this.buff[3] & 0xff));
}
public string ReadLine()
{
int num=0;
int num2=0;
StringBuilder builder = new StringBuilder(80);
bool flag = false;
while (true)
{
do
{
num = this.stream.ReadByte();
switch (num)
{
case -1:
if ((builder.Length == 0) && !flag)
{
return null;
}
return builder.ToString();
case 10:
return builder.ToString();
}
}
while (num2 == 13);
builder.Append((char)num);
}
}
public long ReadLong()
{
if (this.ReadToBuff(8) < 0)
{
throw new EndOfStreamException();
}
int num = ((((this.buff[0] & 0xff) << 0x18) | ((this.buff[1] & 0xff) << 0x10)) | ((this.buff[2] & 0xff) << 8)) | (this.buff[3] & 0xff);
int num2 = ((((this.buff[4] & 0xff) << 0x18) | ((this.buff[5] & 0xff) << 0x10)) | ((this.buff[6] & 0xff) << 8)) | (this.buff[7] & 0xff);
return (long)(((num & 0xffffffffL) << 0x20) | (num2 & 0xffffffffL));
}
public short ReadShort()
{
if (this.ReadToBuff(2) < 0)
{
throw new EndOfStreamException();
}
return (short)(((this.buff[0] & 0xff) << 8) | (this.buff[1] & 0xff));
}
private int ReadToBuff(int count)
{
int offset = 0;
while (offset < count)
{
int num2 = this.stream.Read(this.buff, offset, count);
if (num2 == 0)
{
return num2;
}
offset += num2;
}
return offset;
}
public int ReadUnsignedByte()
{
int num = this.stream.ReadByte();
if (num < 0)
{
throw new EndOfStreamException();
}
return num;
}
public int ReadUnsignedShort()
{
if (this.ReadToBuff(2) < 0)
{
throw new EndOfStreamException();
}
return (ushort)(((this.buff[0] & 0xff) << 8) | (this.buff[1] & 0xff));
}
public string ReadUTF()
{
return this.DecodeUTF(this.ReadUnsignedShort());
}
public static string ReadUTF(DataInput stream)
{
return DecodeUTF(stream.ReadUnsignedShort(), stream);
}
public void Reset()
{
if (this.marked > -1L)
{
this.stream.Position = this.marked;
}
else
{
this.stream.Position = 0L;
}
}
public long Skip(long cnt)
{
long n = cnt;
while (n > 0)
{
if (Read() == -1)
return cnt - n;
n--;
}
return cnt - n;
}
public int SkipBytes(int count)
{
int num = 0;
while (num < count)
{
this.stream.ReadByte();
num++;
}
if (num < 0)
{
throw new EndOfStreamException();
}
return num;
}
public void Close()
{
if (stream != null)
{
stream.Close();
stream = null;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Trusthub.V1
{
/// <summary>
/// Create a new Customer-Profile.
/// </summary>
public class CreateCustomerProfilesOptions : IOptions<CustomerProfilesResource>
{
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// The email address
/// </summary>
public string Email { get; }
/// <summary>
/// The unique string of a policy.
/// </summary>
public string PolicySid { get; }
/// <summary>
/// The URL we call to inform your application of status changes.
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// Construct a new CreateCustomerProfilesOptions
/// </summary>
/// <param name="friendlyName"> The string that you assigned to describe the resource </param>
/// <param name="email"> The email address </param>
/// <param name="policySid"> The unique string of a policy. </param>
public CreateCustomerProfilesOptions(string friendlyName, string email, string policySid)
{
FriendlyName = friendlyName;
Email = email;
PolicySid = policySid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Email != null)
{
p.Add(new KeyValuePair<string, string>("Email", Email));
}
if (PolicySid != null)
{
p.Add(new KeyValuePair<string, string>("PolicySid", PolicySid.ToString()));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
return p;
}
}
/// <summary>
/// Retrieve a list of all Customer-Profiles for an account.
/// </summary>
public class ReadCustomerProfilesOptions : ReadOptions<CustomerProfilesResource>
{
/// <summary>
/// The verification status of the Customer-Profile resource
/// </summary>
public CustomerProfilesResource.StatusEnum Status { get; set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The unique string of a policy.
/// </summary>
public string PolicySid { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (PolicySid != null)
{
p.Add(new KeyValuePair<string, string>("PolicySid", PolicySid.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch a specific Customer-Profile instance.
/// </summary>
public class FetchCustomerProfilesOptions : IOptions<CustomerProfilesResource>
{
/// <summary>
/// The unique string that identifies the resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchCustomerProfilesOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource. </param>
public FetchCustomerProfilesOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Updates a Customer-Profile in an account.
/// </summary>
public class UpdateCustomerProfilesOptions : IOptions<CustomerProfilesResource>
{
/// <summary>
/// The unique string that identifies the resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The verification status of the Customer-Profile resource
/// </summary>
public CustomerProfilesResource.StatusEnum Status { get; set; }
/// <summary>
/// The URL we call to inform your application of status changes.
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The email address
/// </summary>
public string Email { get; set; }
/// <summary>
/// Construct a new UpdateCustomerProfilesOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource. </param>
public UpdateCustomerProfilesOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Email != null)
{
p.Add(new KeyValuePair<string, string>("Email", Email));
}
return p;
}
}
/// <summary>
/// Delete a specific Customer-Profile.
/// </summary>
public class DeleteCustomerProfilesOptions : IOptions<CustomerProfilesResource>
{
/// <summary>
/// The unique string that identifies the resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteCustomerProfilesOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource. </param>
public DeleteCustomerProfilesOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace fyiReporting.RdlMapFile
{
internal class Undo
{
Stack _actions;
bool _Undoing = false;
XmlDocument _doc;
UndoGroup _currentUndoGroup = null;
object _pState=null; // state saved with previous changing event
int _UndoLevels;
bool _GroupsOnly=false;
internal Undo(XmlDocument doc, int levels)
{
_doc = doc;
_UndoLevels = levels; // we don't currently support; need to write special Stack
_doc.NodeChanging +=new XmlNodeChangedEventHandler(NodeChanging);
_doc.NodeChanged += new XmlNodeChangedEventHandler(NodeChanged);
_doc.NodeInserting +=new XmlNodeChangedEventHandler(NodeChanging);
_doc.NodeInserted += new XmlNodeChangedEventHandler(NodeChanged);
_doc.NodeRemoving +=new XmlNodeChangedEventHandler(NodeChanging);
_doc.NodeRemoved += new XmlNodeChangedEventHandler(NodeChanged);
_actions = new Stack();
}
internal bool GroupsOnly
{
get {return _GroupsOnly;}
set {_GroupsOnly = value;}
}
internal bool CanUndo
{
get {return _actions.Count > 0;}
}
internal string Description
{
get
{
if (_actions.Count == 0)
return "";
UndoItem ui = (UndoItem) _actions.Peek();
return ui.GetDescription();
}
}
internal void Reset()
{
_actions.Clear();
}
internal bool Undoing
{
get {return _Undoing;}
set {_Undoing = value;}
}
private void NodeChanging(object sender, XmlNodeChangedEventArgs e)
{
if (this._Undoing)
return;
switch (e.Action)
{
case XmlNodeChangedAction.Insert:
_pState = NodeInsertedUndo.PreviousState(e);
break;
case XmlNodeChangedAction.Remove:
_pState = NodeRemovedUndo.PreviousState(e);
break;
case XmlNodeChangedAction.Change:
_pState = NodeChangedUndo.PreviousState(e);
break;
default:
throw new Exception("Unknown Action");
}
}
private void NodeChanged(object sender, XmlNodeChangedEventArgs e)
{
if (this._Undoing)
{
// if we're undoing ignore the event since it is the result of an undo
_pState = null;
_Undoing = false;
return;
}
UndoItem undo = null;
switch (e.Action)
{
case XmlNodeChangedAction.Insert:
undo = new NodeInsertedUndo(e, _pState);
break;
case XmlNodeChangedAction.Remove:
undo = new NodeRemovedUndo(e, _pState);
break;
case XmlNodeChangedAction.Change:
undo = new NodeChangedUndo(e, _pState);
break;
default:
throw new Exception("Unknown Action");
}
_pState = null;
if (_currentUndoGroup != null)
{
_currentUndoGroup.AddUndoItem(undo);
}
else if (GroupsOnly)
{
_pState = null;
}
else
{
_actions.Push(undo);
}
}
internal void undo()
{
UndoItem undoItem = null;
if (_actions.Count == 0)
return;
undoItem = (UndoItem)_actions.Pop();
_Undoing = true;
undoItem.Undo();
}
internal void StartUndoGroup(String description)
{
UndoGroup ug = new UndoGroup(this, description);
_currentUndoGroup = ug;
_actions.Push(ug);
}
internal void EndUndoGroup()
{
EndUndoGroup(true); // we want to keep the undo items on the stack
}
internal void EndUndoGroup(bool keepChanges)
{
if (_currentUndoGroup == null)
return;
// group contains no items; or user doesn't want changes to part of undo
//
if (_currentUndoGroup.Count == 0 || !keepChanges)
{
UndoGroup ug = _actions.Pop() as UndoGroup; // get rid of the empty group
if (ug != _currentUndoGroup)
throw new Exception("Internal logic error: EndGroup doesn't match StartGroup");
}
_currentUndoGroup = null;
}
}
internal interface UndoItem
{
void Undo();
String GetDescription();
}
internal class NodeInsertedUndo : UndoItem
{
XmlNode iNode;
public NodeInsertedUndo(XmlNodeChangedEventArgs e, object previous)
{
iNode = e.Node;
}
public void Undo()
{
XmlNode parent = iNode.ParentNode;
if (parent == null) // happens with attributes but doesn't affect the undo??
{
return;
}
parent.RemoveChild(iNode);
}
public String GetDescription()
{
return "insert"; // could be more explicit using XmlNodeType but ...
}
static internal object PreviousState(XmlNodeChangedEventArgs e)
{
return null;
}
}
internal class NodeRemovedUndo : UndoItem
{
internal XmlNode removedNode;
internal XmlNode parentNode;
internal XmlNode nextSibling;
internal NodeRemovedUndo(XmlNodeChangedEventArgs e, object previous)
{
removedNode = e.Node;
parentNode = e.OldParent;
nextSibling = previous as XmlNode;
}
public void Undo()
{
parentNode.InsertBefore(removedNode, nextSibling);
}
public String GetDescription()
{
return "remove"; // could be more specific using NodeType
}
static internal object PreviousState(XmlNodeChangedEventArgs e)
{
return e.Node.NextSibling;
}
}
/**
* Can be used for both CharacterData and ProcessingInstruction nodes.
*/
internal class NodeChangedUndo : UndoItem
{
String oldValue;
XmlNode node;
internal NodeChangedUndo(XmlNodeChangedEventArgs e, object pValue)
{
oldValue = pValue as string;
node = e.Node;
}
public void Undo()
{
node.Value = oldValue;
}
public String GetDescription()
{
return "change";
}
static internal object PreviousState(XmlNodeChangedEventArgs e)
{
return e.Node.Value;
}
}
/**
* Groups several undo events into one transaction. Needed when one
* user action corresponds to multiple dom events
* */
internal class UndoGroup : UndoItem
{
Undo _undo;
string description;
List<UndoItem> undoItems = new List<UndoItem>();
internal UndoGroup(Undo undo, String description)
{
_undo = undo;
this.description = description;
}
internal void AddUndoItem(UndoItem ui)
{
undoItems.Add(ui);
}
internal int Count
{
get {return undoItems.Count;}
}
public void Undo()
{
// loop thru group items backwards
for (int i=undoItems.Count-1; i >= 0; i--)
{
UndoItem ui = undoItems[i] as UndoItem;
_undo.Undoing = true;
ui.Undo();
}
}
public String GetDescription()
{
return description;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.ServiceModel.Channels;
using System.Xml;
namespace System.ServiceModel.Security
{
public class ScopedMessagePartSpecification
{
private MessagePartSpecification _channelParts;
private Dictionary<string, MessagePartSpecification> _actionParts;
private Dictionary<string, MessagePartSpecification> _readOnlyNormalizedActionParts;
private bool _isReadOnly;
public ScopedMessagePartSpecification()
{
_channelParts = new MessagePartSpecification();
_actionParts = new Dictionary<string, MessagePartSpecification>();
}
public ICollection<string> Actions
{
get
{
return _actionParts.Keys;
}
}
public MessagePartSpecification ChannelParts
{
get
{
return _channelParts;
}
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
public ScopedMessagePartSpecification(ScopedMessagePartSpecification other)
: this()
{
if (other == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));
_channelParts.Union(other._channelParts);
if (other._actionParts != null)
{
foreach (string action in other._actionParts.Keys)
{
MessagePartSpecification p = new MessagePartSpecification();
p.Union(other._actionParts[action]);
_actionParts[action] = p;
}
}
}
internal ScopedMessagePartSpecification(ScopedMessagePartSpecification other, bool newIncludeBody)
: this(other)
{
_channelParts.IsBodyIncluded = newIncludeBody;
foreach (string action in _actionParts.Keys)
_actionParts[action].IsBodyIncluded = newIncludeBody;
}
public void AddParts(MessagePartSpecification parts)
{
if (parts == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));
ThrowIfReadOnly();
_channelParts.Union(parts);
}
public void AddParts(MessagePartSpecification parts, string action)
{
if (action == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
if (parts == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));
ThrowIfReadOnly();
if (!_actionParts.ContainsKey(action))
_actionParts[action] = new MessagePartSpecification();
_actionParts[action].Union(parts);
}
internal void AddParts(MessagePartSpecification parts, XmlDictionaryString action)
{
if (action == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
AddParts(parts, action.Value);
}
internal bool IsEmpty()
{
bool result;
if (!_channelParts.IsEmpty())
{
result = false;
}
else
{
result = true;
foreach (string action in this.Actions)
{
MessagePartSpecification parts;
if (TryGetParts(action, true, out parts))
{
if (!parts.IsEmpty())
{
result = false;
break;
}
}
}
}
return result;
}
public bool TryGetParts(string action, bool excludeChannelScope, out MessagePartSpecification parts)
{
if (action == null)
action = MessageHeaders.WildcardAction;
parts = null;
if (_isReadOnly)
{
if (_readOnlyNormalizedActionParts.ContainsKey(action))
if (excludeChannelScope)
parts = _actionParts[action];
else
parts = _readOnlyNormalizedActionParts[action];
}
else if (_actionParts.ContainsKey(action))
{
MessagePartSpecification p = new MessagePartSpecification();
p.Union(_actionParts[action]);
if (!excludeChannelScope)
p.Union(_channelParts);
parts = p;
}
return parts != null;
}
internal void CopyTo(ScopedMessagePartSpecification target)
{
if (target == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("target");
}
target.ChannelParts.IsBodyIncluded = this.ChannelParts.IsBodyIncluded;
foreach (XmlQualifiedName headerType in ChannelParts.HeaderTypes)
{
if (!target._channelParts.IsHeaderIncluded(headerType.Name, headerType.Namespace))
{
target.ChannelParts.HeaderTypes.Add(headerType);
}
}
foreach (string action in _actionParts.Keys)
{
target.AddParts(_actionParts[action], action);
}
}
public bool TryGetParts(string action, out MessagePartSpecification parts)
{
return this.TryGetParts(action, false, out parts);
}
public void MakeReadOnly()
{
if (!_isReadOnly)
{
_readOnlyNormalizedActionParts = new Dictionary<string, MessagePartSpecification>();
foreach (string action in _actionParts.Keys)
{
MessagePartSpecification p = new MessagePartSpecification();
p.Union(_actionParts[action]);
p.Union(_channelParts);
p.MakeReadOnly();
_readOnlyNormalizedActionParts[action] = p;
}
_isReadOnly = true;
}
}
private void ThrowIfReadOnly()
{
if (_isReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
}
}
}
| |
// 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.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Microsoft.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<Microsoft.Xml.XmlQualifiedName, DataContract>;
using Microsoft.Xml.Serialization;
using Microsoft.Xml.Schema;
using System.Security;
using System.Linq;
#if NET_NATIVE
public delegate IXmlSerializable CreateXmlSerializableDelegate();
public sealed class XmlDataContract : DataContract
#else
internal delegate IXmlSerializable CreateXmlSerializableDelegate();
internal sealed class XmlDataContract : DataContract
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private XmlDataContractCriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
public XmlDataContract() : base(new XmlDataContractCriticalHelper())
{
_helper = base.Helper as XmlDataContractCriticalHelper;
}
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type))
{
_helper = base.Helper as XmlDataContractCriticalHelper;
}
public override DataContractDictionary KnownDataContracts
{
/// <SecurityNote>
/// Critical - fetches the critical KnownDataContracts property
/// Safe - KnownDataContracts only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
/// <SecurityNote>
/// Critical - sets the critical KnownDataContracts property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.KnownDataContracts = value; }
}
internal bool IsAnonymous
{
/// <SecurityNote>
/// Critical - fetches the critical IsAnonymous property
/// Safe - IsAnonymous only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsAnonymous; }
}
public override bool HasRoot
{
/// <SecurityNote>
/// Critical - fetches the critical HasRoot property
/// Safe - HasRoot only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.HasRoot; }
/// <SecurityNote>
/// Critical - sets the critical HasRoot property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.HasRoot = value; }
}
public override XmlDictionaryString TopLevelElementName
{
/// <SecurityNote>
/// Critical - fetches the critical TopLevelElementName property
/// Safe - TopLevelElementName only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.TopLevelElementName; }
/// <SecurityNote>
/// Critical - sets the critical TopLevelElementName property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.TopLevelElementName = value; }
}
internal XmlSchemaType XsdType
{
// TODO: [Fx.Tag.SecurityNote(Critical = "Fetches the critical XsdType property.",
// Safe = "XsdType only needs to be protected for write.")]
[SecuritySafeCritical]
get { return _helper.XsdType; }
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets the critical XsdType property.")]
[SecurityCritical]
set { _helper.XsdType = value; }
}
public override XmlDictionaryString TopLevelElementNamespace
{
/// <SecurityNote>
/// Critical - fetches the critical TopLevelElementNamespace property
/// Safe - TopLevelElementNamespace only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.TopLevelElementNamespace; }
/// <SecurityNote>
/// Critical - sets the critical TopLevelElementNamespace property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.TopLevelElementNamespace = value; }
}
internal bool IsTopLevelElementNullable
{
// TODO: [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsTopLevelElementNullable property.",
// Safe = "IsTopLevelElementNullable only needs to be protected for write.")]
[SecuritySafeCritical]
get { return _helper.IsTopLevelElementNullable; }
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets the critical IsTopLevelElementNullable property.")]
[SecurityCritical]
set { _helper.IsTopLevelElementNullable = value; }
}
internal bool IsTypeDefinedOnImport
{
// TODO: [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsTypeDefinedOnImport property.",
// Safe = "IsTypeDefinedOnImport only needs to be protected for write.")]
[SecuritySafeCritical]
get { return _helper.IsTypeDefinedOnImport; }
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets the critical IsTypeDefinedOnImport property.")]
[SecurityCritical]
set { _helper.IsTypeDefinedOnImport = value; }
}
#if !NET_NATIVE
internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical CreateXmlSerializableDelegate property
/// Safe - CreateXmlSerializableDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.CreateXmlSerializableDelegate == null)
{
lock (this)
{
if (_helper.CreateXmlSerializableDelegate == null)
{
CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate();
Interlocked.MemoryBarrier();
_helper.CreateXmlSerializableDelegate = tempCreateXmlSerializable;
}
}
}
return _helper.CreateXmlSerializableDelegate;
}
}
#else
public CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get; set; }
#endif
internal override bool CanContainReferences
{
get { return false; }
}
public override bool IsBuiltInDataContract
{
get
{
return UnderlyingType == Globals.TypeOfXmlElement || UnderlyingType == Globals.TypeOfXmlNodeArray;
}
}
/// <SecurityNote>
/// Critical - holds all state used for for (de)serializing XML types.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
[SecurityCritical]
private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private XmlDictionaryString _topLevelElementName;
private XmlDictionaryString _topLevelElementNamespace;
private bool _isTopLevelElementNullable;
private bool _isTypeDefinedOnImport;
private XmlSchemaType _xsdType;
private bool _hasRoot;
private CreateXmlSerializableDelegate _createXmlSerializable;
internal XmlDataContractCriticalHelper()
{
}
internal XmlDataContractCriticalHelper(Type type) : base(type)
{
if (type.GetTypeInfo().IsAttributeDefined(Globals.TypeOfDataContractAttribute))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
if (type.GetTypeInfo().IsAttributeDefined(Globals.TypeOfCollectionDataContractAttribute))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
XmlSchemaType xsdType;
bool hasRoot;
XmlQualifiedName stableName;
SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot);
this.StableName = stableName;
this.XsdType = xsdType;
this.HasRoot = hasRoot;
XmlDictionary dictionary = new XmlDictionary();
this.Name = dictionary.Add(StableName.Name);
this.Namespace = dictionary.Add(StableName.Namespace);
object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetTypeInfo().GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
{
if (hasRoot)
{
_topLevelElementName = Name;
_topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
}
}
else
{
if (hasRoot)
{
XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
_isTopLevelElementNullable = xmlRootAttribute.IsNullable;
string elementName = xmlRootAttribute.ElementName;
_topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
string elementNs = xmlRootAttribute.Namespace;
_topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType))));
}
}
}
internal override DataContractDictionary KnownDataContracts
{
[SecurityCritical]
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
[SecurityCritical]
set
{ _knownDataContracts = value; }
}
internal XmlSchemaType XsdType
{
get { return _xsdType; }
set { _xsdType = value; }
}
internal bool IsAnonymous
{
get { return false; }
}
internal override bool HasRoot
{
get { return _hasRoot; }
set { _hasRoot = value; }
}
internal override XmlDictionaryString TopLevelElementName
{
[SecurityCritical]
get
{ return _topLevelElementName; }
[SecurityCritical]
set
{ _topLevelElementName = value; }
}
internal override XmlDictionaryString TopLevelElementNamespace
{
[SecurityCritical]
get
{ return _topLevelElementNamespace; }
[SecurityCritical]
set
{ _topLevelElementNamespace = value; }
}
internal bool IsTopLevelElementNullable
{
get { return _isTopLevelElementNullable; }
set { _isTopLevelElementNullable = value; }
}
internal bool IsTypeDefinedOnImport
{
get { return _isTypeDefinedOnImport; }
set { _isTypeDefinedOnImport = value; }
}
internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
{
get { return _createXmlSerializable; }
set { _createXmlSerializable = value; }
}
}
private ConstructorInfo GetConstructor()
{
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType)
return null;
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
if (ctor == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
return ctor;
}
//TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on XmlDataContract.")]
[SecurityCritical]
internal void SetTopLevelElementName(XmlQualifiedName elementName)
{
if (elementName != null)
{
XmlDictionary dictionary = new XmlDictionary();
this.TopLevelElementName = dictionary.Add(elementName.Name);
this.TopLevelElementNamespace = dictionary.Add(elementName.Namespace);
}
}
#if !NET_NATIVE
/// <SecurityNote>
/// Critical - calls CodeGenerator.BeginMethod which is SecurityCritical
/// Safe - self-contained: returns the delegate to the generated IL but otherwise all IL generation is self-contained here
/// </SecurityNote>
[SecuritySafeCritical]
internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate()
{
Type type = this.UnderlyingType;
CodeGenerator ilg = new CodeGenerator();
bool memberAccessFlag = RequiresMemberAccessForCreate(null) && !(type.FullName == "System.Xml.Linq.XElement");
try
{
ilg.BeginMethod("Create" + DataContract.GetClrTypeFullName(type), typeof(CreateXmlSerializableDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
RequiresMemberAccessForCreate(securityException);
}
else
{
throw;
}
}
if (type.GetTypeInfo().IsValueType)
{
System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value");
ilg.Ldloca(local);
ilg.InitObj(type);
ilg.Ldloc(local);
}
else
{
// Special case XElement
// codegen the same as 'internal XElement : this("default") { }'
ConstructorInfo ctor = GetConstructor();
if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement")
{
Type xName = type.GetTypeInfo().Assembly.GetType("System.Xml.Linq.XName");
if (xName != null)
{
MethodInfo XName_op_Implicit = xName.GetMethod(
"op_Implicit",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
new Type[] { typeof(String) }
);
ConstructorInfo XElement_ctor = type.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
new Type[] { xName }
);
if (XName_op_Implicit != null && XElement_ctor != null)
{
ilg.Ldstr("default");
ilg.Call(XName_op_Implicit);
ctor = XElement_ctor;
}
}
}
ilg.New(ctor);
}
ilg.ConvertValue(this.UnderlyingType, Globals.TypeOfIXmlSerializable);
ilg.Ret();
return (CreateXmlSerializableDelegate)ilg.EndMethod();
}
/// <SecurityNote>
/// Review - calculates whether this Xml type requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
private bool RequiresMemberAccessForCreate(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(string.Format(SRSerialization.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(GetConstructor()))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(string.Format(SRSerialization.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
return false;
}
#endif
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (context == null)
XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj);
else
context.WriteIXmlSerializable(xmlWriter, obj);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
object o;
if (context == null)
{
o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/);
}
else
{
o = context.ReadIXmlSerializable(xmlReader, this, true /*isMemberType*/);
context.AddNewObject(o);
}
xmlReader.ReadEndElement();
return o;
}
}
}
| |
using System.Linq;
using UnityEngine;
public class Piece : MonoBehaviour
{
public PieceGroup.Directions Direction;
private PieceGroup _group;
private bool _hasCollided;
private Vector3 _initialLocalPosition;
private Quaternion _initialLocalRotation;
private string _specialName;
// Use this for initialization
public void Start()
{
_initialLocalPosition = transform.localPosition;
_initialLocalRotation = transform.localRotation;
_group = transform.parent.GetComponent<PieceGroup>();
var random = Random.value;
foreach (var special in GameManager.Instance.SpecialMaterials.OrderByDescending(x => x.Chance).Where(special => random < special.Chance))
{
_specialName = special.Name;
GetComponent<Renderer>().material = special.Material;
}
//if (string.IsNullOrEmpty(_specialName))
// GetComponent<Renderer>().material =
// GameManager.Instance.Materials[Random.Range(0, GameManager.Instance.Materials.Length)];
if (string.IsNullOrEmpty(_specialName))
{
GetComponent<Renderer>().material = GameManager.Instance.NormalPieceMaterial;
GetComponent<Renderer>().material.color =
GameManager.Instance.Colours[Random.Range(0, GameManager.Instance.Colours.Length)];
}
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
}
// Update is called once per frame
public void Update()
{
if (!GameManager.Instance.IsGameRunning) return;
if (!_group.IsMoving) return;
//rigidbody.velocity = Vector3.zero;
if (transform.localPosition != _initialLocalPosition)
transform.localPosition = _initialLocalPosition;
if (transform.localRotation != _initialLocalRotation)
transform.localRotation = _initialLocalRotation;
}
public void FixedUpdate()
{
//GetComponent<Rigidbody>().constraints= RigidbodyConstraints.FreezeAll;
}
public void SetCollisionBoxSize(float size)
{
GetComponent<BoxCollider>().size = Vector3.one * size;
}
public void OnTriggerEnter(Collider other)
{
if (!GameManager.Instance.IsGameRunning) return;
switch (GameManager.Instance.GameplayMode)
{
case GameManager.GameplayModes.AnyCollision:
CollisionDetectedMode1(other);
break;
case GameManager.GameplayModes.NoDiagonals:
//CollisionDetectedMode2(other);
break;
}
}
private void CollisionDetectedMode1(Collider other)
{
if (_group.Pieces.Contains(other.gameObject))
{
return;
}
if (other.GetComponent<Renderer>() == null ||
(other.GetComponent<Renderer>().material.HasProperty("_Color") && other.GetComponent<Renderer>().material.color == Color.black))
{
FreezeBlock();
return;
}
if (!string.IsNullOrEmpty(_specialName))
{
if (!string.IsNullOrEmpty(other.GetComponent<Piece>()._specialName))
{
if (_specialName == other.GetComponent<Piece>()._specialName)
{
// Execute special.
switch (_specialName)
{
case "GravityBomb":
GameManager.Instance.GravityBombTrigger = true;
break;
case "MirrorBomb":
GameManager.Instance.MirrorBombTrigger = true;
break;
default:
return;
}
Destroy(other.gameObject);
Destroy(gameObject);
}
}
FreezeBlock();
return;
}
if (!string.IsNullOrEmpty(other.GetComponent<Piece>()._specialName))
{
FreezeBlock();
return;
}
var currentPieceColour = GetComponent<Renderer>().material.color;
var otherPieceColour = other.GetComponent<Renderer>().material.color;
if (currentPieceColour != otherPieceColour)
{
FreezeBlock();
return;
}
Destroy(other.gameObject);
Destroy(gameObject);
}
//private void CollisionDetectedMode2(Collider other)
//{
// var hasCollidedWithSameColour = false;
// var hasHitOtherColour = false;
// var brotherPieces = transform.parent.GetComponent<PieceGroup>().Pieces;
// if (brotherPieces.Contains(other.gameObject)) return;
// foreach (var brother in brotherPieces.Where(brother => brother != null))
// {
// for (var i = 0; i < 4; i++)
// {
// Vector3 direction;
// switch (i)
// {
// case 0:
// direction = Vector3.up;
// break;
// case 1:
// direction = Vector3.right;
// break;
// case 2:
// direction = -Vector3.up;
// break;
// case 3:
// direction = -Vector3.right;
// break;
// default:
// direction = Vector3.left;
// break;
// }
// direction = direction / 10;
// //var gridPoint = GameManager.Instance.GetClosestGridPoint(brother.transform.position + direction);
// var gridPoint = Helper.Instance.SnapToGrid(brother.transform.position + direction);
// var piece = GameManager.Instance.GetPieceAtGridPoint(gridPoint);
// if (piece == null ||
// brotherPieces.Contains(piece) ||
// piece.GetInstanceID() == brother.GetInstanceID())
// continue;
// if (!string.IsNullOrEmpty(_specialName))
// {
// if (!string.IsNullOrEmpty(piece.GetComponent<Piece>()._specialName))
// {
// if (_specialName == piece.GetComponent<Piece>()._specialName)
// {
// // Execute special.
// switch (_specialName)
// {
// case "GravityBomb":
// GameManager.Instance.GravityBombTrigger = true;
// break;
// case "MirrorBomb":
// GameManager.Instance.MirrorBombTrigger = true;
// break;
// default:
// return;
// }
// Destroy(piece.gameObject);
// Destroy(brother.gameObject);
// }
// }
// FreezeBlock();
// return;
// }
// if (!string.IsNullOrEmpty(piece.GetComponent<Piece>()._specialName))
// return;
// if (piece.GetComponent<Renderer>().material.color == Color.black)
// continue;
// var brotherColour = brother.GetComponent<Renderer>().material.color;
// var pieceColour = piece.GetComponent<Renderer>().material.color;
// if (brotherColour == pieceColour)
// {
// Destroy(piece.gameObject);
// Destroy(brother.gameObject);
// hasCollidedWithSameColour = true;
// }
// else
// {
// hasHitOtherColour = true;
// }
// }
// }
// var numberOfBorthersLeft = transform.parent.transform.childCount;
// if (numberOfBorthersLeft == 0)
// GameManager.Instance.IncrementScore(100);
// if (hasCollidedWithSameColour)
// {
// GameManager.Instance.IncrementScore();
// if (!hasHitOtherColour)
// return;
// }
// FreezeBlock();
//}
private void FreezeBlock()
{
_group.IsMoving = false;
if (_hasCollided) return;
_hasCollided = true;
var currentPos = transform.parent.position;
transform.parent.position = GameManager.Instance.GetClosestGridPoint(currentPos);
//transform.parent.position = Helper.Instance.SnapToGrid(currentPos);
transform.parent.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using UnityEngine;
//
//public class ProceduralFairingBase : PartModule
//{
// [KSPField] public float outlineWidth=0.05f;
// [KSPField] public int outlineSlices=12;
// [KSPField] public Vector4 outlineColor=new Vector4(0, 0, 0.2f, 1);
// [KSPField] public float verticalStep=0.2f;
// [KSPField] public float baseSize=1.25f;
// [KSPField(isPersistant=true)] public float extraRadius=0.2f;
// [KSPField] public int circleSegments=24;
//
// [KSPField] public float sideThickness=0.05f;
//
// [KSPField] public string extraRadiusKey="r";
//
// float updateDelay=0;
//
//
// LineRenderer line=null;
//
// List<LineRenderer> outline=new List<LineRenderer>();
//
//
// List<ConfigurableJoint> joints=new List<ConfigurableJoint>();
//
//
// public void OnMouseOver()
// {
// if (HighLogic.LoadedSceneIsEditor)
// {
// if (part.isConnected && Input.GetKey(extraRadiusKey))
// {
// float old=extraRadius;
// extraRadius+=(Input.GetAxis("Mouse X")+Input.GetAxis("Mouse Y"))*0.1f;
// extraRadius=Mathf.Max(extraRadius, -1);
// extraRadius=Mathf.Min(extraRadius, 100);
// if (extraRadius!=old) updateDelay=0;
// }
// }
// }
//
//
// public override string GetInfo()
// {
// string s="Attach side fairings and they'll be shaped for your attached payload.\n"+
// "Remember to add a decoupler if you need one.";
//
// if (!string.IsNullOrEmpty(extraRadiusKey))
// s+="\nMouse over and hold '"+extraRadiusKey+"' to adjust extra radius.";
//
// return s;
// }
//
//
// public override void OnStart(StartState state)
// {
// if (state==StartState.None) return;
//
// if ((state & StartState.Editor)!=0)
// {
// // line=makeLineRenderer("payload outline", Color.red, outlineWidth);
// if (line) line.transform.Rotate(0, 90, 0);
//
// destroyOutline();
// for (int i=0; i<outlineSlices; ++i)
// {
// var r=makeLineRenderer("fairing outline", outlineColor, outlineWidth);
// outline.Add(r);
// r.transform.Rotate(0, i*360f/outlineSlices, 0);
// }
//
// updateDelay=0;
// }
// }
//
//
// public void OnPartPack()
// {
// while (joints.Count>0)
// {
// int i=joints.Count-1;
// var joint=joints[i]; joints.RemoveAt(i);
// UnityEngine.Object.Destroy(joint);
// }
// }
//
//
// public void OnPartUnpack()
// {
// if (!HighLogic.LoadedSceneIsEditor)
// {
// // strut side fairings together
// var attached=part.findAttachNodes("connect");
// for (int i=0; i<attached.Length; ++i)
// {
// var p=attached[i].attachedPart;
// if (p==null || p.Rigidbody==null) continue;
//
// // var sf=p.GetComponent<ProceduralFairingSide>();
// // if (sf==null) continue;
//
// var pp=attached[i>0 ? i-1 : attached.Length-1].attachedPart;
// if (pp==null) continue;
//
// var rb=pp.Rigidbody;
// if (rb==null) continue;
//
// var joint=p.gameObject.AddComponent<ConfigurableJoint>();
// joint.xMotion=ConfigurableJointMotion.Locked;
// joint.yMotion=ConfigurableJointMotion.Locked;
// joint.zMotion=ConfigurableJointMotion.Locked;
// joint.angularXMotion=ConfigurableJointMotion.Locked;
// joint.angularYMotion=ConfigurableJointMotion.Locked;
// joint.angularZMotion=ConfigurableJointMotion.Locked;
// joint.projectionDistance=0.1f;
// joint.projectionAngle=5;
// joint.breakForce =p.breakingForce ;
// joint.breakTorque=p.breakingTorque;
// joint.connectedBody=rb;
//
// joints.Add(joint);
// }
// }
// }
//
//
// LineRenderer makeLineRenderer(string name, Color color, float wd)
// {
// var o=new GameObject(name);
// o.transform.parent=part.transform;
// o.transform.localPosition=Vector3.zero;
// o.transform.localRotation=Quaternion.identity;
// var r=o.AddComponent<LineRenderer>();
// r.useWorldSpace=false;
// r.material=new Material(Shader.Find("Particles/Additive"));
// r.SetColors(color, color);
// r.SetWidth(wd, wd);
// r.SetVertexCount(0);
// return r;
// }
//
//
// void destroyOutline()
// {
// foreach (var r in outline) UnityEngine.Object.Destroy(r.gameObject);
// outline.Clear();
// }
//
//
// public void OnDestroy()
// {
// if (line) { UnityEngine.Object.Destroy(line.gameObject); line=null; }
// destroyOutline();
// }
//
//
// public void Update()
// {
// if (HighLogic.LoadedSceneIsEditor)
// {
// updateDelay-=Time.deltaTime;
// if (updateDelay<=0) { recalcShape(); updateDelay=0.2f; }
// }
// }
//
//
// static public Vector3[] buildFairingShape(float baseRad, float maxRad,
// float cylStart, float cylEnd, float noseHeightRatio,
// Vector4 baseConeShape, Vector4 noseConeShape,
// int baseConeSegments, int noseConeSegments,
// Vector4 vertMapping, float mappingScaleY)
// {
// float baseConeRad=maxRad-baseRad;
// float tip=maxRad*noseHeightRatio;
//
// var baseSlope=new BezierSlope(baseConeShape);
// var noseSlope=new BezierSlope(noseConeShape);
//
// float baseV0=vertMapping.x/mappingScaleY;
// float baseV1=vertMapping.y/mappingScaleY;
// float noseV0=vertMapping.z/mappingScaleY;
// float noseV1=vertMapping.w/mappingScaleY;
//
// var shape=new Vector3[1+(cylStart==0?0:baseConeSegments)+1+noseConeSegments];
// int vi=0;
//
// if (cylStart!=0)
// {
// for (int i=0; i<=baseConeSegments; ++i, ++vi)
// {
// float t=(float)i/baseConeSegments;
// var p=baseSlope.interp(t);
// shape[vi]=new Vector3(p.x*baseConeRad+baseRad, p.y*cylStart,
// Mathf.Lerp(baseV0, baseV1, t));
// }
// }
// else
// shape[vi++]=new Vector3(baseRad, 0, baseV1);
//
// for (int i=0; i<=noseConeSegments; ++i, ++vi)
// {
// float t=(float)i/noseConeSegments;
// var p=noseSlope.interp(1-t);
// shape[vi]=new Vector3(p.x*maxRad, (1-p.y)*tip+cylEnd,
// Mathf.Lerp(noseV0, noseV1, t));
// }
//
// return shape;
// }
//
//
// static public Vector3[] buildInlineFairingShape(float baseRad, float maxRad, float topRad,
// float cylStart, float cylEnd, float top,
// Vector4 baseConeShape,
// int baseConeSegments,
// Vector4 vertMapping, float mappingScaleY)
// {
// float baseConeRad=maxRad-baseRad;
// float topConeRad=maxRad- topRad;
//
// var baseSlope=new BezierSlope(baseConeShape);
//
// float baseV0=vertMapping.x/mappingScaleY;
// float baseV1=vertMapping.y/mappingScaleY;
// float noseV0=vertMapping.z/mappingScaleY;
//
// var shape=new Vector3[2+(cylStart==0?0:baseConeSegments+1)+(cylEnd==top?0:baseConeSegments+1)];
// int vi=0;
//
// if (cylStart!=0)
// {
// for (int i=0; i<=baseConeSegments; ++i, ++vi)
// {
// float t=(float)i/baseConeSegments;
// var p=baseSlope.interp(t);
// shape[vi]=new Vector3(p.x*baseConeRad+baseRad, p.y*cylStart,
// Mathf.Lerp(baseV0, baseV1, t));
// }
// }
//
// shape[vi++]=new Vector3(maxRad, cylStart, baseV1);
// shape[vi++]=new Vector3(maxRad, cylEnd, noseV0);
//
// if (cylEnd!=top)
// {
// for (int i=0; i<=baseConeSegments; ++i, ++vi)
// {
// float t=(float)i/baseConeSegments;
// var p=baseSlope.interp(1-t);
// shape[vi]=new Vector3(p.x*topConeRad+topRad, Mathf.Lerp(top, cylEnd, p.y),
// Mathf.Lerp(baseV1, baseV0, t));
// }
// }
//
// return shape;
// }
//
//
// void recalcShape()
// {
// // scan payload and build its profile
// var scan=new PayloadScan(part, verticalStep, extraRadius);
//
// AttachNode node=part.findAttachNode("top");
// if (node!=null && node.attachedPart!=null)
// {
// scan.ofs=node.position.y;
// scan.addPart(node.attachedPart, part);
// }
//
// for (int i=0; i<scan.payload.Count; ++i)
// {
// var cp=scan.payload[i];
//
// // add connected payload parts
// scan.addPart(cp.parent, cp);
// foreach (var p in cp.children) scan.addPart(p, cp);
//
// // scan part colliders
// foreach (var coll in cp.FindModelComponents<Collider>())
// {
// if (coll.tag!="Untagged") continue; // skip ladders etc.
// scan.addPayload(coll);
// }
// }
//
// // check for reversed base for inline fairings
// float topY=0;
// ProceduralFairingBase topBase=null;
// if (scan.targets.Count>0)
// {
// topBase=scan.targets[0].GetComponent<ProceduralFairingBase>();
// topY=scan.w2l.MultiplyPoint3x4(topBase.part.transform.position).y;
// if (topY<scan.ofs) topY=scan.ofs;
// }
//
// if (scan.profile.Count<=0)
// {
// // no payload
// if (line) line.SetVertexCount(0);
// foreach (var lr in outline) lr.SetVertexCount(0);
// return;
// }
//
// // fill profile outline (for debugging)
// if (line)
// {
// line.SetVertexCount(scan.profile.Count*2+2);
//
// float prevRad=0;
// int hi=0;
// foreach (var r in scan.profile)
// {
// line.SetPosition(hi*2 , new Vector3(prevRad, hi*verticalStep+scan.ofs, 0));
// line.SetPosition(hi*2+1, new Vector3( r, hi*verticalStep+scan.ofs, 0));
// hi++; prevRad=r;
// }
//
// line.SetPosition(hi*2 , new Vector3(prevRad, hi*verticalStep+scan.ofs, 0));
// line.SetPosition(hi*2+1, new Vector3( 0, hi*verticalStep+scan.ofs, 0));
// }
//
// // check attached side parts and get params
// var attached=part.findAttachNodes("connect");
// int numSideParts=attached.Length;
//
// var sideNode=attached.FirstOrDefault(n => n.attachedPart
// && n.attachedPart.GetComponent<ProceduralFairingSide>());
//
// float noseHeightRatio=2;
// Vector4 baseConeShape=new Vector4(0.5f, 0, 1, 0.5f);
// Vector4 noseConeShape=new Vector4(0.5f, 0, 1, 0.5f);
// int baseConeSegments=1;
// int noseConeSegments=1;
// Vector2 mappingScale=new Vector2(1024, 1024);
// Vector2 stripMapping=new Vector2(992, 1024);
// Vector4 horMapping=new Vector4(0, 480, 512, 992);
// Vector4 vertMapping=new Vector4(0, 160, 704, 1024);
//
// if (sideNode!=null)
// {
// var sf=sideNode.attachedPart.GetComponent<ProceduralFairingSide>();
// noseHeightRatio =sf.noseHeightRatio ;
// baseConeShape =sf.baseConeShape ;
// noseConeShape =sf.noseConeShape ;
// baseConeSegments=sf.baseConeSegments;
// noseConeSegments=sf.noseConeSegments;
// mappingScale =sf.mappingScale ;
// stripMapping =sf.stripMapping ;
// horMapping =sf.horMapping ;
// vertMapping =sf.vertMapping ;
// }
//
// // compute fairing shape
// float baseRad=baseSize*0.5f;
//
// float cylStart=0;
// float maxRad=scan.profile.Max();
//
// float topRad=0;
// if (topBase!=null)
// {
// topRad=topBase.baseSize*0.5f;
// maxRad=Mathf.Max(maxRad, topRad);
// }
//
// if (maxRad>baseRad)
// {
// // try to fit base cone as high as possible
// cylStart=scan.ofs;
// for (int i=1; i<scan.profile.Count; ++i)
// {
// float y=i*verticalStep+scan.ofs;
// float r0=baseRad;
// float k=(maxRad-r0)/y;
//
// bool ok=true;
// float r=r0+k*scan.ofs;
// for (int j=0; j<i; ++j, r+=k*verticalStep)
// if (scan.profile[j]>r) { ok=false; break; }
//
// if (!ok) break;
// cylStart=y;
// }
// }
// else
// maxRad=baseRad; // no base cone, just cylinder and nose
//
// float cylEnd=scan.profile.Count*verticalStep+scan.ofs;
//
// if (topBase!=null)
// {
// cylEnd=topY;
//
// if (maxRad>topRad)
// {
// // try to fit top cone as low as possible
// for (int i=scan.profile.Count-1; i>=0; --i)
// {
// float y=i*verticalStep+scan.ofs;
// float r0=topRad;
// float k=(maxRad-r0)/(y-topY);
//
// bool ok=true;
// float r=maxRad+k*verticalStep;
// for (int j=i; j<scan.profile.Count; ++j, r+=k*verticalStep)
// if (scan.profile[j]>r) { ok=false; break; }
//
// if (!ok) break;
//
// cylEnd=y;
// }
// }
// }
// else
// {
// // try to fit nose cone as low as possible
// for (int i=scan.profile.Count-1; i>=0; --i)
// {
// float s=verticalStep/noseHeightRatio;
//
// bool ok=true;
// float r=maxRad-s;
// for (int j=i; j<scan.profile.Count; ++j, r-=s)
// if (scan.profile[j]>r) { ok=false; break; }
//
// if (!ok) break;
//
// float y=i*verticalStep+scan.ofs;
// cylEnd=y;
// }
// }
//
// if (cylStart>cylEnd) cylStart=cylEnd;
//
// // build fairing shape line
// Vector3[] shape;
//
// if (topBase!=null)
// shape=buildInlineFairingShape(baseRad, maxRad, topRad, cylStart, cylEnd, topY,
// baseConeShape, baseConeSegments,
// vertMapping, mappingScale.y);
// else
// shape=buildFairingShape(baseRad, maxRad, cylStart, cylEnd, noseHeightRatio,
// baseConeShape, noseConeShape, baseConeSegments, noseConeSegments,
// vertMapping, mappingScale.y);
//
// if (sideNode==null)
// {
// // no side parts - fill fairing outlines
// foreach (var lr in outline)
// {
// lr.SetVertexCount(shape.Length);
// for (int i=0; i<shape.Length; ++i)
// lr.SetPosition(i, new Vector3(shape[i].x, shape[i].y));
// }
// }
// else
// {
// foreach (var lr in outline)
// lr.SetVertexCount(0);
// }
//
// // rebuild side parts
// int numSegs=circleSegments/numSideParts;
// if (numSegs<2) numSegs=2;
//
// foreach (var sn in attached)
// {
// var sp=sn.attachedPart;
// if (!sp) continue;
// var sf=sp.GetComponent<ProceduralFairingSide>();
// if (!sf) continue;
//
// var mf=sp.FindModelComponent<MeshFilter>("model");
// if (!mf) { Debug.LogError("[ProceduralFairingBase] no model in side fairing", sp); continue; }
//
// var nodePos=sn.position;
//
// mf.transform.position=part.transform.position;
// mf.transform.rotation=part.transform.rotation;
// float ra=Mathf.Atan2(-nodePos.z, nodePos.x)*Mathf.Rad2Deg;
// mf.transform.Rotate(0, ra, 0);
//
// sf.meshPos=mf.transform.localPosition;
// sf.meshRot=mf.transform.localRotation;
// sf.numSegs=numSegs;
// sf.numSideParts=numSideParts;
// sf.baseRad=baseRad;
// sf.maxRad=maxRad;
// sf.cylStart=cylStart;
// sf.cylEnd=cylEnd;
// sf.topRad=topRad;
// sf.inlineHeight=topY;
// sf.sideThickness=sideThickness;
// sf.rebuildMesh();
// }
// }
//}
//
//
////ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ//
//
//
//public class ProceduralFairingSide : PartModule
//{
// [KSPField] public float ejectionDv=15;
// [KSPField] public float ejectionTorque=0.2f;
// [KSPField] public float ejectionLowDv=1;
// [KSPField] public float ejectionLowTorque=0.01f;
//
// [KSPField] public string ejectionPowerKey="f";
// [KSPField(isPersistant=true)] public float ejectionPower=1;
//
// [KSPField] public string ejectSoundUrl="Squad/Sounds/sound_decoupler_fire";
// public FXGroup ejectFx;
//
// [KSPField] public float noseHeightRatio=2;
// [KSPField] public Vector4 baseConeShape=new Vector4(0.5f, 0, 1, 0.5f);
// [KSPField] public Vector4 noseConeShape=new Vector4(0.5f, 0, 1, 0.5f);
// [KSPField] public int baseConeSegments=5;
// [KSPField] public int noseConeSegments=7;
//
// [KSPField] public Vector2 mappingScale=new Vector2(1024, 1024);
// [KSPField] public Vector2 stripMapping=new Vector2(992, 1024);
// [KSPField] public Vector4 horMapping=new Vector4(0, 480, 512, 992);
// [KSPField] public Vector4 vertMapping=new Vector4(0, 160, 704, 1024);
//
// [KSPField] public float density=0.2f;
// [KSPField] public float specificBreakingForce =2000;
// [KSPField] public float specificBreakingTorque=2000;
//
// [KSPField(isPersistant=true)] public int numSegs=12;
// [KSPField(isPersistant=true)] public int numSideParts=2;
// [KSPField(isPersistant=true)] public float baseRad=1.25f;
// [KSPField(isPersistant=true)] public float maxRad=1.50f;
// [KSPField(isPersistant=true)] public float cylStart=0.5f;
// [KSPField(isPersistant=true)] public float cylEnd =2.5f;
// [KSPField(isPersistant=true)] public float topRad=0;
// [KSPField(isPersistant=true)] public float inlineHeight=0;
// [KSPField(isPersistant=true)] public float sideThickness=0.05f;
// [KSPField(isPersistant=true)] public Vector3 meshPos=Vector3.zero;
// [KSPField(isPersistant=true)] public Quaternion meshRot=Quaternion.identity;
//
//
// public override string GetInfo()
// {
// string s="Attach to Keramzit's fairing base to reshape.";
//
// if (!string.IsNullOrEmpty(ejectionPowerKey))
// s+="\nMouse over and press '"+ejectionPowerKey+"' to change ejection force.";
//
// return s;
// }
//
//
// public override void OnStart(StartState state)
// {
// if (state==StartState.None) return;
//
// ejectFx.audio=part.gameObject.AddComponent<AudioSource>();
// ejectFx.audio.volume=GameSettings.SHIP_VOLUME;
// ejectFx.audio.rolloffMode=AudioRolloffMode.Logarithmic;
// ejectFx.audio.panLevel=1;
// ejectFx.audio.maxDistance=100;
// ejectFx.audio.loop=false;
// ejectFx.audio.playOnAwake=false;
//
// if (GameDatabase.Instance.ExistsAudioClip(ejectSoundUrl))
// ejectFx.audio.clip=GameDatabase.Instance.GetAudioClip(ejectSoundUrl);
// else
// Debug.LogError("[ProceduralFairingSide] can't find sound: "+ejectSoundUrl, this);
//
// if (state!=StartState.Editor) rebuildMesh();
// }
//
//
// public void rebuildMesh()
// {
// var mf=part.FindModelComponent<MeshFilter>("model");
// if (!mf) { Debug.LogError("[ProceduralFairingSide] no model in side fairing", part); return; }
//
// Mesh m=mf.mesh;
// if (!m) { Debug.LogError("[ProceduralFairingSide] no mesh in side fairing", part); return; }
//
// mf.transform.localPosition=meshPos;
// mf.transform.localRotation=meshRot;
//
// // build fairing shape line
// float tip=maxRad*noseHeightRatio;
//
// Vector3[] shape;
// if (inlineHeight<=0)
// shape=ProceduralFairingBase.buildFairingShape(
// baseRad, maxRad, cylStart, cylEnd, noseHeightRatio,
// baseConeShape, noseConeShape, baseConeSegments, noseConeSegments,
// vertMapping, mappingScale.y);
// else
// shape=ProceduralFairingBase.buildInlineFairingShape(
// baseRad, maxRad, topRad, cylStart, cylEnd, inlineHeight,
// baseConeShape, baseConeSegments,
// vertMapping, mappingScale.y);
//
// // set up params
// var dirs=new Vector3[numSegs+1];
// for (int i=0; i<=numSegs; ++i)
// {
// float a=Mathf.PI*2*(i-numSegs*0.5f)/(numSideParts*numSegs);
// dirs[i]=new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a));
// }
//
// float segOMappingScale=(horMapping.y-horMapping.x)/(mappingScale.x*numSegs);
// float segIMappingScale=(horMapping.w-horMapping.z)/(mappingScale.x*numSegs);
// float segOMappingOfs=horMapping.x/mappingScale.x;
// float segIMappingOfs=horMapping.z/mappingScale.x;
//
// if (numSideParts>2)
// {
// segOMappingOfs+=segOMappingScale*numSegs*(0.5f-1f/numSideParts);
// segOMappingScale*=2f/numSideParts;
// segIMappingOfs+=segIMappingScale*numSegs*(0.5f-1f/numSideParts);
// segIMappingScale*=2f/numSideParts;
// }
//
// float stripU0=stripMapping.x/mappingScale.x;
// float stripU1=stripMapping.y/mappingScale.x;
//
// float ringSegLen=baseRad*Mathf.PI*2/(numSegs*numSideParts);
// float topRingSegLen=topRad*Mathf.PI*2/(numSegs*numSideParts);
//
// float collWidth=maxRad*Mathf.PI*2/(numSideParts*3);
//
// int numMainVerts=(numSegs+1)*(shape.Length-1)+1;
// int numMainFaces=numSegs*((shape.Length-2)*2+1);
//
// int numSideVerts=shape.Length*2;
// int numSideFaces=(shape.Length-1)*2;
//
// int numRingVerts=(numSegs+1)*2;
// int numRingFaces=numSegs*2;
//
// if (inlineHeight>0)
// {
// numMainVerts=(numSegs+1)*shape.Length;
// numMainFaces=numSegs*(shape.Length-1)*2;
// }
//
// int totalVerts=numMainVerts*2+numSideVerts*2+numRingVerts;
// int totalFaces=numMainFaces*2+numSideFaces*2+numRingFaces;
//
// if (inlineHeight>0)
// {
// totalVerts+=numRingVerts;
// totalFaces+=numRingFaces;
// }
//
// var p=shape[shape.Length-1];
// float topY=p.y, topV=p.z;
//
// float collCenter=(cylStart+cylEnd)/2, collHeight=cylEnd-cylStart;
// if (collHeight<=0) collHeight=Mathf.Min(topY-cylEnd, cylStart)/2;
//
// // compute area
// double area=0;
// for (int i=1; i<shape.Length; ++i)
// area+=(shape[i-1].x+shape[i].x)*(shape[i].y-shape[i-1].y)*Mathf.PI/numSideParts;
//
// // set params based on volume
// float volume=(float)(area*sideThickness);
// part.mass=volume*density;
// part.breakingForce =part.mass*specificBreakingForce;
// part.breakingTorque=part.mass*specificBreakingTorque;
//
// var offset=new Vector3(maxRad*0.7f, topY*0.5f, 0);
// part.CoMOffset=part.transform.InverseTransformPoint(mf.transform.TransformPoint(offset));
//
// // remove old colliders
// foreach (var c in part.FindModelComponents<Collider>())
// UnityEngine.Object.Destroy(c.gameObject);
//
// // add new colliders
// for (int i=-1; i<=1; ++i)
// {
// var obj=new GameObject("collider");
// obj.transform.parent=mf.transform;
// obj.transform.localPosition=Vector3.zero;
// obj.transform.localRotation=Quaternion.AngleAxis(90f*i/numSideParts, Vector3.up);
// var coll=obj.AddComponent<BoxCollider>();
// coll.center=new Vector3(maxRad+sideThickness*0.5f, collCenter, 0);
// coll.size=new Vector3(sideThickness, collHeight, collWidth);
// }
//
// {
// // nose collider
// float r=maxRad*0.2f;
// var obj=new GameObject("nose_collider");
// obj.transform.parent=mf.transform;
// obj.transform.localPosition=new Vector3(r, cylEnd+tip-r*1.2f, 0);
// obj.transform.localRotation=Quaternion.identity;
//
// if (inlineHeight>0)
// {
// r=sideThickness*0.5f;
// obj.transform.localPosition=new Vector3(maxRad+r, collCenter, 0);
// }
//
// var coll=obj.AddComponent<SphereCollider>();
// coll.center=Vector3.zero;
// coll.radius=r;
// }
//
// // build mesh
// m.Clear();
//
// var verts=new Vector3[totalVerts];
// var uv=new Vector2[totalVerts];
// var norm=new Vector3[totalVerts];
// var tang=new Vector4[totalVerts];
//
// if (inlineHeight<=0)
// {
// // tip vertex
// verts[numMainVerts -1].Set(0, topY+sideThickness, 0); // outside
// verts[numMainVerts*2-1].Set(0, topY, 0); // inside
// uv[numMainVerts -1].Set(segOMappingScale*0.5f*numSegs+segOMappingOfs, topV);
// uv[numMainVerts*2-1].Set(segIMappingScale*0.5f*numSegs+segIMappingOfs, topV);
// norm[numMainVerts -1]= Vector3.up;
// norm[numMainVerts*2-1]=-Vector3.up;
// // tang[numMainVerts -1]= Vector3.forward;
// // tang[numMainVerts*2-1]=-Vector3.forward;
// tang[numMainVerts -1]=Vector3.zero;
// tang[numMainVerts*2-1]=Vector3.zero;
// }
//
// // main vertices
// float noseV0=vertMapping.z/mappingScale.y;
// float noseV1=vertMapping.w/mappingScale.y;
// float noseVScale=1f/(noseV1-noseV0);
// float oCenter=(horMapping.x+horMapping.y)/(mappingScale.x*2);
// float iCenter=(horMapping.z+horMapping.w)/(mappingScale.x*2);
//
// int vi=0;
// for (int i=0; i<shape.Length-(inlineHeight<=0?1:0); ++i)
// {
// p=shape[i];
//
// Vector2 n;
// if (i==0) n=shape[1]-shape[0];
// else if (i==shape.Length-1) n=shape[i]-shape[i-1];
// else n=shape[i+1]-shape[i-1];
// n.Set(n.y, -n.x);
// n.Normalize();
//
// for (int j=0; j<=numSegs; ++j, ++vi)
// {
// var d=dirs[j];
// var dp=d*p.x+Vector3.up*p.y;
// var dn=d*n.x+Vector3.up*n.y;
// if (i==0 || i==shape.Length-1) verts[vi]=dp+d*sideThickness;
// else verts[vi]=dp+dn*sideThickness;
// verts[vi+numMainVerts]=dp;
//
// float v=(p.z-noseV0)*noseVScale;
// float uo=j*segOMappingScale+segOMappingOfs;
// float ui=(numSegs-j)*segIMappingScale+segIMappingOfs;
// if (v>0 && v<1)
// {
// float us=1-v;
// uo=(uo-oCenter)*us+oCenter;
// ui=(ui-iCenter)*us+iCenter;
// }
//
// uv[vi].Set(uo, p.z);
// uv[vi+numMainVerts].Set(ui, p.z);
//
// norm[vi]=dn;
// norm[vi+numMainVerts]=-dn;
// tang[vi].Set(-d.z, 0, d.x, 0);
// tang[vi+numMainVerts].Set(d.z, 0, -d.x, 0);
// }
// }
//
// // side strip vertices
// float stripScale=Mathf.Abs(stripMapping.y-stripMapping.x)/(sideThickness*mappingScale.y);
//
// vi=numMainVerts*2;
// float o=0;
// for (int i=0; i<shape.Length; ++i, vi+=2)
// {
// int si=i*(numSegs+1);
//
// var d=dirs[0];
// verts[vi]=verts[si];
// uv[vi].Set(stripU0, o);
// norm[vi].Set(d.z, 0, -d.x);
//
// verts[vi+1]=verts[si+numMainVerts];
// uv[vi+1].Set(stripU1, o);
// norm[vi+1]=norm[vi];
// tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized;
//
// if (i+1<shape.Length) o+=((Vector2)shape[i+1]-(Vector2)shape[i]).magnitude*stripScale;
// }
//
// vi+=numSideVerts-2;
// for (int i=shape.Length-1; i>=0; --i, vi-=2)
// {
// int si=i*(numSegs+1)+numSegs;
// if (i==shape.Length-1 && inlineHeight<=0) si=numMainVerts-1;
//
// var d=dirs[numSegs];
// verts[vi]=verts[si];
// uv[vi].Set(stripU0, o);
// norm[vi].Set(-d.z, 0, d.x);
//
// verts[vi+1]=verts[si+numMainVerts];
// uv[vi+1].Set(stripU1, o);
// norm[vi+1]=norm[vi];
// tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized;
//
// if (i>0) o+=((Vector2)shape[i]-(Vector2)shape[i-1]).magnitude*stripScale;
// }
//
// // ring vertices
// vi=numMainVerts*2+numSideVerts*2;
// o=0;
// for (int j=numSegs; j>=0; --j, vi+=2, o+=ringSegLen*stripScale)
// {
// verts[vi]=verts[j];
// uv[vi].Set(stripU0, o);
// norm[vi]=-Vector3.up;
//
// verts[vi+1]=verts[j+numMainVerts];
// uv[vi+1].Set(stripU1, o);
// norm[vi+1]=-Vector3.up;
// tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized;
// }
//
// if (inlineHeight>0)
// {
// // top ring vertices
// o=0;
// int si=(shape.Length-1)*(numSegs+1);
// for (int j=0; j<=numSegs; ++j, vi+=2, o+=topRingSegLen*stripScale)
// {
// verts[vi]=verts[si+j];
// uv[vi].Set(stripU0, o);
// norm[vi]=Vector3.up;
//
// verts[vi+1]=verts[si+j+numMainVerts];
// uv[vi+1].Set(stripU1, o);
// norm[vi+1]=Vector3.up;
// tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized;
// }
// }
//
// // set vertex data to mesh
// for (int i=0; i<totalVerts; ++i) tang[i].w=1;
// m.vertices=verts;
// m.uv=uv;
// m.normals=norm;
// m.tangents=tang;
//
// m.uv2=null;
// m.colors32=null;
//
// var tri=new int[totalFaces*3];
//
// // main faces
// vi=0;
// int ti1=0, ti2=numMainFaces*3;
// for (int i=0; i<shape.Length-(inlineHeight<=0?2:1); ++i, ++vi)
// {
// p=shape[i];
// for (int j=0; j<numSegs; ++j, ++vi)
// {
// tri[ti1++]=vi;
// tri[ti1++]=vi+1+numSegs+1;
// tri[ti1++]=vi+1;
//
// tri[ti1++]=vi;
// tri[ti1++]=vi +numSegs+1;
// tri[ti1++]=vi+1+numSegs+1;
//
// tri[ti2++]=numMainVerts+vi;
// tri[ti2++]=numMainVerts+vi+1;
// tri[ti2++]=numMainVerts+vi+1+numSegs+1;
//
// tri[ti2++]=numMainVerts+vi;
// tri[ti2++]=numMainVerts+vi+1+numSegs+1;
// tri[ti2++]=numMainVerts+vi +numSegs+1;
// }
// }
//
// if (inlineHeight<=0)
// {
// // main tip faces
// for (int j=0; j<numSegs; ++j, ++vi)
// {
// tri[ti1++]=vi;
// tri[ti1++]=numMainVerts-1;
// tri[ti1++]=vi+1;
//
// tri[ti2++]=numMainVerts+vi;
// tri[ti2++]=numMainVerts+vi+1;
// tri[ti2++]=numMainVerts+numMainVerts-1;
// }
// }
//
// // side strip faces
// vi=numMainVerts*2;
// ti1=numMainFaces*2*3;
// ti2=ti1+numSideFaces*3;
// for (int i=0; i<shape.Length-1; ++i, vi+=2)
// {
// tri[ti1++]=vi;
// tri[ti1++]=vi+1;
// tri[ti1++]=vi+3;
//
// tri[ti1++]=vi;
// tri[ti1++]=vi+3;
// tri[ti1++]=vi+2;
//
// tri[ti2++]=numSideVerts+vi;
// tri[ti2++]=numSideVerts+vi+3;
// tri[ti2++]=numSideVerts+vi+1;
//
// tri[ti2++]=numSideVerts+vi;
// tri[ti2++]=numSideVerts+vi+2;
// tri[ti2++]=numSideVerts+vi+3;
// }
//
// // ring faces
// vi=numMainVerts*2+numSideVerts*2;
// ti1=(numMainFaces+numSideFaces)*2*3;
// for (int j=0; j<numSegs; ++j, vi+=2)
// {
// tri[ti1++]=vi;
// tri[ti1++]=vi+1;
// tri[ti1++]=vi+3;
//
// tri[ti1++]=vi;
// tri[ti1++]=vi+3;
// tri[ti1++]=vi+2;
// }
//
// if (inlineHeight>0)
// {
// // top ring faces
// vi+=2;
// for (int j=0; j<numSegs; ++j, vi+=2)
// {
// tri[ti1++]=vi;
// tri[ti1++]=vi+1;
// tri[ti1++]=vi+3;
//
// tri[ti1++]=vi;
// tri[ti1++]=vi+3;
// tri[ti1++]=vi+2;
// }
// }
//
// m.triangles=tri;
//
// if (!HighLogic.LoadedSceneIsEditor) m.Optimize();
//
// part.SendEvent("FairingShapeChanged");
// }
//
//
// [KSPEvent(name = "Jettison", active=true, guiActive=true, guiActiveUnfocused=false, guiName="Jettison")]
// public void Jettison()
// {
// if (part.parent)
// {
// foreach (var p in part.parent.children)
// {
// var joint=p.GetComponent<ConfigurableJoint>();
// if (joint!=null && (joint.rigidbody==part.Rigidbody || joint.connectedBody==part.Rigidbody))
// Destroy(joint);
// }
//
// part.decouple(0);
//
// var tr=part.FindModelTransform("nose_collider");
// if (tr)
// {
// part.Rigidbody.AddForce(tr.right*Mathf.Lerp(ejectionLowDv, ejectionDv, ejectionPower),
// ForceMode.VelocityChange);
// part.Rigidbody.AddTorque(-tr.forward*Mathf.Lerp(ejectionLowTorque, ejectionTorque, ejectionPower),
// ForceMode.VelocityChange);
// }
// else
// Debug.LogError("[ProceduralFairingSide] no 'nose_collider' in side fairing", part);
//
// ejectFx.audio.Play();
// }
// }
//
//
// public override void OnActive()
// {
// Jettison();
// }
//
//
// [KSPAction("Jettison", actionGroup=KSPActionGroup.None)]
// public void ActionJettison(KSPActionParam param)
// {
// Jettison();
// }
//
//
// float osdMessageTime=0;
// string osdMessageText=null;
//
//
// public void OnMouseOver()
// {
// if (HighLogic.LoadedSceneIsEditor)
// {
// if (Input.GetKeyDown(ejectionPowerKey))
// {
// if (ejectionPower<0.25f) ejectionPower=0.5f;
// else if (ejectionPower<0.75f) ejectionPower=1;
// else ejectionPower=0;
//
// foreach (var p in part.symmetryCounterparts)
// p.GetComponent<ProceduralFairingSide>().ejectionPower=ejectionPower;
//
// osdMessageTime=Time.time+0.5f;
// osdMessageText="Fairing ejection force: ";
//
// if (ejectionPower<0.25f) osdMessageText+="low";
// else if (ejectionPower<0.75f) osdMessageText+="medium";
// else osdMessageText+="high";
// }
// }
// }
//
//
// public void OnGUI()
// {
// if (!HighLogic.LoadedSceneIsEditor) return;
//
// if (Time.time<osdMessageTime)
// {
// GUI.skin=HighLogic.Skin;
// GUIStyle style=new GUIStyle("Label");
// style.alignment=TextAnchor.MiddleCenter;
// style.fontSize=20;
// style.normal.textColor=Color.black;
// GUI.Label(new Rect(2, 2+(Screen.height/9), Screen.width, 50), osdMessageText, style);
// style.normal.textColor=Color.yellow;
// GUI.Label(new Rect(0, Screen.height/9, Screen.width, 50), osdMessageText, style);
// }
// }
//}
//
//struct BezierSlope
//{
// Vector2 p1, p2;
//
// public BezierSlope(Vector4 v)
// {
// p1=new Vector2(v.x, v.y);
// p2=new Vector2(v.z, v.w);
// }
//
// public Vector2 interp(float t)
// {
// Vector2 a=Vector2.Lerp(Vector2.zero, p1, t);
// Vector2 b=Vector2.Lerp(p1, p2, t);
// Vector2 c=Vector2.Lerp(p2, Vector2.one, t);
//
// Vector2 d=Vector2.Lerp(a, b, t);
// Vector2 e=Vector2.Lerp(b, c, t);
//
// return Vector2.Lerp(d, e, t);
// }
//}
//
//
//
//struct PayloadScan
//{
// public List<float> profile;
// public List<Part> payload;
// public HashSet<Part> hash;
//
// public List<Part> targets;
//
// public Matrix4x4 w2l;
//
// public float ofs, verticalStep, extraRadius;
//
//
// public PayloadScan(Part p, float vs, float er)
// {
// profile=new List<float>();
// payload=new List<Part>();
// targets=new List<Part>();
// hash=new HashSet<Part>();
// hash.Add(p);
// w2l=p.transform.worldToLocalMatrix;
// ofs=0;
// verticalStep=vs;
// extraRadius=er;
// }
//
//
// public void addPart(Part p, Part prevPart)
// {
// if (p==null || hash.Contains(p)) return;
// hash.Add(p);
//
// // check for another fairing base
// if (p.GetComponent<ProceduralFairingBase>()!=null)
// {
// AttachNode node=p.findAttachNode("top");
// if (node!=null && node.attachedPart==prevPart)
// {
// // reversed base - potential inline fairing target
// targets.Add(p);
// return;
// }
// }
//
// payload.Add(p);
// }
//
//
// public void addPayloadEdge(Vector3 v0, Vector3 v1)
// {
// float r0=Mathf.Sqrt(v0.x*v0.x+v0.z*v0.z)+extraRadius;
// float r1=Mathf.Sqrt(v1.x*v1.x+v1.z*v1.z)+extraRadius;
//
// float y0=(v0.y-ofs)/verticalStep;
// float y1=(v1.y-ofs)/verticalStep;
//
// if (y0>y1)
// {
// float tmp;
// tmp=y0; y0=y1; y1=tmp;
// tmp=r0; r0=r1; r1=tmp;
// }
//
// int h0=Mathf.FloorToInt(y0);
// int h1=Mathf.FloorToInt(y1);
// if (h1<0) return;
// if (h1>=profile.Count) profile.AddRange(Enumerable.Repeat(0f, h1-profile.Count+1));
//
// if (h0>=0) profile[h0]=Mathf.Max(profile[h0], r0);
// profile[h1]=Mathf.Max(profile[h1], r1);
//
// if (h0!=h1)
// {
// float k=(r1-r0)/(y1-y0);
// float b=r0+k*(h0+1-y0);
// float maxR=Mathf.Max(r0, r1);
//
// for (int h=Math.Max(h0, 0); h<h1; ++h)
// {
// float r=Mathf.Min(k*(h-h0)+b, maxR);
// profile[h ]=Mathf.Max(profile[h ], r);
// profile[h+1]=Mathf.Max(profile[h+1], r);
// }
// }
// }
//
//
// public void addPayload(Bounds box, Matrix4x4 boxTm)
// {
// Matrix4x4 m=w2l*boxTm;
//
// Vector3 p0=box.min, p1=box.max;
// var verts=new Vector3[8];
// for (int i=0; i<8; ++i)
// verts[i]=m.MultiplyPoint3x4(new Vector3(
// (i&1)!=0 ? p1.x : p0.x,
// (i&2)!=0 ? p1.y : p0.y,
// (i&4)!=0 ? p1.z : p0.z));
//
// addPayloadEdge(verts[0], verts[1]);
// addPayloadEdge(verts[2], verts[3]);
// addPayloadEdge(verts[4], verts[5]);
// addPayloadEdge(verts[6], verts[7]);
//
// addPayloadEdge(verts[0], verts[2]);
// addPayloadEdge(verts[1], verts[3]);
// addPayloadEdge(verts[4], verts[6]);
// addPayloadEdge(verts[5], verts[7]);
//
// addPayloadEdge(verts[0], verts[4]);
// addPayloadEdge(verts[1], verts[5]);
// addPayloadEdge(verts[2], verts[6]);
// addPayloadEdge(verts[3], verts[7]);
// }
//
//
// public void addPayload(Collider c)
// {
// var mc=c as MeshCollider;
// var bc=c as BoxCollider;
// if (mc)
// {
// // addPayload(mc.sharedMesh.bounds,
// // c.GetComponent<Transform>().localToWorldMatrix);
// var m=w2l*mc.transform.localToWorldMatrix;
// var verts=mc.sharedMesh.vertices;
// var faces=mc.sharedMesh.triangles;
// for (int i=0; i<faces.Length; i+=3)
// {
// var v0=m.MultiplyPoint3x4(verts[faces[i ]]);
// var v1=m.MultiplyPoint3x4(verts[faces[i+1]]);
// var v2=m.MultiplyPoint3x4(verts[faces[i+2]]);
// addPayloadEdge(v0, v1);
// addPayloadEdge(v1, v2);
// addPayloadEdge(v2, v0);
// }
// }
// else if (bc)
// addPayload(new Bounds(bc.center, bc.size),
// bc.transform.localToWorldMatrix);
// else
// {
// // Debug.Log("generic collider "+c);
// addPayload(c.bounds, Matrix4x4.identity);
// }
// }
//}
//
//
////ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ//
//
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Ceen;
using Ceen.Mvc;
using NUnit.Framework;
namespace Unittests
{
[Name("reporttarget")]
public class ReportExample : Controller
{
[HttpPost]
public async Task<IResult> Index(IHttpContext context)
{
var sb = new System.Text.StringBuilder();
foreach(var file in context.Request.Files)
sb.Append(await file.Data.ReadAllAsStringAsync());
if (context.Request.Files.Count == 0)
sb.Append("No content...");
return Text(sb.ToString());
}
}
[TestFixture()]
public class MultipartTests
{
[Test()]
public void TestSingleMultipart()
{
using (var server = new ServerRunner(
new Ceen.Httpd.ServerConfig()
{
AutoParseMultipartFormData = true,
}
.AddLogger((context, exception, started, duration) => Task.Run(() => Console.WriteLine("Error: {0}", exception)))
.AddRoute(
new[] { typeof(ReportExample) }
.ToRoute(
new ControllerRouterConfig()
{ Debug = true }
))
))
{
var payload = " ... some text data ...";
string result = null;
try
{
var boundary = "--test-boundary-1234";
var req = System.Net.WebRequest.CreateHttp($"http://127.0.0.1:{server.Port}/reporttarget");
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (var p = req.GetRequestStream())
{
var data = System.Text.Encoding.UTF8.GetBytes(
string.Join("\r\n",
$"--{boundary}",
"Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"",
"Content-Type: text/plain",
"",
payload,
$"--{boundary}--",
""
)
);
p.Write(data, 0, data.Length);
}
using (var res = (System.Net.HttpWebResponse)req.GetResponse())
using (var sr = new System.IO.StreamReader(res.GetResponseStream()))
result = sr.ReadToEnd();
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse)
result = ((System.Net.HttpWebResponse)wex.Response).StatusDescription;
else
throw;
}
Assert.AreEqual(payload, result);
}
}
[Test()]
public void TestDualMultipart()
{
using (var server = new ServerRunner(
new Ceen.Httpd.ServerConfig()
{
AutoParseMultipartFormData = true,
}
.AddLogger((context, exception, started, duration) => Task.Run(() => Console.WriteLine("Error: {0}", exception)))
.AddRoute(
new[] { typeof(ReportExample) }
.ToRoute(
new ControllerRouterConfig()
{ Debug = true }
))
))
{
var payload1 = " ... some text data ...";
var payload2 = " ... some other text data ...";
string result = null;
try
{
var boundary = "--test-boundary-1234";
var req = System.Net.WebRequest.CreateHttp($"http://127.0.0.1:{server.Port}/reporttarget");
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (var p = req.GetRequestStream())
{
var data = System.Text.Encoding.UTF8.GetBytes(
string.Join("\r\n",
$"--{boundary}",
"Content-Disposition: form-data; name=\"file1\"; filename=\"test1.txt\"",
"Content-Type: text/plain",
"",
payload1,
$"--{boundary}",
"Content-Disposition: form-data; name=\"file2\"; filename=\"test2.txt\"",
"Content-Type: text/plain",
"",
payload2,
$"--{boundary}--",
""
)
);
p.Write(data, 0, data.Length);
}
using (var res = (System.Net.HttpWebResponse)req.GetResponse())
using (var sr = new System.IO.StreamReader(res.GetResponseStream()))
result = sr.ReadToEnd();
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse)
result = ((System.Net.HttpWebResponse)wex.Response).StatusDescription;
else
throw;
}
Assert.AreEqual(payload1 + payload2, result);
}
}
[Test]
public void TestBadTrailingMultipart()
{
using (var server = new ServerRunner(
new Ceen.Httpd.ServerConfig()
{
AutoParseMultipartFormData = true,
}
.AddLogger((context, exception, started, duration) => Task.Run(() => Console.WriteLine("Error: {0}", exception)))
.AddRoute(
new[] { typeof(ReportExample) }
.ToRoute(
new ControllerRouterConfig()
{ Debug = true }
))
))
{
var payload = " ... some text data ...";
string result = null;
try
{
var boundary = "--test-boundary-1234";
var req = System.Net.WebRequest.CreateHttp($"http://127.0.0.1:{server.Port}/reporttarget");
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (var p = req.GetRequestStream())
{
var data = System.Text.Encoding.UTF8.GetBytes(
string.Join("\r\n",
$"--{boundary}",
"Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"",
"Content-Type: text/plain",
"",
payload,
$"--{boundary}--",
"",
"abc" // This should not be here...
)
);
p.Write(data, 0, data.Length);
}
using (var res = (System.Net.HttpWebResponse)req.GetResponse())
using (var sr = new System.IO.StreamReader(res.GetResponseStream()))
result = sr.ReadToEnd();
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse)
result = ((System.Net.HttpWebResponse)wex.Response).StatusDescription;
else
throw;
}
Assert.AreEqual("Bad Request", result);
}
}
}
}
| |
#region License
// Copyright 2010-2011 J.W.Marsden
//
// 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.
//
// Parts of this file are Copyright the Open Toolkit Library
// ---------------------------------------------------------------------------
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using OpenTK;
using OpenTK.Input;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace Kinetic.Provide
{
public class OpenTKGameWindow : NativeWindow, IDisposable
{
IGraphicsContext glContext;
VSyncMode vsync;
#region --- Contructors ---
#region public GameWindow()
/// <summary>Constructs a new GameWindow with sensible default attributes.</summary>
public OpenTKGameWindow () : this(640, 480, GraphicsMode.Default, "OpenTK Game Window", 0, DisplayDevice.Default)
{
}
#endregion
#region public GameWindow(int width, int height)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
public OpenTKGameWindow (int width, int height) : this(width, height, GraphicsMode.Default, "OpenTK Game Window", 0, DisplayDevice.Default)
{
}
#endregion
#region public GameWindow(int width, int height, GraphicsMode mode)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
public OpenTKGameWindow (int width, int height, GraphicsMode mode) : this(width, height, mode, "OpenTK Game Window", 0, DisplayDevice.Default)
{
}
#endregion
#region public GameWindow(int width, int height, GraphicsMode mode, string title)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
/// <param name="title">The title of the GameWindow.</param>
public OpenTKGameWindow (int width, int height, GraphicsMode mode, string title) : this(width, height, mode, title, 0, DisplayDevice.Default)
{
}
#endregion
#region public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
/// <param name="title">The title of the GameWindow.</param>
/// <param name="options">GameWindow options regarding window appearance and behavior.</param>
public OpenTKGameWindow (int width, int height, GraphicsMode mode, string title, GameWindowFlags options) : this(width, height, mode, title, options, DisplayDevice.Default)
{
}
#endregion
#region public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
/// <param name="title">The title of the GameWindow.</param>
/// <param name="options">GameWindow options regarding window appearance and behavior.</param>
/// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
public OpenTKGameWindow (int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device) : this(width, height, mode, title, options, device, 1, 0, GraphicsContextFlags.Default)
{
}
#endregion
#region public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device, int major, int minor, GraphicsContextFlags flags)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
/// <param name="title">The title of the GameWindow.</param>
/// <param name="options">GameWindow options regarding window appearance and behavior.</param>
/// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
/// <param name="major">The major version for the OpenGL GraphicsContext.</param>
/// <param name="minor">The minor version for the OpenGL GraphicsContext.</param>
/// <param name="flags">The GraphicsContextFlags version for the OpenGL GraphicsContext.</param>
public OpenTKGameWindow (int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device, int major, int minor, GraphicsContextFlags flags) : this(width, height, mode, title, options, device, major, minor, flags, null)
{
}
#endregion
#region public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device, int major, int minor, GraphicsContextFlags flags, IGraphicsContext sharedContext)
/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
/// <param name="width">The width of the GameWindow in pixels.</param>
/// <param name="height">The height of the GameWindow in pixels.</param>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
/// <param name="title">The title of the GameWindow.</param>
/// <param name="options">GameWindow options regarding window appearance and behavior.</param>
/// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
/// <param name="major">The major version for the OpenGL GraphicsContext.</param>
/// <param name="minor">The minor version for the OpenGL GraphicsContext.</param>
/// <param name="flags">The GraphicsContextFlags version for the OpenGL GraphicsContext.</param>
/// <param name="sharedContext">An IGraphicsContext to share resources with.</param>
public OpenTKGameWindow (int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device, int major, int minor, GraphicsContextFlags flags, IGraphicsContext sharedContext) : base(width, height, title, options, mode == null ? GraphicsMode.Default : mode, device == null ? DisplayDevice.Default : device)
{
try {
glContext = new GraphicsContext (mode == null ? GraphicsMode.Default : mode, WindowInfo, major, minor, flags);
glContext.MakeCurrent (WindowInfo);
(glContext as IGraphicsContextInternal).LoadAll ();
VSync = VSyncMode.On;
//glWindow.WindowInfoChanged += delegate(object sender, EventArgs e) { OnWindowInfoChangedInternal(e); };
} catch (Exception e) {
Console.WriteLine(e.StackTrace);
base.Dispose ();
throw;
}
}
#endregion
#endregion
/// <summary>
/// Disposes of the GameWindow, releasing all resources consumed by it.
/// </summary>
public override void Dispose ()
{
try {
Dispose(true);
} finally {
try {
if (glContext != null) {
glContext.Dispose ();
glContext = null;
}
} finally {
base.Dispose ();
}
}
GC.SuppressFinalize (this);
}
#region SwapBuffers
/// <summary>
/// Swaps the front and back buffer, presenting the rendered scene to the user.
/// </summary>
public void SwapBuffers ()
{
EnsureUndisposed ();
this.Context.SwapBuffers ();
}
#endregion
#region Properties
#region Context
/// <summary>
/// Returns the opengl IGraphicsContext associated with the current GameWindow.
/// </summary>
public IGraphicsContext Context {
get {
EnsureUndisposed ();
return glContext;
}
}
#endregion
#region Joysticks
/// <summary>
/// Gets a readonly IList containing all available OpenTK.Input.JoystickDevices.
/// </summary>
public IList<JoystickDevice> Joysticks {
get { return InputDriver.Joysticks; }
}
#endregion
#region Keyboard
/// <summary>
/// Gets the primary Keyboard device, or null if no Keyboard exists.
/// </summary>
public KeyboardDevice Keyboard {
get { return InputDriver.Keyboard.Count > 0 ? InputDriver.Keyboard[0] : null; }
}
#endregion
#region Mouse
/// <summary>
/// Gets the primary Mouse device, or null if no Mouse exists.
/// </summary>
public MouseDevice Mouse {
get { return InputDriver.Mouse.Count > 0 ? InputDriver.Mouse[0] : null; }
}
#endregion
#endregion
#region VSync
/// <summary>
/// Gets or sets the VSyncMode.
/// </summary>
public VSyncMode VSync {
get {
EnsureUndisposed ();
GraphicsContext.Assert ();
return vsync;
}
set {
EnsureUndisposed ();
GraphicsContext.Assert ();
Context.VSync = (vsync = value) != VSyncMode.Off;
}
}
#endregion
#region WindowState
/// <summary>
/// Gets or states the state of the NativeWindow.
/// </summary>
public override WindowState WindowState {
get { return base.WindowState; }
set {
base.WindowState = value;
//Debug.Print("Updating Context after setting WindowState to {0}", value);
if (Context != null)
Context.Update (WindowInfo);
}
}
#endregion
#region Dispose
/// <summary>
/// Override to add custom cleanup logic.
/// </summary>
/// <param name="manual">True, if this method was called by the application; false if this was called by the finalizer thread.</param>
protected virtual void Dispose (bool manual)
{
}
#endregion
#region OnResize
/// <summary>
/// Called when this window is resized.
/// </summary>
/// <param name="e">Not used.</param>
/// <remarks>
/// You will typically wish to update your viewport whenever
/// the window is resized. See the
/// <see cref="OpenTK.Graphics.OpenGL.GL.Viewport(int, int, int, int)"/> method.
/// </remarks>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
glContext.Update(base.WindowInfo);
}
#endregion
}
#region public enum VSyncMode
/// <summary>
/// Enumerates available VSync modes.
/// </summary>
public enum VSyncMode
{
/// <summary>
/// Vsync disabled.
/// </summary>
Off = 0,
/// <summary>
/// VSync enabled.
/// </summary>
On,
/// <summary>
/// VSync enabled, unless framerate falls below one half of target framerate.
/// If no target framerate is specified, this behaves exactly like <see cref="VSyncMode.On"/>.
/// </summary>
Adaptive
}
#endregion
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Clients;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Mshtml;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Progress;
namespace OpenLiveWriter.BlogClient.Detection
{
public class BlogEditingTemplateFile
{
public BlogEditingTemplateFile(BlogEditingTemplateType type, string file)
{
TemplateType = type;
TemplateFile = file;
}
public readonly BlogEditingTemplateType TemplateType;
public readonly string TemplateFile;
}
public enum BlogEditingTemplateType { Normal, Styled, Framed, Webpage };
/// <summary>
/// Manages the creation of a blog editor template based on the styles in a weblog.
/// This downloader will publish an temporary post to a weblog, and then re-download
/// the post so that the surrounding HTML can be parsed back out.
/// </summary>
public class BlogEditingTemplateDetector
{
public static BlogEditingTemplateFile[] DetectTemplate(IBlogClientUIContext uiContext, Control parentControl, IBlogSettingsAccessor blogSettings, bool probeForManifest, out Color? postBodyBackgroundColor)
{
postBodyBackgroundColor = null;
try
{
// create a new detector
BlogEditingTemplateDetector detector = new BlogEditingTemplateDetector(uiContext, parentControl, blogSettings, probeForManifest);
// execute with a progress dialog
ProgressHelper.ExecuteWithProgress(
Res.Get(StringId.DownloadingWeblogStyle),
new ProgressOperation(detector.DetectTemplate),
uiContext,
uiContext);
// propagate exception
if (detector.ExceptionOccurred)
throw detector.Exception;
postBodyBackgroundColor = detector.PostBodyBackgroundColor;
// return the template
return detector.BlogTemplateFiles;
}
catch (OperationCancelledException)
{
return new BlogEditingTemplateFile[0];
}
catch (BlogClientOperationCancelledException)
{
Debug.WriteLine("BlogClient operation cancelled");
return new BlogEditingTemplateFile[0];
}
catch (Exception e)
{
Trace.Fail("Error occurred while downloading weblog style" + e.ToString());
DisplayMessage.Show(MessageId.TemplateDownloadFailed);
return new BlogEditingTemplateFile[0];
}
}
private IBlogClientUIContext _uiContext;
public BlogEditingTemplateDetector(IBlogClientUIContext uiContext, Control parentControl, IBlogSettingsAccessor blogSettings, bool probeForManifest)
: this(uiContext, parentControl)
{
BlogAccount blogAccount = new BlogAccount(blogSettings.ServiceName, blogSettings.ClientType, blogSettings.PostApiUrl, blogSettings.HostBlogId);
string blogTemplateDir = BlogEditingTemplate.GetBlogTemplateDir(blogSettings.Id);
SetContext(blogAccount, blogSettings.Credentials, blogSettings.HomepageUrl, blogTemplateDir, blogSettings.ManifestDownloadInfo, probeForManifest, blogSettings.ProviderId, blogSettings.OptionOverrides, blogSettings.UserOptionOverrides, blogSettings.HomePageOverrides);
}
/// <summary>
/// Initialize BlogTemplateDetector without providing context (if you do not call
/// one of the SetContext methods prior to executing the Start method then the
/// BlogTemplateDetector will be a no-op that does not detect and download the template)
/// </summary>
/// <param name="parentControl"></param>
public BlogEditingTemplateDetector(IBlogClientUIContext uiContext, Control parentControl)
{
_uiContext = uiContext;
_parentControl = parentControl;
}
/// <summary>
/// SetContext using a weblog account
/// </summary>
public void SetContext(BlogAccount blogAccount, IBlogCredentialsAccessor credentials, string blogHomepageUrl, string blogTemplateDir, WriterEditingManifestDownloadInfo manifestDownloadInfo, bool probeForManifest, string providerId, IDictionary optionOverrides, IDictionary userOptionOverrides, IDictionary homepageOptionOverrides)
{
// note context set
_contextSet = true;
// create a blog client
_blogAccount = blogAccount;
_credentials = credentials;
_blogClient = BlogClientManager.CreateClient(blogAccount.ClientType, blogAccount.PostApiUrl, credentials, providerId, optionOverrides, userOptionOverrides, homepageOptionOverrides);
// set other context that we've got
_blogHomepageUrl = blogHomepageUrl;
_blogTemplateDir = blogTemplateDir;
_manifestDownloadInfo = manifestDownloadInfo;
_probeForManifest = probeForManifest;
}
public BlogEditingTemplateFile[] BlogTemplateFiles
{
get
{
return _blogTemplateFiles;
}
}
public Color? PostBodyBackgroundColor
{
get
{
return _postBodyBackgroundColor;
}
}
public bool ExceptionOccurred
{
get { return Exception != null; }
}
public Exception Exception
{
get { return _exception; }
}
private Exception _exception;
public object DetectTemplate(IProgressHost progress)
{
// if our context has not been set then just return without doing anything
// (supports this being an optional step at the end of a chain of
// other progress operations)
if (_contextSet == false)
return this;
using (BlogClientUIContextScope uiContextScope = new BlogClientUIContextScope(_uiContext))
{
// initial progress
progress.UpdateProgress(Res.Get(StringId.ProgressDetectingWeblogEditingStyle));
// build list of detected templates
ArrayList blogTemplateFiles = new ArrayList();
// build list of template types that we need to auto-detect
ArrayList detectionTargetTypes = new ArrayList();
ArrayList detectionTargetStrategies = new ArrayList();
// try explicit detection of templates
BlogEditingTemplateFiles templateFiles = SafeGetTemplates(new ProgressTick(progress, 50, 100));
// see if we got the FramedTempalte
if (templateFiles.FramedTemplate != null)
blogTemplateFiles.Add(templateFiles.FramedTemplate);
else
{
detectionTargetTypes.Add(BlogEditingTemplateType.Framed);
detectionTargetStrategies.Add(BlogEditingTemplateStrategies.GetTemplateStrategy(BlogEditingTemplateStrategies.StrategyType.NoSiblings));
}
// see if we got the WebPageTemplate
if (templateFiles.WebPageTemplate != null)
blogTemplateFiles.Add(templateFiles.WebPageTemplate);
else
{
detectionTargetTypes.Add(BlogEditingTemplateType.Webpage);
detectionTargetStrategies.Add(BlogEditingTemplateStrategies.GetTemplateStrategy(BlogEditingTemplateStrategies.StrategyType.Site));
}
// perform detection if we have detection targets
if (detectionTargetTypes.Count > 0)
{
BlogEditingTemplateFile[] detectedBlogTemplateFiles = DetectTemplates(new ProgressTick(progress, 50, 100),
detectionTargetTypes.ToArray(typeof(BlogEditingTemplateType)) as BlogEditingTemplateType[],
detectionTargetStrategies.ToArray(typeof(BlogEditingTemplateStrategy)) as BlogEditingTemplateStrategy[]);
if (detectedBlogTemplateFiles != null)
blogTemplateFiles.AddRange(detectedBlogTemplateFiles);
}
// updates member if we succeeded
if (blogTemplateFiles.Count > 0)
{
// capture template files
_blogTemplateFiles = blogTemplateFiles.ToArray(typeof(BlogEditingTemplateFile)) as BlogEditingTemplateFile[];
// if we got at least one template by some method then clear any exception
// that occurs so we can at least update that tempalte
_exception = null;
}
foreach (BlogEditingTemplateFile file in blogTemplateFiles)
{
if (file.TemplateType == BlogEditingTemplateType.Webpage)
{
_postBodyBackgroundColor = BackgroundColorDetector.DetectColor(UrlHelper.SafeToAbsoluteUri(new Uri(file.TemplateFile)), _postBodyBackgroundColor);
}
}
// return
return this;
}
}
private class BlogEditingTemplateFiles
{
public BlogEditingTemplateFile FramedTemplate;
public BlogEditingTemplateFile WebPageTemplate;
}
private BlogEditingTemplateFiles SafeGetTemplates(IProgressHost progress)
{
WriterEditingManifest editingManifest = null;
BlogEditingTemplateFiles templateFiles = new BlogEditingTemplateFiles();
try
{
// if we have a manifest url then try to get our manifest
if (_manifestDownloadInfo != null)
{
// try to get the editing manifest
string manifestUrl = _manifestDownloadInfo.SourceUrl;
editingManifest = WriterEditingManifest.FromUrl(
new Uri(manifestUrl),
_blogClient,
_credentials,
true);
// progress
CheckCancelRequested(progress);
progress.UpdateProgress(20, 100);
}
// if we have no editing manifest then probe (if allowed)
if ((editingManifest == null) && _probeForManifest)
{
editingManifest = WriterEditingManifest.FromHomepage(
new LazyHomepageDownloader(_blogHomepageUrl, new HttpRequestHandler(_blogClient.SendAuthenticatedHttpRequest)),
new Uri(_blogHomepageUrl),
_blogClient,
_credentials);
}
// progress
CheckCancelRequested(progress);
progress.UpdateProgress(40, 100);
// if we got one then return templates from it as-appropriate
if (editingManifest != null)
{
if (editingManifest.WebLayoutUrl != null)
{
string webLayoutTemplate = DownloadManifestTemplate(new ProgressTick(progress, 10, 100), editingManifest.WebLayoutUrl);
if (BlogEditingTemplate.ValidateTemplate(webLayoutTemplate))
{
// download supporting files
string templateFile = DownloadTemplateFiles(webLayoutTemplate, _blogHomepageUrl, new ProgressTick(progress, 20, 100));
// return the template
templateFiles.FramedTemplate = new BlogEditingTemplateFile(BlogEditingTemplateType.Framed, templateFile);
}
else
{
Trace.WriteLine("Invalid webLayoutTemplate specified in manifest");
}
}
if (editingManifest.WebPreviewUrl != null)
{
string webPreviewTemplate = DownloadManifestTemplate(new ProgressTick(progress, 10, 100), editingManifest.WebPreviewUrl);
if (BlogEditingTemplate.ValidateTemplate(webPreviewTemplate))
{
// download supporting files
string templateFile = DownloadTemplateFiles(webPreviewTemplate, _blogHomepageUrl, new ProgressTick(progress, 20, 100));
// return the template
templateFiles.WebPageTemplate = new BlogEditingTemplateFile(BlogEditingTemplateType.Webpage, templateFile);
}
else
{
Trace.WriteLine("Invalid webPreviewTemplate specified in manifest");
}
}
}
}
catch
{
}
finally
{
progress.UpdateProgress(100, 100);
}
return templateFiles;
}
private string DownloadManifestTemplate(IProgressHost progress, string manifestTemplateUrl)
{
try
{
// update progress
progress.UpdateProgress(0, 100, Res.Get(StringId.ProgressDownloadingEditingTemplate));
// process any parameters within the url
string templateUrl = BlogClientHelper.FormatUrl(manifestTemplateUrl, _blogHomepageUrl, _blogAccount.PostApiUrl, _blogAccount.BlogId);
// download the url
using (StreamReader streamReader = new StreamReader(_blogClient.SendAuthenticatedHttpRequest(templateUrl, 20000, null).GetResponseStream()))
return streamReader.ReadToEnd();
}
catch (Exception ex)
{
Trace.WriteLine("Exception occurred while attempting to download template from " + manifestTemplateUrl + " :" + ex.ToString());
return null;
}
finally
{
progress.UpdateProgress(100, 100);
}
}
/// <summary>
///
/// </summary>
/// <param name="progress"></param>
/// <param name="targetTemplateTypes"></param>
/// <param name="templateStrategies">equivalent strategies for manipulating the blog homepage DOM into an editing template type</param>
/// <returns></returns>
private BlogEditingTemplateFile[] DetectTemplates(IProgressHost progress, BlogEditingTemplateType[] targetTemplateTypes, BlogEditingTemplateStrategy[] templateStrategies)
{
RecentPostRegionLocatorStrategy recentPostLocatorStrategy =
new RecentPostRegionLocatorStrategy(_blogClient, _blogAccount, _credentials, _blogHomepageUrl,
new PageDownloader(RequestPageDownload));
TemporaryPostRegionLocatorStrategy tempPostLocatorStrategy =
new TemporaryPostRegionLocatorStrategy(_blogClient, _blogAccount, _credentials, _blogHomepageUrl,
new PageDownloader(RequestPageDownload), new BlogPostRegionLocatorBooleanCallback(recentPostLocatorStrategy.HasBlogPosts));
//setup the strategies for locating the title/body regions in the blog homepage.
BlogPostRegionLocatorStrategy[] regionLocatorStrategies = new BlogPostRegionLocatorStrategy[]
{
recentPostLocatorStrategy,
tempPostLocatorStrategy
};
// template files to return
BlogEditingTemplateFile[] blogTemplateFiles = null;
// try each strategy as necessary
for (int i = 0; i < regionLocatorStrategies.Length && blogTemplateFiles == null; i++)
{
CheckCancelRequested(progress);
//reset the progress for each iteration
BlogPostRegionLocatorStrategy regionLocatorStrategy = regionLocatorStrategies[i];
try
{
blogTemplateFiles = GetBlogTemplateFiles(progress, regionLocatorStrategy, templateStrategies, targetTemplateTypes);
progress.UpdateProgress(100, 100);
//if any exception occured along the way, clear them since one of the template strategies
//was successful.
_exception = null;
}
catch (OperationCancelledException)
{
// cancel just means our template will be String.Empty
_exception = null;
}
catch (BlogClientOperationCancelledException e)
{
// cancel just means our template will be String.Empty
// (setting this exception here means that at least the user
// will be notified that they won't be able to edit with style)
_exception = e;
}
catch (BlogClientAbortGettingTemplateException e)
{
_exception = e;
//Do not proceed with the other strategies if getting the template was aborted.
break;
}
catch (WebException e)
{
_exception = e;
Trace.WriteLine("Error occurred while downloading weblog style: " + e.ToString());
if (e.Response != null)
{
Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "Blogpost homepage request failed: {0}", _blogHomepageUrl));
//Debug.WriteLine(HttpRequestHelper.DumpResponse((HttpWebResponse)e.Response));
}
}
catch (Exception e)
{
_exception = e;
Trace.WriteLine("Error occurred while downloading weblog style: " + e.ToString());
}
}
// return the detected tempaltes
return blogTemplateFiles;
}
/// <summary>
/// Creates a set of BlogTemplateFiles using a specific region locator strategy.
/// </summary>
/// <param name="progress"></param>
/// <param name="regionLocatorStrategy"></param>
/// <param name="templateStrategies"></param>
/// <param name="templateTypes"></param>
/// <returns></returns>
private BlogEditingTemplateFile[] GetBlogTemplateFiles(IProgressHost progress, BlogPostRegionLocatorStrategy regionLocatorStrategy, BlogEditingTemplateStrategy[] templateStrategies, BlogEditingTemplateType[] templateTypes)
{
BlogEditingTemplateFile[] blogTemplateFiles = null;
try
{
regionLocatorStrategy.PrepareRegions(new ProgressTick(progress, 25, 100));
ArrayList templateFiles = new ArrayList();
ProgressTick tick = new ProgressTick(progress, 50, 100);
for (int i = 0; i < templateTypes.Length; i++)
{
ProgressTick parseTick = new ProgressTick(tick, 1, templateTypes.Length);
try
{
CheckCancelRequested(parseTick);
templateStrategy = templateStrategies[i];
// Parse the blog post HTML into an editing template.
// Note: we can't use MarkupServices to parse the document from a non-UI thread,
// so we have to execute the parsing portion of the template download operation on the UI thread.
string editingTemplate = ParseWebpageIntoEditingTemplate_OnUIThread(_parentControl, regionLocatorStrategy, new ProgressTick(parseTick, 1, 5));
// check for cancel
CheckCancelRequested(parseTick);
string baseUrl = HTMLDocumentHelper.GetBaseUrl(editingTemplate, _blogHomepageUrl);
// Download the template stylesheets and embedded resources (this lets the editing template load faster..and works offline!)
string templateFile = DownloadTemplateFiles(editingTemplate, baseUrl, new ProgressTick(parseTick, 4, 5));
templateFiles.Add(new BlogEditingTemplateFile(templateTypes[i], templateFile));
}
catch(BlogClientAbortGettingTemplateException)
{
Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Failed to download template {0}. Aborting getting further templates", templateTypes[i].ToString()));
throw;
}
catch (Exception e)
{
Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Failed to download template {0}: {1}", templateTypes[i].ToString(), e.ToString()));
}
}
if (templateFiles.Count > 0)
blogTemplateFiles = (BlogEditingTemplateFile[])templateFiles.ToArray(typeof(BlogEditingTemplateFile));
}
finally
{
regionLocatorStrategy.CleanupRegions(new ProgressTick(progress, 25, 100));
}
return blogTemplateFiles;
}
private void CheckCancelRequested(IProgressHost progress)
{
if (progress.CancelRequested)
throw new OperationCancelledException();
}
private void NoCacheFilter(HttpWebRequest request)
{
request.Headers.Add("Pragma", "no-cache");
}
private HttpWebResponse RequestPageDownload(string url, int timeoutMs)
{
return _blogClient.SendAuthenticatedHttpRequest(url, timeoutMs, new HttpRequestFilter(NoCacheFilter));
}
private void ApplyCredentials(PageAndReferenceDownloader downloader, string url)
{
WinInetCredentialsContext credentialsContext = CreateCredentialsContext(url);
if (credentialsContext != null)
downloader.CredentialsContext = credentialsContext;
}
private void ApplyCredentials(PageDownloadContext downloadContext, string url)
{
WinInetCredentialsContext credentialsContext = CreateCredentialsContext(url);
if (credentialsContext != null && credentialsContext.CookieString != null)
downloadContext.CookieString = credentialsContext.CookieString.Cookies;
}
private WinInetCredentialsContext CreateCredentialsContext(string url)
{
try
{
return BlogClientHelper.GetCredentialsContext(_blogClient, _credentials, url);
}
catch (BlogClientOperationCancelledException)
{
return null;
}
}
/// <summary>
/// Parses a webpage into an editing template using a marshalled callback on the UI context's thread.
/// </summary>
/// <param name="uiContext"></param>
/// <param name="progress"></param>
/// <returns></returns>
private string ParseWebpageIntoEditingTemplate_OnUIThread(Control uiContext, BlogPostRegionLocatorStrategy regionLocator, IProgressHost progress)
{
BlogEditingTemplate blogEditingTemplate = (BlogEditingTemplate)uiContext.Invoke(new TemplateParser(ParseBlogPostIntoTemplate), new object[] { regionLocator, new ProgressTick(progress, 1, 100) });
return blogEditingTemplate.Template;
}
private delegate BlogEditingTemplate TemplateParser(BlogPostRegionLocatorStrategy regionLocator, IProgressHost progress);
private BlogEditingTemplate ParseBlogPostIntoTemplate(BlogPostRegionLocatorStrategy regionLocator, IProgressHost progress)
{
progress.UpdateProgress(Res.Get(StringId.ProgressCreatingEditingTemplate));
BlogPostRegions regions = regionLocator.LocateRegionsOnUIThread(progress);
IHTMLElement primaryTitleRegion = GetPrimaryEditableTitleElement(regions.BodyRegion, regions.Document, regions.TitleRegions);
BlogEditingTemplate template = GenerateBlogTemplate((IHTMLDocument3)regions.Document, primaryTitleRegion, regions.TitleRegions, regions.BodyRegion);
progress.UpdateProgress(100, 100);
return template;
}
/// <summary>
/// Disambiguates a set of title regions to determine which should be editable based on proximity to the main post body element.
/// </summary>
/// <param name="bodyElement"></param>
/// <param name="doc"></param>
/// <param name="titleElements"></param>
/// <returns>The title region in closest proximity to the post body element.</returns>
protected static IHTMLElement GetPrimaryEditableTitleElement(IHTMLElement bodyElement, IHTMLDocument doc, IHTMLElement[] titleElements)
{
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
IHTMLElement titleElement = titleElements[0];
if (titleElements.Length > 1)
{
try
{
MshtmlMarkupServices markupServices = new MshtmlMarkupServices((IMarkupServicesRaw)doc2);
MarkupRange bodyRange = markupServices.CreateMarkupRange(bodyElement, true);
MarkupPointer titlePointer = null;
MarkupPointer tempPointer = markupServices.CreateMarkupPointer();
foreach (IHTMLElement title in titleElements)
{
tempPointer.MoveAdjacentToElement(title, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
if (titlePointer == null)
titlePointer = markupServices.CreateMarkupPointer(title, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
else
{
tempPointer.MoveAdjacentToElement(title, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
if (tempPointer.IsLeftOf(bodyRange.End) && tempPointer.IsRightOf(titlePointer))
{
//the temp pointer is closer to the body element, so assume it is more appropriate
//to use as the title.
titleElement = title;
titlePointer.MoveToPointer(tempPointer);
}
}
}
}
catch (COMException ex)
{
Trace.WriteLine("Failed to differentiate between multiple nodes with title text, using the first node. Exception: " + ex);
}
catch (InvalidCastException ex)
{
Trace.WriteLine("Failed to differentiate between multiple nodes with title text, using the first node. Exception: " + ex);
}
}
return titleElement;
}
private string DownloadTemplateFiles(string templateContents, string templateUrl, IProgressHost progress)
{
progress.UpdateProgress(Res.Get(StringId.ProgressDownloadingSupportingFiles));
FileBasedSiteStorage files = new FileBasedSiteStorage(_blogTemplateDir);
// convert the string to a stream
MemoryStream templateStream = new MemoryStream();
StreamWriter writer = new StreamWriter(templateStream, Encoding.UTF8);
writer.Write(templateContents);
writer.Flush();
templateStream.Seek(0, SeekOrigin.Begin);
//read the stream into a lightweight HTML. Note that we use from LightWeightHTMLDocument.FromIHTMLDocument2
//instead of LightWeightHTMLDocument.FromStream because from stream improperly shoves a saveFrom declaration
//above the docType (bug 289357)
IHTMLDocument2 doc = HTMLDocumentHelper.StreamToHTMLDoc(templateStream, templateUrl, true);
LightWeightHTMLDocument ldoc = LightWeightHTMLDocument.FromIHTMLDocument2(doc, templateUrl, true, false);
PageDownloadContext downloadContext = new PageDownloadContext(0);
ApplyCredentials(downloadContext, templateUrl);
using (PageToDownloadFactory downloadFactory = new PageToDownloadFactory(ldoc, downloadContext, _parentControl))
{
//calculate the dependent styles and resources
ProgressTick tick = new ProgressTick(progress, 50, 100);
downloadFactory.CreatePagesToDownload(tick);
tick.UpdateProgress(100, 100);
//download the dependent styles and resources
tick = new ProgressTick(progress, 50, 100);
PageAndReferenceDownloader downloader = new PageAndReferenceDownloader(downloadFactory.PagesToDownload, files);
this.ApplyCredentials(downloader, templateUrl);
downloader.Download(tick);
tick.UpdateProgress(100, 100);
//Expand out the relative paths in the downloaded HTML file with absolute paths.
//Note: this is necessary so that template resources are not improperly resolved relative
// to the location of the file the editor is editing.
string blogTemplateFile = Path.Combine(_blogTemplateDir, files.RootFile);
string origFile = blogTemplateFile + ".token";
File.Move(blogTemplateFile, origFile);
string absPath = String.Format(CultureInfo.InvariantCulture, "file:///{0}/{1}", _blogTemplateDir.Replace('\\', '/'), downloader.PathToken);
TextHelper.ReplaceInFile(origFile, downloader.PathToken, blogTemplateFile, absPath);
File.Delete(origFile);
//fix up the files
FixupDownloadedFiles(blogTemplateFile, files, downloader.PathToken);
//complete the progress.
progress.UpdateProgress(100, 100);
File.WriteAllText(blogTemplateFile + ".path", absPath);
return blogTemplateFile;
}
}
/// <summary>
/// Fixes up the downloaded supporting files that were in the template.
/// </summary>
/// <param name="blogTemplateFile"></param>
/// <param name="storage"></param>
/// <param name="supportingFilesDir"></param>
protected internal virtual void FixupDownloadedFiles(string blogTemplateFile, FileBasedSiteStorage storage, string supportingFilesDir)
{
templateStrategy.FixupDownloadedFiles(blogTemplateFile, storage, supportingFilesDir);
}
private BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
{
return templateStrategy.GenerateBlogTemplate(doc, titleElement, allTitleElements, bodyElement);
}
BlogEditingTemplateStrategy templateStrategy = BlogEditingTemplateStrategies.GetTemplateStrategy(BlogEditingTemplateStrategies.StrategyType.FramedWysiwyg);
// execution context
private Control _parentControl;
private bool _contextSet = false;
private BlogAccount _blogAccount;
private IBlogClient _blogClient;
private string _blogHomepageUrl;
private string _blogTemplateDir;
private WriterEditingManifestDownloadInfo _manifestDownloadInfo;
private bool _probeForManifest = false;
private IBlogCredentialsAccessor _credentials;
// return value
private BlogEditingTemplateFile[] _blogTemplateFiles = new BlogEditingTemplateFile[0];
private Color? _postBodyBackgroundColor;
}
public delegate HttpWebResponse PageDownloader(string url, int timeoutMs);
}
| |
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Signum.Entities.Files;
using System.Collections.Concurrent;
using System.IO;
namespace Signum.Engine.Files;
public static class BlobContainerClientPool
{
static ConcurrentDictionary<(string connectionString, string blobContainerName), BlobContainerClient> Pool =
new ConcurrentDictionary<(string connectionString, string blobContainerName), BlobContainerClient>();
public static BlobContainerClient Get(string connectionString, string blobContainerName)
{
return Pool.GetOrAdd((connectionString, blobContainerName), t => new BlobContainerClient(t.connectionString, t.blobContainerName));
}
}
public enum BlobAction
{
Open,
Download
}
public class AzureBlobStoragebFileTypeAlgorithm : FileTypeAlgorithmBase, IFileTypeAlgorithm
{
public Func<IFilePath, BlobContainerClient> GetClient { get; private set; }
public Func<bool> WebDownload { get; private set; } = () => false;
public Func<IFilePath, string> CalculateSuffix { get; set; } = SuffixGenerators.Safe.YearMonth_Guid_Filename;
public bool WeakFileReference { get; set; }
public bool CreateBlobContainerIfNotExists { get; set; }
//ExistBlob is too slow, consider using CalculateSuffix with a GUID!
public Func<string, int, string>? RenameAlgorithm { get; set; } = null; // FileTypeAlgorithm.DefaultRenameAlgorithm;
public Func<IFilePath, BlobAction> BlobAction { get; set; } = (IFilePath ifp) => { return Files.BlobAction.Download; };
public AzureBlobStoragebFileTypeAlgorithm(Func<IFilePath, BlobContainerClient> getClient)
{
this.GetClient = getClient;
}
public PrefixPair GetPrefixPair(IFilePath efp)
{
var client = GetClient(efp);
if (!this.WebDownload())
return PrefixPair.None();
//return PrefixPair.WebOnly($"https://{client.Uri}/{efp.Suffix}");
return PrefixPair.WebOnly($"{client.Uri}");
}
public BlobProperties GetProperties(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage GetProperties"))
{
var client = GetClient(fp);
return client.GetBlobClient(fp.Suffix).GetProperties();
}
}
public Stream OpenRead(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage OpenRead"))
{
var client = GetClient(fp);
return client.GetBlobClient(fp.Suffix).Download().Value.Content;
}
}
public byte[] ReadAllBytes(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage ReadAllBytes"))
{
var client = GetClient(fp);
return client.GetBlobClient(fp.Suffix).Download().Value.Content.ReadAllBytes();
}
}
public virtual void SaveFile(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage SaveFile"))
using (new EntityCache(EntityCacheType.ForceNew))
{
if (WeakFileReference)
return;
BlobContainerClient client = CalculateSuffixWithRenames(fp);
try
{
var blobHeaders = GetBlobHttpHeaders(fp, this.BlobAction(fp));
var blobClient = client.GetBlobClient(fp.Suffix);
var binaryFile = fp.BinaryFile; //For consistency with async
fp.BinaryFile = null!;
SaveFileInAzure(blobClient, blobHeaders, binaryFile);
}
catch (Exception ex)
{
ex.Data.Add("Suffix", fp.Suffix);
ex.Data.Add("AccountName", client.AccountName);
ex.Data.Add("ContainerName", client.Name);
throw;
}
}
}
private static void SaveFileInAzure(BlobClient blobClient, BlobHttpHeaders blobHeaders, byte[] binaryFile)
{
blobClient.Upload(new MemoryStream(binaryFile), httpHeaders: blobHeaders);
}
//Initial exceptions (like connection string problems) should happen synchronously
public virtual /*async*/ Task SaveFileAsync(IFilePath fp, CancellationToken cancellationToken = default)
{
using (HeavyProfiler.Log("AzureBlobStorage SaveFile"))
using (new EntityCache(EntityCacheType.ForceNew))
{
if (WeakFileReference)
return Task.CompletedTask;
BlobContainerClient client = CalculateSuffixWithRenames(fp);
try
{
var headers = GetBlobHttpHeaders(fp, this.BlobAction(fp));
var blobClient = client.GetBlobClient(fp.Suffix);
var binaryFile = fp.BinaryFile;
fp.BinaryFile = null!; //So the entity is not modified after await
return SaveFileInAzureAsync(blobClient, binaryFile, headers, fp.Suffix, cancellationToken);
}
catch (Exception ex)
{
ex.Data.Add("Suffix", fp.Suffix);
ex.Data.Add("AccountName", client.AccountName);
ex.Data.Add("ContainerName", client.Name);
throw;
}
}
}
static async Task SaveFileInAzureAsync(BlobClient blobClient, byte[] binaryFile, BlobHttpHeaders headers, string suffixForException, CancellationToken cancellationToken)
{
try
{
await blobClient.UploadAsync(new MemoryStream(binaryFile), httpHeaders: headers, cancellationToken: cancellationToken);
}
catch (Exception ex)
{
ex.Data.Add("Suffix", suffixForException);
ex.Data.Add("AccountName", blobClient.AccountName);
ex.Data.Add("ContainerName", blobClient.Name);
throw;
}
}
private BlobContainerClient CalculateSuffixWithRenames(IFilePath fp)
{
using (HeavyProfiler.LogNoStackTrace("CalculateSuffixWithRenames"))
{
string suffix = CalculateSuffix(fp);
if (!suffix.HasText())
throw new InvalidOperationException("Suffix not set");
fp.SetPrefixPair(GetPrefixPair(fp));
var client = GetClient(fp);
if (CreateBlobContainerIfNotExists)
{
using (HeavyProfiler.LogNoStackTrace("AzureBlobStorage CreateIfNotExists"))
{
client.CreateIfNotExists();
CreateBlobContainerIfNotExists = false;
}
}
int i = 2;
fp.Suffix = suffix.Replace("\\", "/");
if (RenameAlgorithm != null)
{
while (HeavyProfiler.LogNoStackTrace("ExistBlob").Using(_ => client.ExistsBlob(fp.Suffix)))
{
fp.Suffix = RenameAlgorithm(suffix, i).Replace("\\", "/");
i++;
}
}
return client;
}
}
private static BlobHttpHeaders GetBlobHttpHeaders(IFilePath fp, BlobAction action)
{
var contentType = action == Files.BlobAction.Download ? "application/octet-stream" :
ContentTypesDict.TryGet(Path.GetExtension(fp.FileName).ToLowerInvariant(), "application/octet-stream");
return new BlobHttpHeaders
{
ContentType = contentType,
ContentDisposition = action == Files.BlobAction.Download ? "attachment" : "inline"
};
}
public void MoveFile(IFilePath ofp, IFilePath nfp)
{
using (HeavyProfiler.Log("AzureBlobStorage MoveFile"))
{
if (WeakFileReference)
return;
throw new NotImplementedException();
}
}
public void DeleteFiles(IEnumerable<IFilePath> files)
{
using (HeavyProfiler.Log("AzureBlobStorage DeleteFiles"))
{
if (WeakFileReference)
return;
foreach (var f in files)
{
GetClient(f).DeleteBlob(f.Suffix);
}
}
}
public void DeleteFilesIfExist(IEnumerable<IFilePath> files)
{
using (HeavyProfiler.Log("AzureBlobStorage DeleteFiles"))
{
if (WeakFileReference)
return;
foreach (var f in files)
{
GetClient(f).DeleteBlobIfExists(f.Suffix);
}
}
}
public readonly static Dictionary<string, string> ContentTypesDict = new Dictionary<string, string>()
{
{".x3d", "application/vnd.hzn-3d-crossword"},
{".3gp", "video/3gpp"},
{".3g2", "video/3gpp2"},
{".mseq", "application/vnd.mseq"},
{".pwn", "application/vnd.3m.post-it-notes"},
{".plb", "application/vnd.3gpp.pic-bw-large"},
{".psb", "application/vnd.3gpp.pic-bw-small"},
{".pvb", "application/vnd.3gpp.pic-bw-var"},
{".tcap", "application/vnd.3gpp2.tcap"},
{".7z", "application/x-7z-compressed"},
{".abw", "application/x-abiword"},
{".ace", "application/x-ace-compressed"},
{".acc", "application/vnd.americandynamics.acc"},
{".acu", "application/vnd.acucobol"},
{".atc", "application/vnd.acucorp"},
{".adp", "audio/adpcm"},
{".aab", "application/x-authorware-bin"},
{".aam", "application/x-authorware-map"},
{".aas", "application/x-authorware-seg"},
{".air", "application/vnd.adobe.air-application-installer-package+zip"},
{".swf", "application/x-shockwave-flash"},
{".fxp", "application/vnd.adobe.fxp"},
{".pdf", "application/pdf"},
{".ppd", "application/vnd.cups-ppd"},
{".dir", "application/x-director"},
{".xdp", "application/vnd.adobe.xdp+xml"},
{".xfdf", "application/vnd.adobe.xfdf"},
{".aac", "audio/x-aac"},
{".ahead", "application/vnd.ahead.space"},
{".azf", "application/vnd.airzip.filesecure.azf"},
{".azs", "application/vnd.airzip.filesecure.azs"},
{".azw", "application/vnd.amazon.ebook"},
{".ami", "application/vnd.amiga.ami"},
{".apk", "application/vnd.android.package-archive"},
{".cii", "application/vnd.anser-web-certificate-issue-initiation"},
{".fti", "application/vnd.anser-web-funds-transfer-initiation"},
{".atx", "application/vnd.antix.game-component"},
{".mpkg", "application/vnd.apple.installer+xml"},
{".aw", "application/applixware"},
{".les", "application/vnd.hhe.lesson-player"},
{".swi", "application/vnd.aristanetworks.swi"},
{".s", "text/x-asm"},
{".atomcat", "application/atomcat+xml"},
{".atomsvc", "application/atomsvc+xml"},
{".atom, .xml", "application/atom+xml"},
{".ac", "application/pkix-attr-cert"},
{".aif", "audio/x-aiff"},
{".avi", "video/x-msvideo"},
{".aep", "application/vnd.audiograph"},
{".dxf", "image/vnd.dxf"},
{".dwf", "model/vnd.dwf"},
{".par", "text/plain-bas"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".torrent", "application/x-bittorrent"},
{".cod", "application/vnd.rim.cod"},
{".mpm", "application/vnd.blueice.multipass"},
{".bmi", "application/vnd.bmi"},
{".sh", "application/x-sh"},
{".btif", "image/prs.btif"},
{".rep", "application/vnd.businessobjects"},
{".bz", "application/x-bzip"},
{".bz2", "application/x-bzip2"},
{".csh", "application/x-csh"},
{".c", "text/x-c"},
{".cdxml", "application/vnd.chemdraw+xml"},
{".css", "text/css"},
{".cdx", "chemical/x-cdx"},
{".cml", "chemical/x-cml"},
{".csml", "chemical/x-csml"},
{".cdbcmsg", "application/vnd.contact.cmsg"},
{".cla", "application/vnd.claymore"},
{".c4g", "application/vnd.clonk.c4group"},
{".sub", "image/vnd.dvb.subtitle"},
{".cdmia", "application/cdmi-capability"},
{".cdmic", "application/cdmi-container"},
{".cdmid", "application/cdmi-domain"},
{".cdmio", "application/cdmi-object"},
{".cdmiq", "application/cdmi-queue"},
{".c11amc", "application/vnd.cluetrust.cartomobile-config"},
{".c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"},
{".ras", "image/x-cmu-raster"},
{".dae", "model/vnd.collada+xml"},
{".csv", "text/csv"},
{".cpt", "application/mac-compactpro"},
{".wmlc", "application/vnd.wap.wmlc"},
{".cgm", "image/cgm"},
{".ice", "x-conference/x-cooltalk"},
{".cmx", "image/x-cmx"},
{".xar", "application/vnd.xara"},
{".cmc", "application/vnd.cosmocaller"},
{".cpio", "application/x-cpio"},
{".clkx", "application/vnd.crick.clicker"},
{".clkk", "application/vnd.crick.clicker.keyboard"},
{".clkp", "application/vnd.crick.clicker.palette"},
{".clkt", "application/vnd.crick.clicker.template"},
{".clkw", "application/vnd.crick.clicker.wordbank"},
{".wbs", "application/vnd.criticaltools.wbs+xml"},
{".cryptonote", "application/vnd.rig.cryptonote"},
{".cif", "chemical/x-cif"},
{".cmdf", "chemical/x-cmdf"},
{".cu", "application/cu-seeme"},
{".cww", "application/prs.cww"},
{".curl", "text/vnd.curl"},
{".dcurl", "text/vnd.curl.dcurl"},
{".mcurl", "text/vnd.curl.mcurl"},
{".scurl", "text/vnd.curl.scurl"},
{".car", "application/vnd.curl.car"},
{".pcurl", "application/vnd.curl.pcurl"},
{".cmp", "application/vnd.yellowriver-custom-menu"},
{".dssc", "application/dssc+der"},
{".xdssc", "application/dssc+xml"},
{".deb", "application/x-debian-package"},
{".uva", "audio/vnd.dece.audio"},
{".uvi", "image/vnd.dece.graphic"},
{".uvh", "video/vnd.dece.hd"},
{".uvm", "video/vnd.dece.mobile"},
{".uvu", "video/vnd.uvvu.mp4"},
{".uvp", "video/vnd.dece.pd"},
{".uvs", "video/vnd.dece.sd"},
{".uvv", "video/vnd.dece.video"},
{".dvi", "application/x-dvi"},
{".seed", "application/vnd.fdsn.seed"},
{".dtb", "application/x-dtbook+xml"},
{".res", "application/x-dtbresource+xml"},
{".ait", "application/vnd.dvb.ait"},
{".svc", "application/vnd.dvb.service"},
{".eol", "audio/vnd.digital-winds"},
{".djvu", "image/vnd.djvu"},
{".dtd", "application/xml-dtd"},
{".mlp", "application/vnd.dolby.mlp"},
{".wad", "application/x-doom"},
{".dpg", "application/vnd.dpgraph"},
{".dra", "audio/vnd.dra"},
{".dfac", "application/vnd.dreamfactory"},
{".dts", "audio/vnd.dts"},
{".dtshd", "audio/vnd.dts.hd"},
{".dwg", "image/vnd.dwg"},
{".geo", "application/vnd.dynageo"},
{".es", "application/ecmascript"},
{".mag", "application/vnd.ecowin.chart"},
{".mmr", "image/vnd.fujixerox.edmics-mmr"},
{".rlc", "image/vnd.fujixerox.edmics-rlc"},
{".exi", "application/exi"},
{".mgz", "application/vnd.proteus.magazine"},
{".epub", "application/epub+zip"},
{".eml", "message/rfc822"},
{".nml", "application/vnd.enliven"},
{".xpr", "application/vnd.is-xpr"},
{".xif", "image/vnd.xiff"},
{".xfdl", "application/vnd.xfdl"},
{".emma", "application/emma+xml"},
{".ez2", "application/vnd.ezpix-album"},
{".ez3", "application/vnd.ezpix-package"},
{".fst", "image/vnd.fst"},
{".fvt", "video/vnd.fvt"},
{".fbs", "image/vnd.fastbidsheet"},
{".fe_launch", "application/vnd.denovo.fcselayout-link"},
{".f4v", "video/x-f4v"},
{".flv", "video/x-flv"},
{".fpx", "image/vnd.fpx"},
{".npx", "image/vnd.net-fpx"},
{".flx", "text/vnd.fmi.flexstor"},
{".fli", "video/x-fli"},
{".ftc", "application/vnd.fluxtime.clip"},
{".fdf", "application/vnd.fdf"},
{".f", "text/x-fortran"},
{".mif", "application/vnd.mif"},
{".fm", "application/vnd.framemaker"},
{".fh", "image/x-freehand"},
{".fsc", "application/vnd.fsc.weblaunch"},
{".fnc", "application/vnd.frogans.fnc"},
{".ltf", "application/vnd.frogans.ltf"},
{".ddd", "application/vnd.fujixerox.ddd"},
{".xdw", "application/vnd.fujixerox.docuworks"},
{".xbd", "application/vnd.fujixerox.docuworks.binder"},
{".oas", "application/vnd.fujitsu.oasys"},
{".oa2", "application/vnd.fujitsu.oasys2"},
{".oa3", "application/vnd.fujitsu.oasys3"},
{".fg5", "application/vnd.fujitsu.oasysgp"},
{".bh2", "application/vnd.fujitsu.oasysprs"},
{".spl", "application/x-futuresplash"},
{".fzs", "application/vnd.fuzzysheet"},
{".g3", "image/g3fax"},
{".gmx", "application/vnd.gmx"},
{".gtw", "model/vnd.gtw"},
{".txd", "application/vnd.genomatix.tuxedo"},
{".ggb", "application/vnd.geogebra.file"},
{".ggt", "application/vnd.geogebra.tool"},
{".gdl", "model/vnd.gdl"},
{".gex", "application/vnd.geometry-explorer"},
{".gxt", "application/vnd.geonext"},
{".g2w", "application/vnd.geoplan"},
{".g3w", "application/vnd.geospace"},
{".gsf", "application/x-font-ghostscript"},
{".bdf", "application/x-font-bdf"},
{".gtar", "application/x-gtar"},
{".texinfo", "application/x-texinfo"},
{".gnumeric", "application/x-gnumeric"},
{".kml", "application/vnd.google-earth.kml+xml"},
{".kmz", "application/vnd.google-earth.kmz"},
{".gqf", "application/vnd.grafeq"},
{".gif", "image/gif"},
{".gv", "text/vnd.graphviz"},
{".gac", "application/vnd.groove-account"},
{".ghf", "application/vnd.groove-help"},
{".gim", "application/vnd.groove-identity-message"},
{".grv", "application/vnd.groove-injector"},
{".gtm", "application/vnd.groove-tool-message"},
{".tpl", "application/vnd.groove-tool-template"},
{".vcg", "application/vnd.groove-vcard"},
{".h261", "video/h261"},
{".h263", "video/h263"},
{".h264", "video/h264"},
{".hpid", "application/vnd.hp-hpid"},
{".hps", "application/vnd.hp-hps"},
{".hdf", "application/x-hdf"},
{".rip", "audio/vnd.rip"},
{".hbci", "application/vnd.hbci"},
{".jlt", "application/vnd.hp-jlyt"},
{".pcl", "application/vnd.hp-pcl"},
{".hpgl", "application/vnd.hp-hpgl"},
{".hvs", "application/vnd.yamaha.hv-script"},
{".hvd", "application/vnd.yamaha.hv-dic"},
{".hvp", "application/vnd.yamaha.hv-voice"},
{".sfd-hdstx", "application/vnd.hydrostatix.sof-data"},
{".stk", "application/hyperstudio"},
{".hal", "application/vnd.hal+xml"},
{".html", "text/html"},
{".irm", "application/vnd.ibm.rights-management"},
{".sc", "application/vnd.ibm.secure-container"},
{".ics", "text/calendar"},
{".icc", "application/vnd.iccprofile"},
{".ico", "image/x-icon"},
{".igl", "application/vnd.igloader"},
{".ief", "image/ief"},
{".ivp", "application/vnd.immervision-ivp"},
{".ivu", "application/vnd.immervision-ivu"},
{".rif", "application/reginfo+xml"},
{".3dml", "text/vnd.in3d.3dml"},
{".spot", "text/vnd.in3d.spot"},
{".igs", "model/iges"},
{".i2g", "application/vnd.intergeo"},
{".cdy", "application/vnd.cinderella"},
{".xpw", "application/vnd.intercon.formnet"},
{".fcs", "application/vnd.isac.fcs"},
{".ipfix", "application/ipfix"},
{".cer", "application/pkix-cert"},
{".pki", "application/pkixcmp"},
{".crl", "application/pkix-crl"},
{".pkipath", "application/pkix-pkipath"},
{".igm", "application/vnd.insors.igm"},
{".rcprofile", "application/vnd.ipunplugged.rcprofile"},
{".irp", "application/vnd.irepository.package+xml"},
{".jad", "text/vnd.sun.j2me.app-descriptor"},
{".jar", "application/java-archive"},
{".class", "application/java-vm"},
{".jnlp", "application/x-java-jnlp-file"},
{".ser", "application/java-serialized-object"},
{".java", "text/x-java-source,java"},
{".js", "application/javascript"},
{".json", "application/json"},
{".joda", "application/vnd.joost.joda-archive"},
{".jpm", "video/jpm"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg" },
{".jpgv", "video/jpeg"},
{".ktz", "application/vnd.kahootz"},
{".mmd", "application/vnd.chipnuts.karaoke-mmd"},
{".karbon", "application/vnd.kde.karbon"},
{".chrt", "application/vnd.kde.kchart"},
{".kfo", "application/vnd.kde.kformula"},
{".flw", "application/vnd.kde.kivio"},
{".kon", "application/vnd.kde.kontour"},
{".kpr", "application/vnd.kde.kpresenter"},
{".ksp", "application/vnd.kde.kspread"},
{".kwd", "application/vnd.kde.kword"},
{".htke", "application/vnd.kenameaapp"},
{".kia", "application/vnd.kidspiration"},
{".kne", "application/vnd.kinar"},
{".sse", "application/vnd.kodak-descriptor"},
{".lasxml", "application/vnd.las.las+xml"},
{".latex", "application/x-latex"},
{".lbd", "application/vnd.llamagraphics.life-balance.desktop"},
{".lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"},
{".jam", "application/vnd.jam"},
{".123", "application/vnd.lotus-1-2-3"},
{".apr", "application/vnd.lotus-approach"},
{".pre", "application/vnd.lotus-freelance"},
{".nsf", "application/vnd.lotus-notes"},
{".org", "application/vnd.lotus-organizer"},
{".scm", "application/vnd.lotus-screencam"},
{".lwp", "application/vnd.lotus-wordpro"},
{".lvp", "audio/vnd.lucent.voice"},
{".m3u", "audio/x-mpegurl"},
{".m4v", "video/x-m4v"},
{".hqx", "application/mac-binhex40"},
{".portpkg", "application/vnd.macports.portpkg"},
{".mgp", "application/vnd.osgeo.mapguide.package"},
{".mrc", "application/marc"},
{".mrcx", "application/marcxml+xml"},
{".mxf", "application/mxf"},
{".nbp", "application/vnd.wolfram.player"},
{".ma", "application/mathematica"},
{".mathml", "application/mathml+xml"},
{".mbox", "application/mbox"},
{".mc1", "application/vnd.medcalcdata"},
{".mscml", "application/mediaservercontrol+xml"},
{".cdkey", "application/vnd.mediastation.cdkey"},
{".mwf", "application/vnd.mfer"},
{".mfm", "application/vnd.mfmp"},
{".msh", "model/mesh"},
{".mads", "application/mads+xml"},
{".mets", "application/mets+xml"},
{".mods", "application/mods+xml"},
{".meta4", "application/metalink4+xml"},
{".potm", "application/vnd.ms-powerpoint.template.macroenabled.12"},
{".docm", "application/vnd.ms-word.document.macroenabled.12"},
{".dotm", "application/vnd.ms-word.template.macroenabled.12"},
{".mcd", "application/vnd.mcd"},
{".flo", "application/vnd.micrografx.flo"},
{".igx", "application/vnd.micrografx.igx"},
{".es3", "application/vnd.eszigno3+xml"},
{".mdb", "application/x-msaccess"},
{".asf", "video/x-ms-asf"},
{".exe", "application/x-msdownload"},
{".cil", "application/vnd.ms-artgalry"},
{".cab", "application/vnd.ms-cab-compressed"},
{".ims", "application/vnd.ms-ims"},
{".application", "application/x-ms-application"},
{".clp", "application/x-msclip"},
{".mdi", "image/vnd.ms-modi"},
{".eot", "application/vnd.ms-fontobject"},
{".xls", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroenabled.12"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"},
{".xltm", "application/vnd.ms-excel.template.macroenabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"},
{".chm", "application/vnd.ms-htmlhelp"},
{".crd", "application/x-mscardfile"},
{".lrm", "application/vnd.ms-lrm"},
{".mvb", "application/x-msmediaview"},
{".mny", "application/x-msmoney"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".obd", "application/x-msbinder"},
{".thmx", "application/vnd.ms-officetheme"},
{".onetoc", "application/onenote"},
{".pya", "audio/vnd.ms-playready.media.pya"},
{".pyv", "video/vnd.ms-playready.media.pyv"},
{".ppt", "application/vnd.ms-powerpoint"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"},
{".mpp", "application/vnd.ms-project"},
{".pub", "application/x-mspublisher"},
{".scd", "application/x-msschedule"},
{".xap", "application/x-silverlight-app"},
{".stl", "application/vnd.ms-pki.stl"},
{".cat", "application/vnd.ms-pki.seccat"},
{".vsd", "application/vnd.visio"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wax", "audio/x-ms-wax"},
{".wmx", "video/x-ms-wmx"},
{".wmd", "application/x-ms-wmd"},
{".wpl", "application/vnd.ms-wpl"},
{".wmz", "application/x-ms-wmz"},
{".wmv", "video/x-ms-wmv"},
{".wvx", "video/x-ms-wvx"},
{".wmf", "application/x-msmetafile"},
{".trm", "application/x-msterminal"},
{".doc", "application/msword"},
{".wri", "application/x-mswrite"},
{".wps", "application/vnd.ms-works"},
{".xbap", "application/x-ms-xbap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".mid", "audio/midi"},
{".mpy", "application/vnd.ibm.minipay"},
{".afp", "application/vnd.ibm.modcap"},
{".rms", "application/vnd.jcp.javame.midlet-rms"},
{".tmo", "application/vnd.tmobile-livetv"},
{".prc", "application/x-mobipocket-ebook"},
{".mbk", "application/vnd.mobius.mbk"},
{".dis", "application/vnd.mobius.dis"},
{".plc", "application/vnd.mobius.plc"},
{".mqy", "application/vnd.mobius.mqy"},
{".msl", "application/vnd.mobius.msl"},
{".txf", "application/vnd.mobius.txf"},
{".daf", "application/vnd.mobius.daf"},
{".fly", "text/vnd.fly"},
{".mpc", "application/vnd.mophun.certificate"},
{".mpn", "application/vnd.mophun.application"},
{".mj2", "video/mj2"},
{".mpga", "audio/mpeg"},
{".mxu", "video/vnd.mpegurl"},
{".mpeg", "video/mpeg"},
{".m21", "application/mp21"},
{".mp4a", "audio/mp4"},
{".mp4", "video/mp4"},
{".m3u8", "application/vnd.apple.mpegurl"},
{".mus", "application/vnd.musician"},
{".msty", "application/vnd.muvee.style"},
{".mxml", "application/xv+xml"},
{".ngdat", "application/vnd.nokia.n-gage.data"},
{".n-gage", "application/vnd.nokia.n-gage.symbian.install"},
{".ncx", "application/x-dtbncx+xml"},
{".nc", "application/x-netcdf"},
{".nlu", "application/vnd.neurolanguage.nlu"},
{".dna", "application/vnd.dna"},
{".nnd", "application/vnd.noblenet-directory"},
{".nns", "application/vnd.noblenet-sealer"},
{".nnw", "application/vnd.noblenet-web"},
{".rpst", "application/vnd.nokia.radio-preset"},
{".rpss", "application/vnd.nokia.radio-presets"},
{".n3", "text/n3"},
{".edm", "application/vnd.novadigm.edm"},
{".edx", "application/vnd.novadigm.edx"},
{".ext", "application/vnd.novadigm.ext"},
{".gph", "application/vnd.flographit"},
{".ecelp4800", "audio/vnd.nuera.ecelp4800"},
{".ecelp7470", "audio/vnd.nuera.ecelp7470"},
{".ecelp9600", "audio/vnd.nuera.ecelp9600"},
{".oda", "application/oda"},
{".ogx", "application/ogg"},
{".oga", "audio/ogg"},
{".ogv", "video/ogg"},
{".dd2", "application/vnd.oma.dd2+xml"},
{".oth", "application/vnd.oasis.opendocument.text-web"},
{".opf", "application/oebps-package+xml"},
{".qbo", "application/vnd.intu.qbo"},
{".oxt", "application/vnd.openofficeorg.extension"},
{".osf", "application/vnd.yamaha.openscoreformat"},
{".weba", "audio/webm"},
{".webm", "video/webm"},
{".odc", "application/vnd.oasis.opendocument.chart"},
{".otc", "application/vnd.oasis.opendocument.chart-template"},
{".odb", "application/vnd.oasis.opendocument.database"},
{".odf", "application/vnd.oasis.opendocument.formula"},
{".odft", "application/vnd.oasis.opendocument.formula-template"},
{".odg", "application/vnd.oasis.opendocument.graphics"},
{".otg", "application/vnd.oasis.opendocument.graphics-template"},
{".odi", "application/vnd.oasis.opendocument.image"},
{".oti", "application/vnd.oasis.opendocument.image-template"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".otp", "application/vnd.oasis.opendocument.presentation-template"},
{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
{".ots", "application/vnd.oasis.opendocument.spreadsheet-template"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".odm", "application/vnd.oasis.opendocument.text-master"},
{".ott", "application/vnd.oasis.opendocument.text-template"},
{".ktx", "image/ktx"},
{".sxc", "application/vnd.sun.xml.calc"},
{".stc", "application/vnd.sun.xml.calc.template"},
{".sxd", "application/vnd.sun.xml.draw"},
{".std", "application/vnd.sun.xml.draw.template"},
{".sxi", "application/vnd.sun.xml.impress"},
{".sti", "application/vnd.sun.xml.impress.template"},
{".sxm", "application/vnd.sun.xml.math"},
{".sxw", "application/vnd.sun.xml.writer"},
{".sxg", "application/vnd.sun.xml.writer.global"},
{".stw", "application/vnd.sun.xml.writer.template"},
{".otf", "application/x-font-otf"},
{".osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"},
{".dp", "application/vnd.osgi.dp"},
{".pdb", "application/vnd.palm"},
{".p", "text/x-pascal"},
{".paw", "application/vnd.pawaafile"},
{".pclxl", "application/vnd.hp-pclxl"},
{".efif", "application/vnd.picsel"},
{".pcx", "image/x-pcx"},
{".psd", "image/vnd.adobe.photoshop"},
{".prf", "application/pics-rules"},
{".pic", "image/x-pict"},
{".chat", "application/x-chat"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7m", "application/pkcs7-mime"},
{".p7s", "application/pkcs7-signature"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7b", "application/x-pkcs7-certificates"},
{".p8", "application/pkcs8"},
{".plf", "application/vnd.pocketlearn"},
{".pnm", "image/x-portable-anymap"},
{".pbm", "image/x-portable-bitmap"},
{".pcf", "application/x-font-pcf"},
{".pfr", "application/font-tdpfr"},
{".pgn", "application/x-chess-pgn"},
{".pgm", "image/x-portable-graymap"},
{".png", "image/png"},
{".ppm", "image/x-portable-pixmap"},
{".pskcxml", "application/pskc+xml"},
{".pml", "application/vnd.ctc-posml"},
{".ai", "application/postscript"},
{".pfa", "application/x-font-type1"},
{".pbd", "application/vnd.powerbuilder6"},
{".pgp", "application/pgp-signature"},
{".box", "application/vnd.previewsystems.box"},
{".ptid", "application/vnd.pvi.ptid1"},
{".pls", "application/pls+xml"},
{".str", "application/vnd.pg.format"},
{".ei6", "application/vnd.pg.osasli"},
{".dsc", "text/prs.lines.tag"},
{".psf", "application/x-font-linux-psf"},
{".qps", "application/vnd.publishare-delta-tree"},
{".wg", "application/vnd.pmi.widget"},
{".qxd", "application/vnd.quark.quarkxpress"},
{".esf", "application/vnd.epson.esf"},
{".msf", "application/vnd.epson.msf"},
{".ssf", "application/vnd.epson.ssf"},
{".qam", "application/vnd.epson.quickanime"},
{".qfx", "application/vnd.intu.qfx"},
{".qt", "video/quicktime"},
{".rar", "application/x-rar-compressed"},
{".ram", "audio/x-pn-realaudio"},
{".rmp", "audio/x-pn-realaudio-plugin"},
{".rsd", "application/rsd+xml"},
{".rm", "application/vnd.rn-realmedia"},
{".bed", "application/vnd.realvnc.bed"},
{".mxl", "application/vnd.recordare.musicxml"},
{".musicxml", "application/vnd.recordare.musicxml+xml"},
{".rnc", "application/relax-ng-compact-syntax"},
{".rdz", "application/vnd.data-vision.rdz"},
{".rdf", "application/rdf+xml"},
{".rp9", "application/vnd.cloanto.rp9"},
{".jisp", "application/vnd.jisp"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".link66", "application/vnd.route66.link66+xml"},
{".rss, .xml", "application/rss+xml"},
{".shf", "application/shf+xml"},
{".st", "application/vnd.sailingtracker.track"},
{".svg", "image/svg+xml"},
{".sus", "application/vnd.sus-calendar"},
{".sru", "application/sru+xml"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".sema", "application/vnd.sema"},
{".semd", "application/vnd.semd"},
{".semf", "application/vnd.semf"},
{".see", "application/vnd.seemail"},
{".snf", "application/x-font-snf"},
{".spq", "application/scvp-vp-request"},
{".spp", "application/scvp-vp-response"},
{".scq", "application/scvp-cv-request"},
{".scs", "application/scvp-cv-response"},
{".sdp", "application/sdp"},
{".etx", "text/x-setext"},
{".movie", "video/x-sgi-movie"},
{".ifm", "application/vnd.shana.informed.formdata"},
{".itp", "application/vnd.shana.informed.formtemplate"},
{".iif", "application/vnd.shana.informed.interchange"},
{".ipk", "application/vnd.shana.informed.package"},
{".tfi", "application/thraud+xml"},
{".shar", "application/x-shar"},
{".rgb", "image/x-rgb"},
{".slt", "application/vnd.epson.salt"},
{".aso", "application/vnd.accpac.simply.aso"},
{".imp", "application/vnd.accpac.simply.imp"},
{".twd", "application/vnd.simtech-mindmapper"},
{".csp", "application/vnd.commonspace"},
{".saf", "application/vnd.yamaha.smaf-audio"},
{".mmf", "application/vnd.smaf"},
{".spf", "application/vnd.yamaha.smaf-phrase"},
{".teacher", "application/vnd.smart.teacher"},
{".svd", "application/vnd.svd"},
{".rq", "application/sparql-query"},
{".srx", "application/sparql-results+xml"},
{".gram", "application/srgs"},
{".grxml", "application/srgs+xml"},
{".ssml", "application/ssml+xml"},
{".skp", "application/vnd.koan"},
{".sgml", "text/sgml"},
{".sdc", "application/vnd.stardivision.calc"},
{".sda", "application/vnd.stardivision.draw"},
{".sdd", "application/vnd.stardivision.impress"},
{".smf", "application/vnd.stardivision.math"},
{".sdw", "application/vnd.stardivision.writer"},
{".sgl", "application/vnd.stardivision.writer-global"},
{".sm", "application/vnd.stepmania.stepchart"},
{".sit", "application/x-stuffit"},
{".sitx", "application/x-stuffitx"},
{".sdkm", "application/vnd.solent.sdkm+xml"},
{".xo", "application/vnd.olpc-sugar"},
{".au", "audio/basic"},
{".wqd", "application/vnd.wqd"},
{".sis", "application/vnd.symbian.install"},
{".smi", "application/smil+xml"},
{".xsm", "application/vnd.syncml+xml"},
{".bdm", "application/vnd.syncml.dm+wbxml"},
{".xdm", "application/vnd.syncml.dm+xml"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".sbml", "application/sbml+xml"},
{".tsv", "text/tab-separated-values"},
{".tiff", "image/tiff"},
{".tao", "application/vnd.tao.intent-module-archive"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".tex", "application/x-tex"},
{".tfm", "application/x-tex-tfm"},
{".tei", "application/tei+xml"},
{".txt", "text/plain"},
{".dxp", "application/vnd.spotfire.dxp"},
{".sfs", "application/vnd.spotfire.sfs"},
{".tsd", "application/timestamped-data"},
{".tpt", "application/vnd.trid.tpt"},
{".mxs", "application/vnd.triscape.mxs"},
{".t", "text/troff"},
{".tra", "application/vnd.trueapp"},
{".ttf", "application/x-font-ttf"},
{".ttl", "text/turtle"},
{".umj", "application/vnd.umajin"},
{".uoml", "application/vnd.uoml+xml"},
{".unityweb", "application/vnd.unity"},
{".ufd", "application/vnd.ufdl"},
{".uri", "text/uri-list"},
{".utz", "application/vnd.uiq.theme"},
{".ustar", "application/x-ustar"},
{".uu", "text/x-uuencode"},
{".vcs", "text/x-vcalendar"},
{".vcf", "text/x-vcard"},
{".vcd", "application/x-cdlink"},
{".vsf", "application/vnd.vsf"},
{".wrl", "model/vrml"},
{".vcx", "application/vnd.vcx"},
{".mts", "model/vnd.mts"},
{".vtu", "model/vnd.vtu"},
{".vis", "application/vnd.visionary"},
{".viv", "video/vnd.vivo"},
{".ccxml", "application/ccxml+xml,"},
{".vxml", "application/voicexml+xml"},
{".src", "application/x-wais-source"},
{".wbxml", "application/vnd.wap.wbxml"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wav", "audio/x-wav"},
{".davmount", "application/davmount+xml"},
{".woff", "application/x-font-woff"},
{".woff2", "application/x-font-woff"},
{".wspolicy", "application/wspolicy+xml"},
{".webp", "image/webp"},
{".wtb", "application/vnd.webturbo"},
{".wgt", "application/widget"},
{".hlp", "application/winhlp"},
{".wml", "text/vnd.wap.wml"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wpd", "application/vnd.wordperfect"},
{".stf", "application/vnd.wt.stf"},
{".wsdl", "application/wsdl+xml"},
{".xbm", "image/x-xbitmap"},
{".xpm", "image/x-xpixmap"},
{".xwd", "image/x-xwindowdump"},
{".der", "application/x-x509-ca-cert"},
{".fig", "application/x-xfig"},
{".xhtml", "application/xhtml+xml"},
{".xml", "application/xml"},
{".xdf", "application/xcap-diff+xml"},
{".xenc", "application/xenc+xml"},
{".xer", "application/patch-ops-error+xml"},
{".rl", "application/resource-lists+xml"},
{".rs", "application/rls-services+xml"},
{".rld", "application/resource-lists-diff+xml"},
{".xslt", "application/xslt+xml"},
{".xop", "application/xop+xml"},
{".xpi", "application/x-xpinstall"},
{".xspf", "application/xspf+xml"},
{".xul", "application/vnd.mozilla.xul+xml"},
{".xyz", "chemical/x-xyz"},
{".yaml", "text/yaml"},
{".yang", "application/yang"},
{".yin", "application/yin+xml"},
{".zir", "application/vnd.zul"},
{".zip", "application/zip"},
{".zmm", "application/vnd.handheld-entertainment+xml"},
{".zaz", "application/vnd.zzazz.deck+xml"}
};
}
public static class BlobExtensions
{
public static bool ExistsBlob(this BlobContainerClient client, string blobName)
{
return client.GetBlobs(prefix: blobName.BeforeLast("/") ?? "").Any(b => b.Name == blobName);
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.ML.Bayesian.Training.Estimator;
using Encog.ML.Bayesian.Training.Search;
using Encog.ML.Bayesian.Training.Search.k2;
using Encog.ML.Data;
using Encog.ML.Train;
using Encog.Neural.Networks.Training.Propagation;
namespace Encog.ML.Bayesian.Training
{
/// <summary>
/// Train a Bayesian network.
/// </summary>
public sealed class TrainBayesian : BasicTraining
{
/// <summary>
/// The data used for training.
/// </summary>
private readonly IMLDataSet _data;
/// <summary>
/// The method used to estimate the probabilities.
/// </summary>
private readonly IBayesEstimator _estimator;
/// <summary>
/// The maximum parents a node should have.
/// </summary>
private readonly int _maximumParents;
/// <summary>
/// The network to train.
/// </summary>
private readonly BayesianNetwork _network;
/// <summary>
/// The method used to search for the best network structure.
/// </summary>
private readonly IBayesSearch _search;
/// <summary>
/// Used to hold the query.
/// </summary>
private String _holdQuery;
/// <summary>
/// The method used to setup the initial Bayesian network.
/// </summary>
private BayesianInit _initNetwork = BayesianInit.InitNaiveBayes;
/// <summary>
/// The phase that training is currently in.
/// </summary>
private Phase _p = Phase.Init;
/// <summary>
/// Construct a Bayesian trainer. Use K2 to search, and the SimpleEstimator
/// to estimate probability. Init as Naive Bayes
/// </summary>
/// <param name="theNetwork">The network to train.</param>
/// <param name="theData">The data to train.</param>
/// <param name="theMaximumParents">The max number of parents.</param>
public TrainBayesian(BayesianNetwork theNetwork, IMLDataSet theData,
int theMaximumParents)
: this(theNetwork, theData, theMaximumParents,
BayesianInit.InitNaiveBayes, new SearchK2(),
new SimpleEstimator())
{
}
/// <summary>
/// Construct a Bayesian trainer.
/// </summary>
/// <param name="theNetwork">The network to train.</param>
/// <param name="theData">The data to train with.</param>
/// <param name="theMaximumParents">The maximum number of parents.</param>
/// <param name="theInit">How to init the new Bayes network.</param>
/// <param name="theSearch">The search method.</param>
/// <param name="theEstimator">The estimation mehod.</param>
public TrainBayesian(BayesianNetwork theNetwork, IMLDataSet theData,
int theMaximumParents, BayesianInit theInit, IBayesSearch theSearch,
IBayesEstimator theEstimator)
: base(TrainingImplementationType.Iterative)
{
_network = theNetwork;
_data = theData;
_maximumParents = theMaximumParents;
_search = theSearch;
_search.Init(this, theNetwork, theData);
_estimator = theEstimator;
_estimator.Init(this, theNetwork, theData);
_initNetwork = theInit;
Error = 1.0;
}
/// <inheritdoc/>
public override bool TrainingDone
{
get { return base.TrainingDone || _p == Phase.Terminated; }
}
/// <inheritdoc/>
public override bool CanContinue
{
get { return false; }
}
/// <inheritdoc/>
public override IMLMethod Method
{
get { return _network; }
}
/// <summary>
/// Returns the network.
/// </summary>
public BayesianNetwork Network
{
get { return _network; }
}
/// <summary>
/// The maximum parents a node can have.
/// </summary>
public int MaximumParents
{
get { return _maximumParents; }
}
/// <summary>
/// The search method.
/// </summary>
public IBayesSearch Search
{
get { return _search; }
}
/// <summary>
/// The init method.
/// </summary>
public BayesianInit InitNetwork
{
get { return _initNetwork; }
set { _initNetwork = value; }
}
/// <summary>
/// Init to Naive Bayes.
/// </summary>
private void InitNaiveBayes()
{
// clear out anything from before
_network.RemoveAllRelations();
// locate the classification target event
BayesianEvent classificationTarget = _network
.ClassificationTargetEvent;
// now link everything to this event
foreach (BayesianEvent e in _network.Events)
{
if (e != classificationTarget)
{
_network.CreateDependency(classificationTarget, e);
}
}
_network.FinalizeStructure();
}
/// <summary>
/// Handle iterations for the Init phase.
/// </summary>
private void IterationInit()
{
_holdQuery = _network.ClassificationStructure;
switch (_initNetwork)
{
case BayesianInit.InitEmpty:
_network.RemoveAllRelations();
_network.FinalizeStructure();
break;
case BayesianInit.InitNoChange:
break;
case BayesianInit.InitNaiveBayes:
InitNaiveBayes();
break;
}
_p = Phase.Search;
}
/// <summary>
/// Handle iterations for the Search phase.
/// </summary>
private void IterationSearch()
{
if (!_search.Iteration())
{
_p = Phase.SearchDone;
}
}
/// <summary>
/// Handle iterations for the Search Done phase.
/// </summary>
private void IterationSearchDone()
{
_network.FinalizeStructure();
_network.Reset();
_p = Phase.Probability;
}
/// <summary>
/// Handle iterations for the Probability phase.
/// </summary>
private void IterationProbability()
{
if (!_estimator.Iteration())
{
_p = Phase.Finish;
}
}
/// <summary>
/// Handle iterations for the Finish phase.
/// </summary>
private void IterationFinish()
{
_network.DefineClassificationStructure(_holdQuery);
Error = _network.CalculateError(_data);
_p = Phase.Terminated;
}
/// <inheritdoc/>
public override void Iteration()
{
PreIteration();
switch (_p)
{
case Phase.Init:
IterationInit();
break;
case Phase.Search:
IterationSearch();
break;
case Phase.SearchDone:
IterationSearchDone();
break;
case Phase.Probability:
IterationProbability();
break;
case Phase.Finish:
IterationFinish();
break;
}
PostIteration();
}
/// <inheritdoc/>
public override TrainingContinuation Pause()
{
return null;
}
/// <inheritdoc/>
public override void Resume(TrainingContinuation state)
{
}
#region Nested type: Phase
/// <summary>
/// What phase of training are we in?
/// </summary>
private enum Phase
{
/// <summary>
/// Init phase.
/// </summary>
Init,
/// <summary>
/// Searching for a network structure.
/// </summary>
Search,
/// <summary>
/// Search complete.
/// </summary>
SearchDone,
/// <summary>
/// Finding probabilities.
/// </summary>
Probability,
/// <summary>
/// Finished training.
/// </summary>
Finish,
/// <summary>
/// Training terminated.
/// </summary>
Terminated
} ;
#endregion
}
}
| |
using NSubstitute;
using NuGet.Configuration;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using NuKeeper.Abstractions.CollaborationModels;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Git;
using NuKeeper.Abstractions.Logging;
using NuKeeper.Abstractions.NuGet;
using NuKeeper.Abstractions.NuGetApi;
using NuKeeper.Abstractions.RepositoryInspection;
using NuKeeper.Engine;
using NuKeeper.Engine.Packages;
using NuKeeper.Update;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NuKeeper.Tests.Engine.Packages
{
[TestFixture]
public class PackageUpdaterTests
{
private ICollaborationFactory _collaborationFactory;
private IExistingCommitFilter _existingCommitFilter;
private IUpdateRunner _updateRunner;
[SetUp]
public void Initialize()
{
_collaborationFactory = Substitute.For<ICollaborationFactory>();
_existingCommitFilter = Substitute.For<IExistingCommitFilter>();
_updateRunner = Substitute.For<IUpdateRunner>();
_existingCommitFilter
.Filter(
Arg.Any<IGitDriver>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<string>(),
Arg.Any<string>()
)
.Returns(ci => ((IReadOnlyCollection<PackageUpdateSet>)ci[1]));
}
[Test]
public async Task MakeUpdatePullRequests_TwoUpdatesOneExistingPrAndMaxOpenPrIsTwo_CreatesOnlyOnePr()
{
_collaborationFactory
.CollaborationPlatform
.GetNumberOfOpenPullRequests(Arg.Any<string>(), Arg.Any<string>())
.Returns(1);
var packages = new List<PackageUpdateSet>
{
MakePackageUpdateSet("foo.bar", "1.0.0"),
MakePackageUpdateSet("notfoo.bar", "2.0.0")
};
var repoData = MakeRepositoryData();
var settings = MakeSettings();
settings.UserSettings.MaxOpenPullRequests = 2;
var sut = MakePackageUpdater();
var (updatesDone, thresholdReached) = await sut.MakeUpdatePullRequests(
Substitute.For<IGitDriver>(),
repoData,
packages,
new NuGetSources(""),
settings
);
Assert.That(updatesDone, Is.EqualTo(1));
Assert.That(thresholdReached, Is.True);
}
[Test]
public async Task MakeUpdatePullRequest_OpenPrsEqualsMaxOpenPrs_DoesNotCreateNewPr()
{
_collaborationFactory
.CollaborationPlatform
.GetNumberOfOpenPullRequests(Arg.Any<string>(), Arg.Any<string>())
.Returns(2);
var packages = new List<PackageUpdateSet>
{
MakePackageUpdateSet("foo.bar", "1.0.0")
};
var repoData = MakeRepositoryData();
var settings = MakeSettings();
settings.UserSettings.MaxOpenPullRequests = 2;
var sut = MakePackageUpdater();
var (updatesDone, thresHoldReached) = await sut.MakeUpdatePullRequests(
Substitute.For<IGitDriver>(),
repoData,
packages,
new NuGetSources(""),
settings
);
Assert.That(updatesDone, Is.EqualTo(0));
Assert.That(thresHoldReached, Is.True);
}
[Test]
public async Task MakeUpdatePullRequest_UpdateDoesNotCreatePrDueToExistingCommits_DoesNotPreventNewUpdates()
{
var packageSetOne = MakePackageUpdateSet("foo.bar", "1.0.0");
var packageSetTwo = MakePackageUpdateSet("notfoo.bar", "2.0.0");
_collaborationFactory
.CollaborationPlatform
.GetNumberOfOpenPullRequests(Arg.Any<string>(), Arg.Any<string>())
.Returns(1);
_existingCommitFilter
.Filter(
Arg.Any<IGitDriver>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<string>(),
Arg.Any<string>()
)
.Returns(new List<PackageUpdateSet>(), new List<PackageUpdateSet> { packageSetTwo });
var packages = new List<PackageUpdateSet> { packageSetOne, packageSetTwo };
var repoData = MakeRepositoryData();
var settings = MakeSettings();
settings.UserSettings.MaxOpenPullRequests = 2;
var sut = MakePackageUpdater();
var (updatesDone, _) = await sut.MakeUpdatePullRequests(
Substitute.For<IGitDriver>(),
repoData,
packages,
new NuGetSources(""),
settings
);
Assert.That(updatesDone, Is.EqualTo(1));
}
[Test]
public async Task MakeUpdatePullRequest_UpdateDoesNotCreatePrDueToExistingPr_DoesNotPreventNewUpdates()
{
var packageSetOne = MakePackageUpdateSet("foo.bar", "1.0.0");
var packageSetTwo = MakePackageUpdateSet("notfoo.bar", "2.0.0");
_collaborationFactory
.CollaborationPlatform
.GetNumberOfOpenPullRequests(Arg.Any<string>(), Arg.Any<string>())
.Returns(1);
_collaborationFactory
.CollaborationPlatform
.PullRequestExists(Arg.Any<ForkData>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(true, false);
var packages = new List<PackageUpdateSet> { packageSetOne, packageSetTwo };
var repoData = MakeRepositoryData();
var settings = MakeSettings();
settings.UserSettings.MaxOpenPullRequests = 2;
var sut = MakePackageUpdater();
var (updatesDone, _) = await sut.MakeUpdatePullRequests(
Substitute.For<IGitDriver>(),
repoData,
packages,
new NuGetSources(""),
settings
);
Assert.That(updatesDone, Is.EqualTo(2));
}
[Test]
public async Task MakeUpdatePullRequests_LessPrsThanMaxOpenPrs_ReturnsNotThresholdReached()
{
_collaborationFactory
.CollaborationPlatform
.GetNumberOfOpenPullRequests(Arg.Any<string>(), Arg.Any<string>())
.Returns(1);
var packages = new List<PackageUpdateSet>
{
MakePackageUpdateSet("foo.bar", "1.0.0"),
MakePackageUpdateSet("notfoo.bar", "2.0.0")
};
var repoData = MakeRepositoryData();
var settings = MakeSettings();
settings.UserSettings.MaxOpenPullRequests = 10;
var sut = MakePackageUpdater();
var (updatesDone, thresholdReached) = await sut.MakeUpdatePullRequests(
Substitute.For<IGitDriver>(),
repoData,
packages,
new NuGetSources(""),
settings
);
Assert.That(thresholdReached, Is.False);
}
private PackageUpdater MakePackageUpdater()
{
return new PackageUpdater(
_collaborationFactory,
_existingCommitFilter,
_updateRunner,
Substitute.For<INuKeeperLogger>()
);
}
private static RepositoryData MakeRepositoryData()
{
return new RepositoryData(
new ForkData(new Uri("http://foo.com"), "me", "test"),
new ForkData(new Uri("http://foo.com"), "me", "test"));
}
private static PackageUpdateSet MakePackageUpdateSet(string packageName, string version)
{
return new PackageUpdateSet(
new PackageLookupResult(
VersionChange.Major,
MakePackageSearchMetadata(packageName, version),
null,
null
),
new List<PackageInProject>
{
MakePackageInProject(packageName, version)
}
);
}
private static SettingsContainer MakeSettings(
bool consolidateUpdates = false
)
{
return new SettingsContainer
{
SourceControlServerSettings = new SourceControlServerSettings
{
Repository = new RepositorySettings()
},
UserSettings = new UserSettings
{
ConsolidateUpdatesInSinglePullRequest = consolidateUpdates
},
BranchSettings = new BranchSettings(),
PackageFilters = new FilterSettings
{
MaxPackageUpdates = 3,
MinimumAge = new TimeSpan(7, 0, 0, 0),
}
};
}
private static PackageInProject MakePackageInProject(string packageName, string version)
{
return new PackageInProject(
new PackageVersionRange(
packageName,
VersionRange.Parse(version)
),
new PackagePath(
"projectA",
"MyFolder",
PackageReferenceType.PackagesConfig
)
);
}
private static PackageSearchMetadata MakePackageSearchMetadata(string packageName, string version)
{
return new PackageSearchMetadata(
new PackageIdentity(
packageName,
NuGetVersion.Parse(version)
),
new PackageSource("https://api.nuget.com/v3/"),
new DateTimeOffset(2019, 1, 12, 0, 0, 0, TimeSpan.Zero),
null
);
}
}
}
| |
using System;
using Xunit;
using com.tms.datastruct;
using com.tms.turing;
namespace com.tms.test
{
public class TestLoadXML
{
private const string ADD_ONE_TM = @"<?xml version='1.0'?>
<turing-machine version='0.1'>
<!-- This Turing machine (TM) adds one to a whole number.
For example, if the initial tape is '199', then
the final tape will be '200'.
The Turing machine assumes that the first (i.e.,
leftmost) symbol on the tape is the leftmost digit
in the number.
If the input tape is completely blank, then the final
tape will be '1'. So, if the input tape is ' 43',
then the Turing machine will assume that tape does not
contain a number.
This Turing Machine Markup Language (TMML) document complies
with the DTD for TMML, which is available at
http://www.unidex.com/turing/tmml.dtd.
This Turing machine can be executed by an XSLT stylesheet that is
available at http://www.unidex.com/turing/utm.xsl. This stylesheet
is a Universal Turing Machine.
The following Instant Saxon command will execute the Turing machine
described by this TMML document using the utm.xsl stylesheet:
saxon add_one_tm.xml utm.xsl tape=199
This TMML document is available at
http://www.unidex.com/turing/add_one_tm.xml.
Developed by Bob Lyons of Unidex, Inc.
Please email any comments about this TMML document to
[email protected].
-->
<!-- COPYRIGHT NOTICE and LICENSE.
Copyright (c) 2001 Unidex, Inc. All rights reserved.
Unidex, Inc. grants you permission to copy, modify, distribute,
and/or use the TMML document provided that you agree to the
following conditions:
1. You must include this COPYRIGHT NOTICE and LICENSE
in all copies or substantial portions of the TMML document.
2. The TMML document is licensed to the user on an 'AS IS' basis.
Unidex Inc. makes no warranties, either express or implied,
with respect to the TMML document including but not limited to any
warranty of merchantability or fitness for any particular
purpose. Unidex Inc. does not warrant that the operation
of the TMML document will be uninterrupted or error-free,
or that defects in the TMML document will be corrected.
You the user are solely responsible for determining the
appropriateness of the TMML document for your use and accept
full responsibility for all risks associated with its use.
Unidex Inc. is not and will not be liable for any
direct, indirect, special, incidental or other damages
of any kind (including loss of profits or interruption of business)
however caused even if Unidex Inc. has been advised of the
possibility of such damages.
-->
<!-- The symbols are '0' through '9'.
-->
<symbols>0123456789</symbols>
<states>
<!-- In the go_right state, the Turing machine moves the
tape head to the blank symbol to the right of the
number.
-->
<state start='yes'>go_right</state>
<!-- In the increment state, the Turing machine keeps moving
left and changing 9's to 0's until it finds a digit
other than '9' or a blank symbol. When it finds a digit
other than '9' (or a blank symbol, which it treats as
the digit '0'), it increments the digit (e.g., replaces
'3' with '4').
-->
<state>increment</state>
<state halt='yes'>stop</state>
</states>
<!-- The transition function for the TM.
-->
<transition-function>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='0'/>
<to next-state='go_right' next-symbol='0' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='1'/>
<to next-state='go_right' next-symbol='1' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='2'/>
<to next-state='go_right' next-symbol='2' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='3'/>
<to next-state='go_right' next-symbol='3' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='4'/>
<to next-state='go_right' next-symbol='4' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='5'/>
<to next-state='go_right' next-symbol='5' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='6'/>
<to next-state='go_right' next-symbol='6' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='7'/>
<to next-state='go_right' next-symbol='7' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='8'/>
<to next-state='go_right' next-symbol='8' movement='right'/>
</mapping>
<mapping>
<!-- Move to the right of the number. -->
<from current-state='go_right' current-symbol='9'/>
<to next-state='go_right' next-symbol='9' movement='right'/>
</mapping>
<mapping>
<!-- Found the blank that follows the number.
Change to the increment state and start moving left. -->
<from current-state='go_right' current-symbol=' '/>
<to next-state='increment' next-symbol=' ' movement='left'/>
</mapping>
<mapping>
<!-- Change the 9 to a 0 and move left. -->
<from current-state='increment' current-symbol='9'/>
<to next-state='increment' next-symbol='0' movement='left'/>
</mapping>
<mapping>
<!-- Change the 0 to a 1. We're done. -->
<from current-state='increment' current-symbol='0'/>
<to next-state='stop' next-symbol='1' movement='left'/>
</mapping>
<mapping>
<!-- Change the blank to a 1. We're done. -->
<from current-state='increment' current-symbol=' '/>
<to next-state='stop' next-symbol='1' movement='none'/>
</mapping>
<mapping>
<!-- Change the 1 to a 2. We're done. -->
<from current-state='increment' current-symbol='1'/>
<to next-state='stop' next-symbol='2' movement='left'/>
</mapping>
<mapping>
<!-- Change the 2 to a 3. We're done. -->
<from current-state='increment' current-symbol='2'/>
<to next-state='stop' next-symbol='3' movement='left'/>
</mapping>
<mapping>
<!-- Change the 3 to a 4. We're done. -->
<from current-state='increment' current-symbol='3'/>
<to next-state='stop' next-symbol='4' movement='left'/>
</mapping>
<mapping>
<!-- Change the 4 to a 5. We're done. -->
<from current-state='increment' current-symbol='4'/>
<to next-state='stop' next-symbol='5' movement='left'/>
</mapping>
<mapping>
<!-- Change the 5 to a 6. We're done. -->
<from current-state='increment' current-symbol='5'/>
<to next-state='stop' next-symbol='6' movement='left'/>
</mapping>
<mapping>
<!-- Change the 6 to a 7. We're done. -->
<from current-state='increment' current-symbol='6'/>
<to next-state='stop' next-symbol='7' movement='left'/>
</mapping>
<mapping>
<!-- Change the 7 to a 8. We're done. -->
<from current-state='increment' current-symbol='7'/>
<to next-state='stop' next-symbol='8' movement='left'/>
</mapping>
<mapping>
<!-- Change the 8 to a 9. We're done. -->
<from current-state='increment' current-symbol='8'/>
<to next-state='stop' next-symbol='9' movement='left'/>
</mapping>
</transition-function>
</turing-machine>";
[Fact]
public void test_add_one_from_string()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromString<string, char>(ADD_ONE_TM, nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|4|5|9|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("|4|6|0| |", machine.Tape.ToString());
}
[Fact]
public void test_add_one_from_string_2()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromString<string, char>(ADD_ONE_TM, nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|4|5|9|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("460", machine.Tape.ToPlainString().Trim());
}
[Fact]
public void test_add_one_from_file()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromFile<string, char>("../../../../../test/xml/add_one_tm.xml", nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|4|5|9|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("460", machine.Tape.ToPlainString().Trim());
}
[Fact]
public void test_palindrome()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromFile<string, char>("../../../../../test/xml/palindrome_tm.xml", nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|0|1|2|1|0|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal(string.Empty, machine.Tape.ToPlainString().Trim());
}
[Fact]
public void test_palindrome_2()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromFile<string, char>("../../../../../test/xml/palindrome_tm.xml", nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|0|1|2|2|0|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("22", machine.Tape.ToPlainString().Trim());
}
[Fact]
public void test_rot13()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromFile<string, char>("../../../../../test/xml/rot13_tm.xml", nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|a|b|c|d|e|f|g|h|$|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("nopqrstu$", machine.Tape.ToPlainString().Trim());
}
[Fact]
public void test_string_length()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromFile<string, char>("../../../../../test/xml/string_length_tm.xml", nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|a|b|a|a|b|b|a|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("7", machine.Tape.ToPlainString().Trim());
}
[Fact]
public void test_string_length_2()
{
const char nullValue = ' ';
var table = StatefulTableXMLParser.LoadFromFile<string, char>("../../../../../test/xml/string_length_tm.xml", nullValue,
new StringStateSerializer(), new CharSymbolSerializer());
var tape = new Tape<char>(new CharSymbolSerializer(), nullValue);
tape.FillFromString("|a|b|a|a|b|b|a|b|a|b|b|");
var machine = new TuringMachine<string,char>(table, tape);
machine.Run();
Assert.Equal("11", machine.Tape.ToPlainString().Trim());
}
}
}
| |
//
// ClientSessionCache.cs: Client-side cache for re-using sessions
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2006 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
namespace Mono.Security.Protocol.Tls {
internal class ClientSessionInfo : IDisposable {
// (by default) we keep this item valid for 3 minutes (if unused)
private const int DefaultValidityInterval = 3 * 60;
private static readonly int ValidityInterval;
private bool disposed;
private DateTime validuntil;
private string host;
// see RFC2246 - Section 7
private byte[] sid;
private byte[] masterSecret;
static ClientSessionInfo ()
{
string user_cache_timeout = Environment.GetEnvironmentVariable ("MONO_TLS_SESSION_CACHE_TIMEOUT");
if (user_cache_timeout == null) {
ValidityInterval = DefaultValidityInterval;
} else {
try {
ValidityInterval = Int32.Parse (user_cache_timeout);
}
catch {
ValidityInterval = DefaultValidityInterval;
}
}
}
public ClientSessionInfo (string hostname, byte[] id)
{
host = hostname;
sid = id;
KeepAlive ();
}
~ClientSessionInfo ()
{
Dispose (false);
}
public string HostName {
get { return host; }
}
public byte[] Id {
get { return sid; }
}
public bool Valid {
get { return ((masterSecret != null) && (validuntil > DateTime.UtcNow)); }
}
public void GetContext (Context context)
{
CheckDisposed ();
if (context.MasterSecret != null)
masterSecret = (byte[]) context.MasterSecret.Clone ();
}
public void SetContext (Context context)
{
CheckDisposed ();
if (masterSecret != null)
context.MasterSecret = (byte[]) masterSecret.Clone ();
}
public void KeepAlive ()
{
CheckDisposed ();
validuntil = DateTime.UtcNow.AddSeconds (ValidityInterval);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
private void Dispose (bool disposing)
{
if (!disposed) {
validuntil = DateTime.MinValue;
host = null;
sid = null;
if (masterSecret != null) {
Array.Clear (masterSecret, 0, masterSecret.Length);
masterSecret = null;
}
}
disposed = true;
}
private void CheckDisposed ()
{
if (disposed) {
string msg = ("Cache session information were disposed.");
throw new ObjectDisposedException (msg);
}
}
}
// note: locking is aggressive but isn't used often (and we gain much more :)
internal class ClientSessionCache {
static Hashtable cache;
static object locker;
static ClientSessionCache ()
{
cache = new Hashtable ();
locker = new object ();
}
// note: we may have multiple connections with a host, so
// possibly multiple entries per host (each with a different
// id), so we do not use the host as the hashtable key
static public void Add (string host, byte[] id)
{
lock (locker) {
string uid = BitConverter.ToString (id);
ClientSessionInfo si = (ClientSessionInfo) cache[uid];
if (si == null) {
cache.Add (uid, new ClientSessionInfo (host, id));
} else if (si.HostName == host) {
// we already have this and it's still valid
// on the server, so we'll keep it a little longer
si.KeepAlive ();
} else {
// it's very unlikely but the same session id
// could be used by more than one host. In this
// case we replace the older one with the new one
si.Dispose ();
cache.Remove (uid);
cache.Add (uid, new ClientSessionInfo (host, id));
}
}
}
// return the first session us
static public byte[] FromHost (string host)
{
lock (locker) {
foreach (ClientSessionInfo si in cache.Values) {
if (si.HostName == host) {
if (si.Valid) {
// ensure it's still valid when we really need it
si.KeepAlive ();
return si.Id;
}
}
}
return null;
}
}
// only called inside the lock
static private ClientSessionInfo FromContext (Context context, bool checkValidity)
{
if (context == null)
return null;
byte[] id = context.SessionId;
if ((id == null) || (id.Length == 0))
return null;
// do we have a session cached for this host ?
string uid = BitConverter.ToString (id);
ClientSessionInfo si = (ClientSessionInfo) cache[uid];
if (si == null)
return null;
// In the unlikely case of multiple hosts using the same
// session id, we just act like we do not know about it
if (context.ClientSettings.TargetHost != si.HostName)
return null;
// yes, so what's its status ?
if (checkValidity && !si.Valid) {
si.Dispose ();
cache.Remove (uid);
return null;
}
// ok, it make sense
return si;
}
static public bool SetContextInCache (Context context)
{
lock (locker) {
// Don't check the validity because the masterKey of the ClientSessionInfo
// can still be null when this is called the first time
ClientSessionInfo csi = FromContext (context, false);
if (csi == null)
return false;
csi.GetContext (context);
csi.KeepAlive ();
return true;
}
}
static public bool SetContextFromCache (Context context)
{
lock (locker) {
ClientSessionInfo csi = FromContext (context, true);
if (csi == null)
return false;
csi.SetContext (context);
csi.KeepAlive ();
return true;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended.TextureAtlases
{
/// <summary>
/// Defines a texture atlas which stores a source image and contains regions specifying its sub-images.
/// </summary>
/// <remarks>
/// <para>
/// Texture atlas (also called a tile map, tile engine, or sprite sheet) is a large image containing a collection,
/// or "atlas", of sub-images, each of which is a texture map for some part of a 2D or 3D model.
/// The sub-textures can be rendered by modifying the texture coordinates of the object's uvmap on the atlas,
/// essentially telling it which part of the image its texture is in.
/// In an application where many small textures are used frequently, it is often more efficient to store the
/// textures in a texture atlas which is treated as a single unit by the graphics hardware.
/// This saves memory and because there are less rendering state changes by binding once, it can be faster to bind
/// one large texture once than to bind many smaller textures as they are drawn.
/// Careful alignment may be needed to avoid bleeding between sub textures when used with mipmapping, and artefacts
/// between tiles for texture compression.
/// </para>
/// </remarks>
public class TextureAtlas : IEnumerable<TextureRegion2D>
{
/// <summary>
/// Initializes a new texture atlas with an empty list of regions.
/// </summary>
/// <param name="name">The asset name of this texture atlas</param>
/// <param name="texture">Source <see cref="Texture2D " /> image used to draw on screen.</param>
public TextureAtlas(string name, Texture2D texture)
{
Name = name;
Texture = texture;
_regions = new List<TextureRegion2D>();
_regionMap = new Dictionary<string, int>();
}
/// <summary>
/// Initializes a new texture atlas and populates it with regions.
/// </summary>
/// <param name="name">The asset name of this texture atlas</param>
/// <param name="texture">Source <see cref="Texture2D " /> image used to draw on screen.</param>
/// <param name="regions">A collection of regions to populate the atlas with.</param>
public TextureAtlas(string name, Texture2D texture, Dictionary<string, Rectangle> regions)
: this(name, texture)
{
foreach (var region in regions)
CreateRegion(region.Key, region.Value.X, region.Value.Y, region.Value.Width, region.Value.Height);
}
private readonly Dictionary<string, int> _regionMap;
private readonly List<TextureRegion2D> _regions;
public string Name { get; }
/// <summary>
/// Gets a source <see cref="Texture2D" /> image.
/// </summary>
public Texture2D Texture { get; }
/// <summary>
/// Gets a list of regions in the <see cref="TextureAtlas" />.
/// </summary>
public IEnumerable<TextureRegion2D> Regions => _regions;
/// <summary>
/// Gets the number of regions in the <see cref="TextureAtlas" />.
/// </summary>
public int RegionCount => _regions.Count;
public TextureRegion2D this[string name] => GetRegion(name);
public TextureRegion2D this[int index] => GetRegion(index);
/// <summary>
/// Gets the enumerator of the <see cref="TextureAtlas" />' list of regions.
/// </summary>
/// <returns>The <see cref="IEnumerator" /> of regions.</returns>
public IEnumerator<TextureRegion2D> GetEnumerator()
{
return _regions.GetEnumerator();
}
/// <summary>
/// Gets the enumerator of the <see cref="TextureAtlas" />' list of regions.
/// </summary>
/// <returns>The <see cref="IEnumerator" /> of regions</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Determines whether the texture atlas contains a region
/// </summary>
/// <param name="name">Name of the texture region.</param>
/// <returns></returns>
public bool ContainsRegion(string name)
{
return _regionMap.ContainsKey(name);
}
/// <summary>
/// Internal method for adding region
/// </summary>
/// <param name="region">Texture region.</param>
private void AddRegion(TextureRegion2D region)
{
var index = _regions.Count;
_regions.Add(region);
_regionMap.Add(region.Name, index);
}
/// <summary>
/// Creates a new texture region and adds it to the list of the <see cref="TextureAtlas" />' regions.
/// </summary>
/// <param name="name">Name of the texture region.</param>
/// <param name="x">X coordinate of the region's top left corner.</param>
/// <param name="y">Y coordinate of the region's top left corner.</param>
/// <param name="width">Width of the texture region.</param>
/// <param name="height">Height of the texture region.</param>
/// <returns>Created texture region.</returns>
public TextureRegion2D CreateRegion(string name, int x, int y, int width, int height)
{
if (_regionMap.ContainsKey(name))
throw new InvalidOperationException($"Region {name} already exists in the texture atlas");
var region = new TextureRegion2D(name, Texture, x, y, width, height);
AddRegion(region);
return region;
}
/// <summary>
/// Creates a new nine patch texture region and adds it to the list of the <see cref="TextureAtlas" />' regions.
/// </summary>
/// <param name="name">Name of the texture region.</param>
/// <param name="x">X coordinate of the region's top left corner.</param>
/// <param name="y">Y coordinate of the region's top left corner.</param>
/// <param name="width">Width of the texture region.</param>
/// <param name="height">Height of the texture region.</param>
/// <param name="thickness">Thickness of the nine patch region.</param>
/// <returns>Created texture region.</returns>
public NinePatchRegion2D CreateNinePatchRegion(string name, int x, int y, int width, int height, Thickness thickness)
{
if (_regionMap.ContainsKey(name))
throw new InvalidOperationException($"Region {name} already exists in the texture atlas");
var textureRegion = new TextureRegion2D(name, Texture, x, y, width, height);
var ninePatchRegion = new NinePatchRegion2D(textureRegion, thickness);
AddRegion(ninePatchRegion);
return ninePatchRegion;
}
/// <summary>
/// Removes a texture region from the <see cref="TextureAtlas" />
/// </summary>
/// <param name="index">An index of the <see cref="TextureRegion2D" /> in <see cref="Region" /> to remove</param>
public void RemoveRegion(int index)
{
_regions.RemoveAt(index);
}
/// <summary>
/// Removes a texture region from the <see cref="TextureAtlas" />
/// </summary>
/// <param name="name">Name of the <see cref="TextureRegion2D" /> to remove</param>
public void RemoveRegion(string name)
{
int index;
if (_regionMap.TryGetValue(name, out index))
{
RemoveRegion(index);
_regionMap.Remove(name);
}
}
/// <summary>
/// Gets a <see cref="TextureRegion2D" /> from the <see cref="TextureAtlas" />' list.
/// </summary>
/// <param name="index">An index of the <see cref="TextureRegion2D" /> in <see cref="Region" /> to get.</param>
/// <returns>The <see cref="TextureRegion2D" />.</returns>
public TextureRegion2D GetRegion(int index)
{
if ((index < 0) || (index >= _regions.Count))
throw new IndexOutOfRangeException();
return _regions[index];
}
/// <summary>
/// Gets a <see cref="TextureRegion2D" /> from the <see cref="TextureAtlas" />' list.
/// </summary>
/// <param name="name">Name of the <see cref="TextureRegion2D" /> to get.</param>
/// <returns>The <see cref="TextureRegion2D" />.</returns>
public TextureRegion2D GetRegion(string name)
{
return GetRegion<TextureRegion2D>(name);
}
/// <summary>
/// Gets a texture region from the <see cref="TextureAtlas" /> of a specified type.
/// This is can be useful if the atlas contains <see cref="NinePatchRegion2D"/>'s.
/// </summary>
/// <typeparam name="T">Type of the region to get</typeparam>
/// <param name="name">Name of the region to get</param>
/// <returns>The texture region</returns>
public T GetRegion<T>(string name) where T : TextureRegion2D
{
int index;
if (_regionMap.TryGetValue(name, out index))
return (T) GetRegion(index);
throw new KeyNotFoundException(name);
}
/// <summary>
/// Creates a new <see cref="TextureAtlas" /> and populates it with a grid of <see cref="TextureRegion2D" />.
/// </summary>
/// <param name="name">The name of this texture atlas</param>
/// <param name="texture">Source <see cref="Texture2D" /> image used to draw on screen</param>
/// <param name="regionWidth">Width of the <see cref="TextureRegion2D" />.</param>
/// <param name="regionHeight">Height of the <see cref="TextureRegion2D" />.</param>
/// <param name="maxRegionCount">The number of <see cref="TextureRegion2D" /> to create.</param>
/// <param name="margin">Minimum distance of the regions from the border of the source <see cref="Texture2D" /> image.</param>
/// <param name="spacing">Horizontal and vertical space between regions.</param>
/// <returns>A created and populated <see cref="TextureAtlas" />.</returns>
public static TextureAtlas Create(string name, Texture2D texture, int regionWidth, int regionHeight,
int maxRegionCount = int.MaxValue, int margin = 0, int spacing = 0)
{
var textureAtlas = new TextureAtlas(name, texture);
var count = 0;
var width = texture.Width - margin;
var height = texture.Height - margin;
var xIncrement = regionWidth + spacing;
var yIncrement = regionHeight + spacing;
for (var y = margin; y < height; y += yIncrement)
{
for (var x = margin; x < width; x += xIncrement)
{
var regionName = $"{texture.Name ?? "region"}{count}";
textureAtlas.CreateRegion(regionName, x, y, regionWidth, regionHeight);
count++;
if (count >= maxRegionCount)
return textureAtlas;
}
}
return textureAtlas;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: ArrayList.cs
//
// 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 Dot42;
using Dot42.Collections;
using Dot42.Internal;
using Java.Lang;
using Java.Util;
namespace System.Collections
{
public class ArrayList : IList
{
private readonly Java.Util.IList<object> list;
private readonly bool isFixedSize;
private readonly bool isReadOnly;
private readonly bool isSynchronized;
/// <summary>
/// Default ctor
/// </summary>
public ArrayList() :
this(new Java.Util.ArrayList<object>(), false, false, false)
{
}
/// <summary>
/// Clone ctor
/// </summary>
public ArrayList(ICollection source)
: this(new Java.Util.ArrayList<object>((source != null) ? source.Count : 0), false, false, false)
{
if (source == null)
throw new ArgumentNullException();
foreach (var item in source)
{
list.Add(item);
}
}
/// <summary>
/// Default ctor with specified initial capacity.
/// </summary>
public ArrayList(int capacity) :
this(new Java.Util.ArrayList<object>(capacity), false, false, false)
{
}
/// <summary>
/// Private ctor
/// </summary>
private ArrayList(Java.Util.IList<object> list, bool isFixedSize, bool isReadOnly, bool isSynchronized)
{
this.list = list;
this.isFixedSize = isFixedSize;
this.isReadOnly = isReadOnly;
this.isSynchronized = isSynchronized;
}
/// <summary>
/// Gets/sets the capacity of this list.
/// </summary>
public virtual int Capacity
{
get { return list.Size(); }
set
{
/* ignore */
}
}
/// <summary>
/// Gets the number of items in this list.
/// </summary>
public int Count
{
get { return list.Size(); }
}
/// <summary>
/// Does this list have a fixed size?
/// </summary>
public virtual bool IsFixedSize
{
get { return isFixedSize; }
}
/// <summary>
/// Is this list readonly?
/// </summary>
public virtual bool IsReadOnly
{
get { return isReadOnly; }
}
/// <summary>
/// Is this list synchronized?
/// </summary>
public virtual bool IsSynchronized
{
get { return isSynchronized; }
}
/// <summary>
/// Is this list readonly?
/// </summary>
public virtual object this[int index]
{
get
{
if ((index < 0) || (index >= list.Size()))
throw new ArgumentOutOfRangeException();
return list[index];
}
set
{
if (isReadOnly)
throw new NotSupportedException();
if ((index < 0) || (index >= list.Size()))
throw new ArgumentOutOfRangeException();
list[index] = value;
}
}
/// <summary>
/// Gets an object that can be used to synchronized access to this list.
/// </summary>
public virtual object SyncRoot
{
get { return this; }
}
/// <summary>
/// Copy all elements into the given array starting at the given index (into the array).
/// </summary>
public virtual void CopyTo(Array array)
{
CopyTo(0, array, 0, list.Size());
}
/// <summary>
/// Copy all elements into the given array starting at the given index (into the array).
/// </summary>
public virtual void CopyTo(Array array, int index)
{
CopyTo(0, array, index, list.Size());
}
/// <summary>
/// Copy all elements into the given array starting at the given index (into the array).
/// </summary>
public virtual void CopyTo(int index, Array array, int arrayIndex, int count)
{
if (array == null)
throw new ArgumentNullException();
if ((index < 0) || (arrayIndex < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
var size = list.Size();
var available = array.Length- arrayIndex;
if ((index > size) || (count > size) || (index + count > size) || (count > available))
throw new ArgumentException();
while (count > 0)
{
array.SetValue(list[index++], arrayIndex++);
count--;
}
}
/// <summary>
/// Add an object to the end of this list
/// </summary>
/// <param name="value"></param>
public virtual int Add(object value)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
list.Add(value);
return list.Size() - 1;
}
/// <summary>
/// Add all elements in the given collection to the end of this list
/// </summary>
/// <param name="value"></param>
public virtual void AddRange(ICollection c)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
if (c == null)
throw new ArgumentNullException();
foreach (var i in c)
{
list.Add(i);
}
}
[NotImplemented]
public virtual int BinarySearch(object element)
{
return Java.Util.Collections.BinarySearch(list, element, Comparer.Default);
}
[NotImplemented]
public virtual int BinarySearch(object element, IComparer comparer)
{
comparer = comparer ?? Comparer.Default;
return Java.Util.Collections.BinarySearch(list, element, comparer);
}
[NotImplemented]
public virtual int BinarySearch(int index, int count, object element, IComparer comparer)
{
if ((index < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
var size = list.Size();
if ((index >= size) || (count > size) || (index + count > size))
throw new ArgumentException();
comparer = comparer ?? Comparer.Default;
return Java.Util.Collections.BinarySearch(list.SubList(index, index + count), element, comparer);
}
/// <summary>
/// Remove all elements
/// </summary>
public virtual void Clear()
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
list.Clear();
}
/// <summary>
/// Create a shallow clone of this list.
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
return new ArrayList(this);
}
/// <summary>
/// Returns an enumerator for the entire list.
/// </summary>
/// <returns></returns>
public virtual IEnumerator GetEnumerator()
{
return new IteratorWrapper<object>(list);
}
/// <summary>
/// Returns an enumerator for the given range of this list.
/// </summary>
public virtual IEnumerator GetEnumerator(int index, int count)
{
if ((index < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
var size = list.Size();
if ((index >= size) || (count > size) || (index + count > size))
throw new ArgumentException();
return new IteratorWrapper<object>(list.SubList(index, index + count));
}
/// <summary>
/// Is the given object part of this list?
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual bool Contains(object value)
{
return list.Contains(value);
}
/// <summary>
/// Create a list that is a subset of this list.
/// </summary>
public virtual ArrayList GetRange(int index, int count)
{
if ((index < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
if (index + count >= list.Size())
throw new ArgumentException();
return new ArrayList(list.SubList(index, index + count), isFixedSize, isReadOnly, isSynchronized);
}
/// <summary>
/// Gets the first index of the given element/
/// </summary>
/// <returns>-1 if not found</returns>
public virtual int IndexOf(object element)
{
return list.IndexOf(element);
}
/// <summary>
/// Gets the first index of the given element/
/// </summary>
/// <returns>-1 if not found</returns>
public virtual int IndexOf(object element, int startIndex)
{
return IndexOf(element, startIndex, list.Size() - startIndex);
}
/// <summary>
/// Gets the first index of the given element/
/// </summary>
/// <returns>-1 if not found</returns>
public virtual int IndexOf(object element, int startIndex, int count)
{
if ((startIndex < 0) || (count < 0) || (startIndex >= list.Size()))
throw new ArgumentOutOfRangeException();
var rc = list.SubList(startIndex, startIndex + count).IndexOf(element);
return (rc >= 0) ? rc + startIndex : rc;
}
/// <summary>
/// Insert the given item at the given index.
/// </summary>
public virtual void Insert(int index, object element)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
if ((index < 0) || (index > list.Size()))
throw new ArgumentOutOfRangeException();
list.Add(index, element);
}
/// <summary>
/// Insert the given items at the given index.
/// </summary>
public virtual void InsertRange(int index, ICollection c)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
if (c == null)
throw new ArgumentNullException();
if ((index < 0) || (index > list.Size()))
throw new ArgumentOutOfRangeException();
foreach (var item in c)
{
list.Add(index++, item);
}
}
/// <summary>
/// Gets the last index of the given element/
/// </summary>
/// <returns>-1 if not found</returns>
public virtual int LastIndexOf(object element)
{
return list.LastIndexOf(element);
}
/// <summary>
/// Gets the last index of the given element/
/// </summary>
/// <returns>-1 if not found</returns>
public virtual int LastIndexOf(object element, int startIndex)
{
if ((startIndex < 0) || (startIndex >= list.Size()))
throw new ArgumentOutOfRangeException();
return list.SubList(0, startIndex).LastIndexOf(element);
}
/// <summary>
/// Gets the last index of the given element/
/// </summary>
/// <returns>-1 if not found</returns>
public virtual int LastIndexOf(object element, int startIndex, int count)
{
var size = list.Size();
if ((startIndex < 0) || (count < 0) || (startIndex >= size))
throw new ArgumentOutOfRangeException();
var start = (startIndex - count) + 1;
if (start < 0)
throw new ArgumentOutOfRangeException();
var end = startIndex + 1;
var rc = list.SubList(start, end).LastIndexOf(element);
return (rc >= 0) ? start + rc : rc;
}
/// <summary>
/// Remove the given item
/// </summary>
public virtual void Remove(object element)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
list.Remove(element);
}
/// <summary>
/// Remove the item at the given index.
/// </summary>
public virtual void RemoveAt(int index)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
if ((index < 0) || (index >= list.Size()))
throw new ArgumentOutOfRangeException();
list.Remove(index);
}
/// <summary>
/// Remove a range of items from list starting at the given the given index.
/// </summary>
public virtual void RemoveRange(int index, int count)
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
if ((index < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
var size = list.Size();
if ((index >= size) || (count > size) || (index + count > size))
throw new ArgumentException();
while (count > 0)
{
list.Remove(index);
count--;
}
}
/// <summary>
/// Reverse the order of items in the entire list.
/// </summary>
public virtual void Reverse()
{
if (isReadOnly)
throw new NotSupportedException();
var size = list.Size();
if (size > 1)
{
Java.Util.Collections.Reverse(list);
}
}
/// <summary>
/// Reverse the order of items in the given range.
/// </summary>
public virtual void Reverse(int index, int count)
{
if (isReadOnly)
throw new NotSupportedException();
if ((index < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
var size = list.Size();
if ((index >= size) || (count > size) || (index + count > size))
throw new ArgumentException();
if (count > 1)
{
Java.Util.Collections.Reverse(list.SubList(index, index + count));
}
}
/// <summary>
/// Copies the elements in the collection over the items in this list starting at the given list index.
/// </summary>
public virtual void SetRange(int index, ICollection c)
{
if (isReadOnly)
throw new NotSupportedException();
if (c == null)
throw new ArgumentNullException();
var count = c.Count;
if ((index < 0) || (index + count > list.Size()))
throw new ArgumentOutOfRangeException();
foreach (var item in c)
{
list[index++] = item;
}
}
/// <summary>
/// Sort the elements in the entire list.
/// </summary>
public virtual void Sort()
{
if (isReadOnly)
throw new NotSupportedException();
Java.Util.Collections.Sort(list);
}
/// <summary>
/// Sort the elements in the entire list.
/// </summary>
public virtual void Sort(IComparer comparer)
{
if (isReadOnly)
throw new NotSupportedException();
comparer = comparer ?? Comparer.Default;
Java.Util.Collections.Sort(list, comparer);
}
/// <summary>
/// Sort the elements in the given range.
/// </summary>
public virtual void Sort(int index, int count, IComparer comparer)
{
if (isReadOnly)
throw new NotSupportedException();
if ((index < 0) || (count < 0))
throw new ArgumentOutOfRangeException();
var size = list.Size();
if ((index > size) || (count > size) || (index + count > size))
throw new ArgumentException();
comparer = comparer ?? Comparer.Default;
Java.Util.Collections.Sort(list.SubList(index, index + count), comparer);
}
/// <summary>
/// Copy all items of the list into a new array.
/// </summary>
public virtual object[] ToArray()
{
return list.ToArray();
}
/// <summary>
/// Copy all items of the list into a new array.
/// </summary>
public virtual Array ToArray(Type elementType)
{
if (elementType == null)
throw new ArgumentNullException();
var arr = (Array)Java.Lang.Reflect.Array.NewInstance(elementType, list.Size());
CopyTo(arr);
return arr;
}
/// <summary>
/// Set the capacity of the list to the number of items in the list.
/// </summary>
public virtual void TrimToSize()
{
if (isFixedSize || isReadOnly)
throw new NotSupportedException();
}
/// <summary>
/// Create an ArrayList wrapper around the given list.
/// </summary>
[NotImplemented]
public static ArrayList Adapter(IList list)
{
if (list == null)
throw new ArgumentNullException();
var wrappedList = UnwrapListOrArray(list);
if (wrappedList != null)
return new ArrayList(wrappedList, list.IsFixedSize, list.IsReadOnly, list.IsSynchronized);
throw new NotImplementedException("System.Collections.ArrayList.Adapter");
}
/// <summary>
/// Create a list wrapper with a fixed size that is backed by the given list.
/// </summary>
public static ArrayList FixedSize(ArrayList list)
{
if (list == null)
throw new ArgumentNullException();
return new ArrayList(list.list, true, list.isReadOnly, list.isSynchronized);
}
/// <summary>
/// Create a list wrapper with a fixed size that is backed by the given list.
/// </summary>
[NotImplemented]
public static ArrayList FixedSize(IList list)
{
if (list == null)
throw new ArgumentNullException();
var wrappedList = UnwrapListOrArray(list);
if (wrappedList != null)
return new ArrayList(wrappedList, true, list.IsReadOnly, list.IsSynchronized);
throw new NotImplementedException("System.Collections.ArrayList.FixedSize");
}
/// <summary>
/// Create a readonly list wrapper that is backed by the given list.
/// </summary>
public static ArrayList ReadOnly(ArrayList list)
{
if (list == null)
throw new ArgumentNullException();
return new ArrayList(list.list, list.isFixedSize, true, list.isSynchronized);
}
/// <summary>
/// Create a readonly list wrapper that is backed by the given list.
/// </summary>
[NotImplemented]
public static ArrayList ReadOnly(IList list)
{
if (list == null)
throw new ArgumentNullException();
var wrappedList = UnwrapListOrArray(list);
if (wrappedList != null)
return new ArrayList(wrappedList, list.IsFixedSize, true, list.IsSynchronized);
throw new NotImplementedException("System.Collections.ArrayList.ReadOnly");
}
/// <summary>
/// Return an ArrayList filled count element of the given value.
/// </summary>
public static ArrayList Repeat(object value, int count)
{
if (count < 0)
throw new ArgumentOutOfRangeException();
var result = new ArrayList(count);
while (count > 0)
{
result.list.Add(value);
count--;
}
return result;
}
/// <summary>
/// Create a thread safe list wrapper that is backed by the given list.
/// </summary>
public static ArrayList Synchronized(ArrayList list)
{
if (list == null)
throw new ArgumentNullException();
return new ArrayList(Java.Util.Collections.SynchronizedList(list.list), list.isFixedSize, list.isReadOnly, true);
}
/// <summary>
/// Create a thread safe list wrapper that is backed by the given list.
/// </summary>
[NotImplemented]
public static ArrayList Synchronized(IList list)
{
if (list == null)
throw new ArgumentNullException();
var wrappedList = UnwrapListOrArray(list);
if (wrappedList != null)
return new ArrayList(wrappedList, list.IsFixedSize, list.IsReadOnly, true);
throw new NotImplementedException("System.Collections.ArrayList.Synchronized");
}
private static Java.Util.IList<object> UnwrapListOrArray(IList list)
{
var wrapper = list as IJavaCollectionWrapper<object>;
if (wrapper != null)
{
return wrapper.Collection as Java.Util.IList<object>;
}
var wrapper1 = list as CompilerHelper.ArrayCollectionWrapper;
if (wrapper1 != null)
{
if(wrapper1.array is object[])
return Arrays.AsList((object[])wrapper1.array);
if (wrapper1.array is int[])
return (Java.Util.IList<object>)Arrays.AsList((int[])wrapper1.array);
if (wrapper1.array is sbyte[])
return (Java.Util.IList<object>)Arrays.AsList((sbyte[])wrapper1.array);
if (wrapper1.array is short[])
return (Java.Util.IList<object>)Arrays.AsList((short[])wrapper1.array);
if (wrapper1.array is char[])
return (Java.Util.IList<object>)Arrays.AsList((char[])wrapper1.array);
if (wrapper1.array is long[])
return (Java.Util.IList<object>)Arrays.AsList((long[])wrapper1.array);
if (wrapper1.array is float[])
return (Java.Util.IList<object>)Arrays.AsList((float[])wrapper1.array);
if (wrapper1.array is double[])
return (Java.Util.IList<object>)Arrays.AsList((double[])wrapper1.array);
return null;
}
return null;
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using Encog.ML.Data.Market.Loader;
using Encog.ML.Data.Temporal;
using Encog.Util.Time;
namespace Encog.ML.Data.Market
{
/// <summary>
/// A data set that is designed to hold market data. This class is based on the
/// TemporalNeuralDataSet. This class is designed to load financial data from
/// external sources. This class is designed to track financial data across days.
/// However, it should be usable with other levels of granularity as well.
/// </summary>
public sealed class MarketMLDataSet : TemporalMLDataSet
{
/// <summary>
/// The loader to use to obtain the data.
/// </summary>
private readonly IMarketLoader _loader;
/// <summary>
/// A map between the data points and actual data.
/// </summary>
private readonly IDictionary<Int64, TemporalPoint> _pointIndex =
new Dictionary<Int64, TemporalPoint>();
/// <summary>
/// Construct a market data set object.
/// </summary>
/// <param name="loader">The loader to use to get the financial data.</param>
/// <param name="inputWindowSize">The input window size, that is how many datapoints do we use to predict.</param>
/// <param name="predictWindowSize">How many datapoints do we want to predict.</param>
public MarketMLDataSet(IMarketLoader loader,Int64 inputWindowSize, Int64 predictWindowSize)
: base((int)inputWindowSize, (int)predictWindowSize)
{
_loader = loader;
SequenceGrandularity = TimeUnit.Days;
}
/// <summary>
/// Initializes a new instance of the <see cref="MarketMLDataSet"/> class.
/// </summary>
/// <param name="loader">The loader.</param>
/// <param name="inputWindowSize">Size of the input window.</param>
/// <param name="predictWindowSize">Size of the predict window.</param>
/// <param name="unit">The time unit to use.</param>
public MarketMLDataSet(IMarketLoader loader, Int64 inputWindowSize, Int64 predictWindowSize, TimeUnit unit)
: base((int)inputWindowSize, (int)predictWindowSize)
{
_loader = loader;
SequenceGrandularity =unit;
}
/// <summary>
/// The loader that is being used for this set.
/// </summary>
public IMarketLoader Loader
{
get { return _loader; }
}
/// <summary>
/// Add one description of the type of market data that we are seeking at
/// each datapoint.
/// </summary>
/// <param name="desc"></param>
public override void AddDescription(TemporalDataDescription desc)
{
if (!(desc is MarketDataDescription))
{
throw new MarketError(
"Only MarketDataDescription objects may be used "
+ "with the MarketMLDataSet container.");
}
base.AddDescription(desc);
}
/// <summary>
/// Create a datapoint at the specified date.
/// </summary>
/// <param name="when">The date to create the point at.</param>
/// <returns>Returns the TemporalPoint created for the specified date.</returns>
public override TemporalPoint CreatePoint(DateTime when)
{
Int64 sequence = (Int64)GetSequenceFromDate(when);
TemporalPoint result;
if (_pointIndex.ContainsKey(sequence))
{
result = _pointIndex[sequence];
}
else
{
result = base.CreatePoint(when);
_pointIndex[(int)result.Sequence] = result;
}
return result;
}
/// <summary>
/// Load data from the loader.
/// </summary>
/// <param name="begin">The beginning date.</param>
/// <param name="end">The ending date.</param>
public void Load(DateTime begin, DateTime end)
{
// define the starting point if it is not already defined
if (StartingPoint == DateTime.MinValue)
{
StartingPoint = begin;
}
// clear out any loaded points
Points.Clear();
// first obtain a collection of symbols that need to be looked up
IDictionary<TickerSymbol, object> symbolSet = new Dictionary<TickerSymbol, object>();
foreach (MarketDataDescription desc in Descriptions)
{
if (symbolSet.Count == 0)
{
symbolSet[desc.Ticker] = null;
}
foreach (TickerSymbol ts in symbolSet.Keys)
{
if (!ts.Equals(desc.Ticker))
{
symbolSet[desc.Ticker] = null;
break;
}
}
}
// now loop over each symbol and load the data
foreach (TickerSymbol symbol in symbolSet.Keys)
{
LoadSymbol(symbol, begin, end);
}
// resort the points
SortPoints();
}
/// <summary>
/// Load one point of market data.
/// </summary>
/// <param name="ticker">The ticker symbol to load.</param>
/// <param name="point">The point to load at.</param>
/// <param name="item">The item being loaded.</param>
private void LoadPointFromMarketData(TickerSymbol ticker,
TemporalPoint point, LoadedMarketData item)
{
foreach (TemporalDataDescription desc in Descriptions)
{
var mdesc = (MarketDataDescription) desc;
if (mdesc.Ticker.Equals(ticker))
{
point.Data[mdesc.Index] = item.Data[mdesc.DataType];
}
}
}
/// <summary>
/// Load one ticker symbol.
/// </summary>
/// <param name="ticker">The ticker symbol to load.</param>
/// <param name="from">Load data from this date.</param>
/// <param name="to">Load data to this date.</param>
private void LoadSymbol(TickerSymbol ticker, DateTime from,
DateTime to)
{
IList < MarketDataType > types = new List<MarketDataType>();
foreach (MarketDataDescription desc in Descriptions)
{
if (desc.Ticker.Equals(ticker))
{
types.Add(desc.DataType);
}
}
ICollection<LoadedMarketData> data = Loader.Load(ticker, types, from, to);
foreach (LoadedMarketData item in data)
{
TemporalPoint point = CreatePoint(item.When);
LoadPointFromMarketData(ticker, point, item);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Xml;
using Epi;
using Epi.Data;
using Epi.Data.Services;
namespace Epi.Fields
{
/// <summary>
/// Date Field.
/// </summary>
public class DateField : DateTimeField
{
#region Fields
private string _pattern = string.Empty;
private string _lower = string.Empty;
private string _upper = string.Empty;
private DateTime _lowerDateTime;
private DateTime _upperDateTime;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
private const string ISO8601 = "YYYY-MM-DD";
//-EI-111
private bool _notfuturedate;
//
#endregion Fields
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public DateField(Page page)
: base(page)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
public DateField(View view)
: base(view)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">Page</param>
/// <param name="viewElement">Xml view element</param>
public DateField(Page page, XmlElement viewElement)
: base(page, viewElement)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
/// <param name="fieldNode">Field Node</param>
public DateField(View view, XmlNode fieldNode)
: base(view, fieldNode)
{
construct();
}
private void construct()
{
genericDbColumnType = GenericDbColumnType.Date;
this.dbColumnType = DbType.Date;
}
#endregion Constructors
/// <summary>
/// Load from row
/// </summary>
/// <param name="row">Row</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
_pattern = row[ColumnNames.PATTERN].ToString();
_lower = row[ColumnNames.LOWER].ToString();
_upper = row[ColumnNames.UPPER].ToString();
//---EI-111
if (_upper == CommandNames.SYSTEMDATE)
{
_upper = GetRange(DateTime.Today);
_notfuturedate = true;
}
//--
LowerDate = GetRange(_lower);
UpperDate = GetRange(_upper);
}
public DateTimeField Clone()
{
DateTimeField clone = (DateTimeField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
public bool IsInRange(DateTime dateCandidate)
{
if (LowerDate.Ticks == 0 && UpperDate.Ticks == 0)
{
return true;
}
if (LowerDate <= dateCandidate && dateCandidate <= UpperDate )
{
return true;
}
else
{
string warningMessage = String.Format(
SharedStrings.INVALID_DATE_RANGE,
LowerDate.ToShortDateString(),
UpperDate.ToShortDateString());
//--Ei-111
if (_notfuturedate)
{
warningMessage = SharedStrings.INVALID_NOTFUTUREDATE;
}
//--
System.Windows.Forms.MessageBox.Show(
warningMessage,
SharedStrings.WARNING,
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Warning);
}
return false;
}
#region Public Properties
public override string Watermark
{
get
{
System.Globalization.DateTimeFormatInfo formatInfo = System.Globalization.DateTimeFormatInfo.CurrentInfo;
return formatInfo.ShortDatePattern.ToUpperInvariant();
}
}
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.Date;
}
}
/// <summary>
/// Returns a string representation of Current Record Value
/// </summary>
public sealed override string CurrentRecordValueString
{
get
{
if (CurrentRecordValueObject == null || CurrentRecordValueObject.Equals(DBNull.Value))
{
return string.Empty;
}
else
{
if (CurrentRecordValueObject is DateTime)
{
return ((DateTime)CurrentRecordValueObject).ToShortDateString();
}
else if (CurrentRecordValueObject is String)
{
DateTime dateTime = new DateTime();
if (DateTime.TryParse((string)CurrentRecordValueObject, out dateTime))
{
CurrentRecordValueObject = dateTime;
return dateTime.ToShortDateString();
}
}
}
return string.Empty;
}
}
/// <summary>
/// Lower
/// </summary>
public string Lower
{
get
{
return (_lower);
}
set
{
_lower = value;
}
}
/// <summary>
/// Upper
/// </summary>
public string Upper
{
get
{
return (_upper);
}
set
{
_upper = value;
}
}
//--EI-111
/// <summary>
/// Notfuturedate
/// </summary>
public bool Notfuturedate
{
get
{
return (_notfuturedate);
}
set
{
_notfuturedate = value;
}
}
//--
/// <summary>
/// Pattern
/// </summary>
public string Pattern
{
get
{
return _pattern == "" ? ISO8601 : _pattern;
}
set
{
_pattern = value == "" ? ISO8601 : value; // ISO8601
}
}
public DateTime LowerDate
{
get
{
return (_lowerDateTime);
}
set
{
if (((DateTime)value).Ticks > 0)
{
_lowerDateTime = value;
_lower = GetRange(value);
}
else
{
_lower = "";
}
}
}
public DateTime UpperDate
{
get
{
return (_upperDateTime);
}
set
{
if (((DateTime)value).Ticks > 0)
{
_upperDateTime = value;
_upper = GetRange(value);
}
else
{
_upper = "";
}
}
}
#endregion Public Properties
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
protected string GetRange(DateTime dateTime)
{
string format = Pattern.Replace("-", "'-'");
format = format.Replace("Y", "y");
format = format.Replace("D", "d");
return dateTime.ToString(format);
}
protected DateTime GetRange(String dateString)
{
DateTime dateCandidate = new DateTime();
if (string.IsNullOrEmpty(dateString)) return dateCandidate;
string format = Pattern.Replace("-", "'-'");
format = format.Replace("Y", "y");
format = format.Replace("D", "d");
bool result = DateTime.TryParseExact(
dateString,
format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.None,
out dateCandidate);
return dateCandidate;
}
#endregion Private Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using EmergeTk.Widgets.Html;
namespace EmergeTk.Model
{
public enum FieldLayout
{
Terse,
Spacious
}
public class DataTypeFieldBuilder
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(DataTypeFieldBuilder));
private DataTypeFieldBuilder()
{
}
public static Widget GetViewWidget(ColumnInfo fi)
{
Widget l = Context.Current.CreateWidget<Label>();
l.Id = fi.Name;
return l;
}
public static Widget GetEditWidget(ColumnInfo fi, FieldLayout layout)
{
return GetEditWidget( fi, layout, null, DataType.None );
}
public static Widget GetEditWidget(ColumnInfo fi, FieldLayout layout, IRecordList records, DataType hint)
{
if( fi.Type.Name.Contains("RecordList") )
return null;
Widget propWidget = null;
if( hint == DataType.None )
hint = fi.DataType;
switch( hint )
{
case DataType.SmallText:
TextBox smallTexBox = Context.Current.CreateWidget<TextBox>();
if( ! string.IsNullOrEmpty( fi.HelpText ) )
{
smallTexBox.HelpText = fi.HelpText;
}
smallTexBox.Columns = 20;
propWidget = smallTexBox;
break;
case DataType.Xml:
TextBox xmlTextBox = Context.Current.CreateWidget<TextBox>();
if( ! string.IsNullOrEmpty( fi.HelpText ) )
{
xmlTextBox.HelpText = fi.HelpText;
}
xmlTextBox.Rows = 10;
xmlTextBox.Columns = 40;
xmlTextBox.ClassName = "xmlTextBox";
propWidget = xmlTextBox;
break;
case DataType.LargeText:
TextBox largeTextBox = Context.Current.CreateWidget<TextBox>();
if( ! string.IsNullOrEmpty( fi.HelpText ) )
{
largeTextBox.HelpText = fi.HelpText;
}
largeTextBox.Rows = 10;
largeTextBox.Columns = 40;
//largeTextBox.IsRich = true;
if( layout == FieldLayout.Terse )
largeTextBox.ClassName = "largeGridEditTextBox";
propWidget = largeTextBox;
break;
case DataType.RecordSelect:
propWidget = (Widget)TypeLoader.InvokeGenericMethod( typeof(DataTypeFieldBuilder), "GetRecordSelect", new Type[]{fi.Type},null,new object[]{fi,records});
break;
case DataType.RecordSelectOrCreate:
propWidget = (Widget)TypeLoader.InvokeGenericMethod( typeof(DataTypeFieldBuilder), "GetSelectOrCreate", new Type[]{fi.Type},null,new object[]{fi,records});
break;
case DataType.ReadOnly:
propWidget = Context.Current.CreateWidget<Label>();
break;
}
if( propWidget == null )
{
if( fi.Type == typeof(DateTime) )
{
propWidget = Context.Current.CreateWidget<DatePicker>();
}
else if (fi.Type.IsEnum)
{
DropDown dd = Context.Current.CreateWidget<DropDown>();
List<string> ids = new List<string>(Enum.GetNames(fi.Type));
List<string> options = new List<string>();
object[] attributes = fi.Type.GetCustomAttributes(typeof(FriendlyNameAttribute),false );
if( attributes != null && attributes.Length > 0 )
{
FriendlyNameAttribute fa = attributes[0] as FriendlyNameAttribute;
for( int i = 0; i < fa.FieldNames.Length; i++ )
options.Add(fa.FieldNames[i] );
}
else for( int i = 0; i < ids.Count; i++ )
options.Add( Util.PascalToHuman( ids[i] ) );
dd.Ids = ids;
dd.Options = options;
dd.DefaultProperty = "SelectedId";
propWidget = dd;
}
else if( fi.Type == typeof(bool) )
{
SelectItem si = Context.Current.CreateWidget<SelectItem>();
si.Mode = SelectionMode.Multiple;
propWidget = si;
}
else if( fi.Type == typeof(int) || fi.Type == typeof(float) )
{
TextBox tb = Context.Current.CreateWidget<TextBox>();
if( ! string.IsNullOrEmpty( fi.HelpText ) )
{
tb.HelpText = fi.HelpText;
}
if (layout == FieldLayout.Spacious) tb.Columns = 5;
propWidget = tb;
}
else if( fi.Type.IsSubclassOf(typeof(AbstractRecord)) )
{
propWidget = (Widget)TypeLoader.InvokeGenericMethod( typeof(DataTypeFieldBuilder), "GetModelForm", new Type[]{fi.Type},null,new object[]{fi,records});
}
else
{
TextBox tb = Context.Current.CreateWidget<TextBox>();
if( ! string.IsNullOrEmpty( fi.HelpText ) )
{
tb.HelpText = fi.HelpText;
}
propWidget = tb;
}
}
propWidget.Id = fi.Name;
string helpText = null;
if (layout == FieldLayout.Spacious)
{
LabeledWidget<Widget> lc = Context.Current.CreateWidget<LabeledWidget<Widget>>();
lc.LabelText = Util.PascalToHuman(fi.Name);
if( fi.HelpText != null )
{
Label help = Context.Current.CreateWidget<Label>();
help.Text = helpText;
help.ClassName = "editfield-helptext";
lc.Label.Add(help);
}
lc.Widget = propWidget;
propWidget = lc;
}
return propWidget;
}
public static Widget GetModelForm<T>(Model.ColumnInfo fi, IRecordList records ) where T : AbstractRecord, new()
{
ModelForm<T> mf = Context.Current.CreateWidget<ModelForm<T>>();
mf.BindsTo = typeof(T);
mf.DestructivelyEdit = true;
mf.ShowCancelButton = false;
mf.ShowDeleteButton = false;
mf.ShowSaveButton = false;
return mf;
}
public static Widget GetSelectOrCreate<T>(Model.ColumnInfo fi, IRecordList records ) where T : AbstractRecord, new()
{
RecordController rc = Context.Current.CreateWidget<RecordController>();
rc.BindsTo = typeof(T);
if( records == null )
records = DataProvider.Factory.GetProvider(typeof(T)).Load<T>();
#if DEBUG
log.Debug( "setting records to RecordController ", records, records.Count );
#endif
rc.AvailableOptions = records;
return rc;
}
public static Widget GetRecordSelect<T>(Model.ColumnInfo fi, IRecordList records ) where T : AbstractRecord, new()
{
IDataSourced dd;
//Autocomplete dd = Context.Current.CreateWidget<Autocomplete>();
if( records == null )
records = DataProvider.Factory.GetProvider(typeof(T)).Load<T>();
dd = RecordSelect<T>.CreateSelector( records.Count );
dd.DataSource = records as IRecordList<T>;
dd.DataBind();
return (Widget)dd;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Globalization.CompareInfo.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Globalization
{
public partial class CompareInfo : System.Runtime.Serialization.IDeserializationCallback
{
#region Methods and constructors
public virtual new int Compare(string string1, string string2, CompareOptions options)
{
return default(int);
}
public virtual new int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
return default(int);
}
public virtual new int Compare(string string1, string string2)
{
return default(int);
}
public virtual new int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options)
{
return default(int);
}
public virtual new int Compare(string string1, int offset1, string string2, int offset2)
{
return default(int);
}
public virtual new int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
return default(int);
}
internal CompareInfo()
{
}
public override bool Equals(Object value)
{
return default(bool);
}
public static CompareInfo GetCompareInfo(int culture, System.Reflection.Assembly assembly)
{
return default(CompareInfo);
}
public static CompareInfo GetCompareInfo(string name, System.Reflection.Assembly assembly)
{
return default(CompareInfo);
}
public static CompareInfo GetCompareInfo(string name)
{
return default(CompareInfo);
}
public static CompareInfo GetCompareInfo(int culture)
{
return default(CompareInfo);
}
public override int GetHashCode()
{
return default(int);
}
public virtual new SortKey GetSortKey(string source, CompareOptions options)
{
return default(SortKey);
}
public virtual new SortKey GetSortKey(string source)
{
return default(SortKey);
}
public virtual new int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
return default(int);
}
public virtual new int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
return default(int);
}
public virtual new int IndexOf(string source, string value, int startIndex)
{
return default(int);
}
public virtual new int IndexOf(string source, char value, int startIndex, int count)
{
return default(int);
}
public virtual new int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
return default(int);
}
public virtual new int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
return default(int);
}
public virtual new int IndexOf(string source, string value, int startIndex, int count)
{
return default(int);
}
public virtual new int IndexOf(string source, string value)
{
return default(int);
}
public virtual new int IndexOf(string source, char value)
{
return default(int);
}
public virtual new int IndexOf(string source, char value, CompareOptions options)
{
return default(int);
}
public virtual new int IndexOf(string source, char value, int startIndex)
{
return default(int);
}
public virtual new int IndexOf(string source, string value, CompareOptions options)
{
return default(int);
}
public virtual new bool IsPrefix(string source, string prefix, CompareOptions options)
{
return default(bool);
}
public virtual new bool IsPrefix(string source, string prefix)
{
return default(bool);
}
public static bool IsSortable(string text)
{
return default(bool);
}
public static bool IsSortable(char ch)
{
return default(bool);
}
public virtual new bool IsSuffix(string source, string suffix)
{
return default(bool);
}
public virtual new bool IsSuffix(string source, string suffix, CompareOptions options)
{
return default(bool);
}
public virtual new int LastIndexOf(string source, string value, int startIndex, int count)
{
return default(int);
}
public virtual new int LastIndexOf(string source, char value, int startIndex, int count)
{
return default(int);
}
public virtual new int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
return default(int);
}
public virtual new int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
return default(int);
}
public virtual new int LastIndexOf(string source, char value, CompareOptions options)
{
return default(int);
}
public virtual new int LastIndexOf(string source, string value, CompareOptions options)
{
return default(int);
}
public virtual new int LastIndexOf(string source, char value)
{
return default(int);
}
public virtual new int LastIndexOf(string source, string value)
{
return default(int);
}
public virtual new int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return default(int);
}
public virtual new int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return default(int);
}
public virtual new int LastIndexOf(string source, char value, int startIndex)
{
return default(int);
}
public virtual new int LastIndexOf(string source, string value, int startIndex)
{
return default(int);
}
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender)
{
}
public override string ToString()
{
return default(string);
}
#endregion
#region Properties and indexers
public int LCID
{
get
{
return default(int);
}
}
public virtual new string Name
{
get
{
return default(string);
}
}
#endregion
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using PlayFab.Json.Utilities;
using System.Globalization;
using System.ComponentModel;
namespace PlayFab.Json.Linq
{
/// <summary>
/// Represents a value in JSON (string, integer, date, etc).
/// </summary>
public class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue>
{
private JTokenType _valueType;
private object _value;
internal JValue(object value, JTokenType type)
{
_value = value;
_valueType = type;
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object.
/// </summary>
/// <param name="other">A <see cref="JValue"/> object to copy from.</param>
public JValue(JValue other)
: this(other.Value, other.Type)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(long value)
: this(value, JTokenType.Integer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
//
public JValue(ulong value)
: this(value, JTokenType.Integer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(double value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(DateTime value)
: this(value, JTokenType.Date)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(bool value)
: this(value, JTokenType.Boolean)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(string value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(Guid value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(Uri value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(TimeSpan value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(object value)
: this(value, GetValueType(null, value))
{
}
internal override bool DeepEquals(JToken node)
{
JValue other = node as JValue;
if (other == null)
return false;
return ValuesEquals(this, other);
}
/// <summary>
/// Gets a value indicating whether this token has childen tokens.
/// </summary>
/// <value>
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
/// </value>
public override bool HasValues
{
get { return false; }
}
private static int Compare(JTokenType valueType, object objA, object objB)
{
if (objA == null && objB == null)
return 0;
if (objA != null && objB == null)
return 1;
if (objA == null && objB != null)
return -1;
switch (valueType)
{
case JTokenType.Integer:
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
else if (objA is float || objB is float || objA is double || objB is double)
return CompareFloat(objA, objB);
else
return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
case JTokenType.Float:
return CompareFloat(objA, objB);
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);
return s1.CompareTo(s2);
case JTokenType.Boolean:
bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);
return b1.CompareTo(b2);
case JTokenType.Date:
if (objA is DateTime)
{
DateTime date1 = Convert.ToDateTime(objA, CultureInfo.InvariantCulture);
DateTime date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
return date1.CompareTo(date2);
}
else
{
if (!(objB is DateTimeOffset))
throw new ArgumentException("Object must be of type DateTimeOffset.");
DateTimeOffset date1 = (DateTimeOffset) objA;
DateTimeOffset date2 = (DateTimeOffset) objB;
return date1.CompareTo(date2);
}
case JTokenType.Bytes:
if (!(objB is byte[]))
throw new ArgumentException("Object must be of type byte[].");
byte[] bytes1 = objA as byte[];
byte[] bytes2 = objB as byte[];
if (bytes1 == null)
return -1;
if (bytes2 == null)
return 1;
return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
case JTokenType.Guid:
if (!(objB is Guid))
throw new ArgumentException("Object must be of type Guid.");
Guid guid1 = (Guid) objA;
Guid guid2 = (Guid) objB;
return guid1.CompareTo(guid2);
case JTokenType.Uri:
if (!(objB is Uri))
throw new ArgumentException("Object must be of type Uri.");
Uri uri1 = (Uri)objA;
Uri uri2 = (Uri)objB;
return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
case JTokenType.TimeSpan:
if (!(objB is TimeSpan))
throw new ArgumentException("Object must be of type TimeSpan.");
TimeSpan ts1 = (TimeSpan)objA;
TimeSpan ts2 = (TimeSpan)objB;
return ts1.CompareTo(ts2);
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
}
}
private static int CompareFloat(object objA, object objB)
{
double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture);
double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture);
// take into account possible floating point errors
if (MathUtils.ApproxEquals(d1, d2))
return 0;
return d1.CompareTo(d2);
}
internal override JToken CloneToken()
{
return new JValue(this);
}
/// <summary>
/// Creates a <see cref="JValue"/> comment with the given value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> comment with the given value.</returns>
public static JValue CreateComment(string value)
{
return new JValue(value, JTokenType.Comment);
}
/// <summary>
/// Creates a <see cref="JValue"/> string with the given value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> string with the given value.</returns>
public static JValue CreateString(string value)
{
return new JValue(value, JTokenType.String);
}
private static JTokenType GetValueType(JTokenType? current, object value)
{
if (value == null)
return JTokenType.Null;
else if (value == DBNull.Value)
return JTokenType.Null;
else if (value is string)
return GetStringValueType(current);
else if (value is long || value is int || value is short || value is sbyte
|| value is ulong || value is uint || value is ushort || value is byte)
return JTokenType.Integer;
else if (value is Enum)
return JTokenType.Integer;
else if (value is double || value is float || value is decimal)
return JTokenType.Float;
else if (value is DateTime)
return JTokenType.Date;
else if (value is DateTimeOffset)
return JTokenType.Date;
else if (value is byte[])
return JTokenType.Bytes;
else if (value is bool)
return JTokenType.Boolean;
else if (value is Guid)
return JTokenType.Guid;
else if (value is Uri)
return JTokenType.Uri;
else if (value is TimeSpan)
return JTokenType.TimeSpan;
throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static JTokenType GetStringValueType(JTokenType? current)
{
if (current == null)
return JTokenType.String;
switch (current.Value)
{
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
return current.Value;
default:
return JTokenType.String;
}
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
get { return _valueType; }
}
#pragma warning disable 108
/// <summary>
/// Gets or sets the underlying token value.
/// </summary>
/// <value>The underlying token value.</value>
public object Value
{
get { return _value; }
set
{
Type currentType = (_value != null) ? _value.GetType() : null;
Type newType = (value != null) ? value.GetType() : null;
if (currentType != newType)
_valueType = GetValueType(_valueType, value);
_value = value;
}
}
#pragma warning restore 108
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
switch (_valueType)
{
case JTokenType.Comment:
writer.WriteComment(_value.ToString());
return;
case JTokenType.Raw:
writer.WriteRawValue((_value != null) ? _value.ToString() : null);
return;
case JTokenType.Null:
writer.WriteNull();
return;
case JTokenType.Undefined:
writer.WriteUndefined();
return;
}
JsonConverter matchingConverter;
if (_value != null && ((matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType())) != null))
{
matchingConverter.WriteJson(writer, _value, new JsonSerializer());
return;
}
switch (_valueType)
{
case JTokenType.Integer:
writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture));
return;
case JTokenType.Float:
writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture));
return;
case JTokenType.String:
writer.WriteValue((_value != null) ? _value.ToString() : null);
return;
case JTokenType.Boolean:
writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture));
return;
case JTokenType.Date:
if (_value is DateTimeOffset)
writer.WriteValue((DateTimeOffset)_value);
else
writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); ;
return;
case JTokenType.Bytes:
writer.WriteValue((byte[])_value);
return;
case JTokenType.Guid:
case JTokenType.Uri:
case JTokenType.TimeSpan:
writer.WriteValue((_value != null) ? _value.ToString() : null);
return;
}
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type.");
}
internal override int GetDeepHashCode()
{
int valueHashCode = (_value != null) ? _value.GetHashCode() : 0;
return _valueType.GetHashCode() ^ valueHashCode;
}
private static bool ValuesEquals(JValue v1, JValue v2)
{
return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0));
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(JValue other)
{
if (other == null)
return false;
return ValuesEquals(this, other);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (obj == null)
return false;
JValue otherValue = obj as JValue;
if (otherValue != null)
return Equals(otherValue);
return base.Equals(obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
if (_value == null)
return 0;
return _value.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (_value == null)
return string.Empty;
return _value.ToString();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public string ToString(IFormatProvider formatProvider)
{
return ToString(null, formatProvider);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
if (_value == null)
return string.Empty;
IFormattable formattable = _value as IFormattable;
if (formattable != null)
return formattable.ToString(format, formatProvider);
else
return _value.ToString();
}
int IComparable.CompareTo(object obj)
{
if (obj == null)
return 1;
object otherValue = (obj is JValue) ? ((JValue) obj).Value : obj;
return Compare(_valueType, _value, otherValue);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value
/// Meaning
/// Less than zero
/// This instance is less than <paramref name="obj"/>.
/// Zero
/// This instance is equal to <paramref name="obj"/>.
/// Greater than zero
/// This instance is greater than <paramref name="obj"/>.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="obj"/> is not the same type as this instance.
/// </exception>
public int CompareTo(JValue obj)
{
if (obj == null)
return 1;
return Compare(_valueType, _value, obj._value);
}
}
}
#endif
| |
/*
'===============================================================================
' Generated From - VistaDB_CSharp_BusinessEntity.vbgen
'
' The supporting base class VistaDBEntity is in the Architecture directory in "dOOdads".
'
' This object is 'abstract' which means you need to inherit from it to be able
' to instantiate it. This is very easilly done. You can override properties and
' methods in your derived class, this allows you to regenerate this class at any
' time and not worry about overwriting custom code.
'
' NEVER EDIT THIS FILE.
'
' public class YourObject : _YourObject
' {
'
' }
'
'===============================================================================
*/
// Generated by MyGeneration Version # (1.1.3.5)
using System;
using System.Data;
using VistaDB;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace MyGeneration.dOOdads.Tests.VistaDB
{
public abstract class _AggregateTest : VistaDBEntity
{
public _AggregateTest()
{
this.QuerySource = "AggregateTest";
this.MappingName = "AggregateTest";
}
//=================================================================
// public Overrides void AddNew()
//=================================================================
//
//=================================================================
public override void AddNew()
{
base.AddNew();
}
public override void FlushData()
{
this._whereClause = null;
this._aggregateClause = null;
base.FlushData();
}
public override string GetAutoKeyColumns()
{
return "ID";
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
return this.Query.Load();
}
//=================================================================
// public Overridable Function LoadByPrimaryKey() As Boolean
//=================================================================
// Loads a single row of via the primary key
//=================================================================
public virtual bool LoadByPrimaryKey(int ID)
{
this.Where.ID.Value = ID;
return this.Query.Load();
}
#region Parameters
protected class Parameters
{
public static VistaDBParameter ID
{
get
{
return new VistaDBParameter("@ID", VistaDBType.Int32);
}
}
public static VistaDBParameter DepartmentID
{
get
{
return new VistaDBParameter("@DepartmentID", VistaDBType.Int32);
}
}
public static VistaDBParameter FirstName
{
get
{
return new VistaDBParameter("@FirstName", VistaDBType.Varchar);
}
}
public static VistaDBParameter LastName
{
get
{
return new VistaDBParameter("@LastName", VistaDBType.Varchar);
}
}
public static VistaDBParameter Age
{
get
{
return new VistaDBParameter("@Age", VistaDBType.Int32);
}
}
public static VistaDBParameter HireDate
{
get
{
return new VistaDBParameter("@HireDate", VistaDBType.DateTime);
}
}
public static VistaDBParameter Salary
{
get
{
return new VistaDBParameter("@Salary", VistaDBType.Currency);
}
}
public static VistaDBParameter IsActive
{
get
{
return new VistaDBParameter("@IsActive", VistaDBType.Boolean);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string ID = "ID";
public const string DepartmentID = "DepartmentID";
public const string FirstName = "FirstName";
public const string LastName = "LastName";
public const string Age = "Age";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ID] = _AggregateTest.PropertyNames.ID;
ht[DepartmentID] = _AggregateTest.PropertyNames.DepartmentID;
ht[FirstName] = _AggregateTest.PropertyNames.FirstName;
ht[LastName] = _AggregateTest.PropertyNames.LastName;
ht[Age] = _AggregateTest.PropertyNames.Age;
ht[HireDate] = _AggregateTest.PropertyNames.HireDate;
ht[Salary] = _AggregateTest.PropertyNames.Salary;
ht[IsActive] = _AggregateTest.PropertyNames.IsActive;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string ID = "ID";
public const string DepartmentID = "DepartmentID";
public const string FirstName = "FirstName";
public const string LastName = "LastName";
public const string Age = "Age";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ID] = _AggregateTest.ColumnNames.ID;
ht[DepartmentID] = _AggregateTest.ColumnNames.DepartmentID;
ht[FirstName] = _AggregateTest.ColumnNames.FirstName;
ht[LastName] = _AggregateTest.ColumnNames.LastName;
ht[Age] = _AggregateTest.ColumnNames.Age;
ht[HireDate] = _AggregateTest.ColumnNames.HireDate;
ht[Salary] = _AggregateTest.ColumnNames.Salary;
ht[IsActive] = _AggregateTest.ColumnNames.IsActive;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string ID = "s_ID";
public const string DepartmentID = "s_DepartmentID";
public const string FirstName = "s_FirstName";
public const string LastName = "s_LastName";
public const string Age = "s_Age";
public const string HireDate = "s_HireDate";
public const string Salary = "s_Salary";
public const string IsActive = "s_IsActive";
}
#endregion
#region Properties
public virtual int ID
{
get
{
return base.Getint(ColumnNames.ID);
}
set
{
base.Setint(ColumnNames.ID, value);
}
}
public virtual int DepartmentID
{
get
{
return base.Getint(ColumnNames.DepartmentID);
}
set
{
base.Setint(ColumnNames.DepartmentID, value);
}
}
public virtual string FirstName
{
get
{
return base.Getstring(ColumnNames.FirstName);
}
set
{
base.Setstring(ColumnNames.FirstName, value);
}
}
public virtual string LastName
{
get
{
return base.Getstring(ColumnNames.LastName);
}
set
{
base.Setstring(ColumnNames.LastName, value);
}
}
public virtual int Age
{
get
{
return base.Getint(ColumnNames.Age);
}
set
{
base.Setint(ColumnNames.Age, value);
}
}
public virtual DateTime HireDate
{
get
{
return base.GetDateTime(ColumnNames.HireDate);
}
set
{
base.SetDateTime(ColumnNames.HireDate, value);
}
}
public virtual decimal Salary
{
get
{
return base.Getdecimal(ColumnNames.Salary);
}
set
{
base.Setdecimal(ColumnNames.Salary, value);
}
}
public virtual bool IsActive
{
get
{
return base.Getbool(ColumnNames.IsActive);
}
set
{
base.Setbool(ColumnNames.IsActive, value);
}
}
#endregion
#region String Properties
public virtual string s_ID
{
get
{
return this.IsColumnNull(ColumnNames.ID) ? string.Empty : base.GetintAsString(ColumnNames.ID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ID);
else
this.ID = base.SetintAsString(ColumnNames.ID, value);
}
}
public virtual string s_DepartmentID
{
get
{
return this.IsColumnNull(ColumnNames.DepartmentID) ? string.Empty : base.GetintAsString(ColumnNames.DepartmentID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.DepartmentID);
else
this.DepartmentID = base.SetintAsString(ColumnNames.DepartmentID, value);
}
}
public virtual string s_FirstName
{
get
{
return this.IsColumnNull(ColumnNames.FirstName) ? string.Empty : base.GetstringAsString(ColumnNames.FirstName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.FirstName);
else
this.FirstName = base.SetstringAsString(ColumnNames.FirstName, value);
}
}
public virtual string s_LastName
{
get
{
return this.IsColumnNull(ColumnNames.LastName) ? string.Empty : base.GetstringAsString(ColumnNames.LastName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.LastName);
else
this.LastName = base.SetstringAsString(ColumnNames.LastName, value);
}
}
public virtual string s_Age
{
get
{
return this.IsColumnNull(ColumnNames.Age) ? string.Empty : base.GetintAsString(ColumnNames.Age);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Age);
else
this.Age = base.SetintAsString(ColumnNames.Age, value);
}
}
public virtual string s_HireDate
{
get
{
return this.IsColumnNull(ColumnNames.HireDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.HireDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.HireDate);
else
this.HireDate = base.SetDateTimeAsString(ColumnNames.HireDate, value);
}
}
public virtual string s_Salary
{
get
{
return this.IsColumnNull(ColumnNames.Salary) ? string.Empty : base.GetdecimalAsString(ColumnNames.Salary);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Salary);
else
this.Salary = base.SetdecimalAsString(ColumnNames.Salary, value);
}
}
public virtual string s_IsActive
{
get
{
return this.IsColumnNull(ColumnNames.IsActive) ? string.Empty : base.GetboolAsString(ColumnNames.IsActive);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.IsActive);
else
this.IsActive = base.SetboolAsString(ColumnNames.IsActive, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region WhereParameter TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter ID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ID, Parameters.ID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter DepartmentID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter FirstName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.FirstName, Parameters.FirstName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter LastName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.LastName, Parameters.LastName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Age
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Age, Parameters.Age);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter HireDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Salary
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter IsActive
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter ID
{
get
{
if(_ID_W == null)
{
_ID_W = TearOff.ID;
}
return _ID_W;
}
}
public WhereParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public WhereParameter FirstName
{
get
{
if(_FirstName_W == null)
{
_FirstName_W = TearOff.FirstName;
}
return _FirstName_W;
}
}
public WhereParameter LastName
{
get
{
if(_LastName_W == null)
{
_LastName_W = TearOff.LastName;
}
return _LastName_W;
}
}
public WhereParameter Age
{
get
{
if(_Age_W == null)
{
_Age_W = TearOff.Age;
}
return _Age_W;
}
}
public WhereParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public WhereParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public WhereParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private WhereParameter _ID_W = null;
private WhereParameter _DepartmentID_W = null;
private WhereParameter _FirstName_W = null;
private WhereParameter _LastName_W = null;
private WhereParameter _Age_W = null;
private WhereParameter _HireDate_W = null;
private WhereParameter _Salary_W = null;
private WhereParameter _IsActive_W = null;
public void WhereClauseReset()
{
_ID_W = null;
_DepartmentID_W = null;
_FirstName_W = null;
_LastName_W = null;
_Age_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
#region Aggregate Clause
public class AggregateClause
{
public AggregateClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffAggregateParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffAggregateParameter(this);
}
return _tearOff;
}
}
#region AggregateParameter TearOff's
public class TearOffAggregateParameter
{
public TearOffAggregateParameter(AggregateClause clause)
{
this._clause = clause;
}
public AggregateParameter ID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.ID, Parameters.ID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter DepartmentID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter FirstName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.FirstName, Parameters.FirstName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter LastName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.LastName, Parameters.LastName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Age
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Age, Parameters.Age);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter HireDate
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Salary
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter IsActive
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
private AggregateClause _clause;
}
#endregion
public AggregateParameter ID
{
get
{
if(_ID_W == null)
{
_ID_W = TearOff.ID;
}
return _ID_W;
}
}
public AggregateParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public AggregateParameter FirstName
{
get
{
if(_FirstName_W == null)
{
_FirstName_W = TearOff.FirstName;
}
return _FirstName_W;
}
}
public AggregateParameter LastName
{
get
{
if(_LastName_W == null)
{
_LastName_W = TearOff.LastName;
}
return _LastName_W;
}
}
public AggregateParameter Age
{
get
{
if(_Age_W == null)
{
_Age_W = TearOff.Age;
}
return _Age_W;
}
}
public AggregateParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public AggregateParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public AggregateParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private AggregateParameter _ID_W = null;
private AggregateParameter _DepartmentID_W = null;
private AggregateParameter _FirstName_W = null;
private AggregateParameter _LastName_W = null;
private AggregateParameter _Age_W = null;
private AggregateParameter _HireDate_W = null;
private AggregateParameter _Salary_W = null;
private AggregateParameter _IsActive_W = null;
public void AggregateClauseReset()
{
_ID_W = null;
_DepartmentID_W = null;
_FirstName_W = null;
_LastName_W = null;
_Age_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushAggregateParameters();
}
private BusinessEntity _entity;
private TearOffAggregateParameter _tearOff;
}
public AggregateClause Aggregate
{
get
{
if(_aggregateClause == null)
{
_aggregateClause = new AggregateClause(this);
}
return _aggregateClause;
}
}
private AggregateClause _aggregateClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
VistaDBCommand cmd = new VistaDBCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"INSERT INTO [AggregateTest]
(
[DepartmentID],
[FirstName],
[LastName],
[Age],
[HireDate],
[Salary],
[IsActive]
)
VALUES
(
@DepartmentID,
@FirstName,
@LastName,
@Age,
@HireDate,
@Salary,
@IsActive
)";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetUpdateCommand()
{
VistaDBCommand cmd = new VistaDBCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"UPDATE [AggregateTest] SET
[DepartmentID]=@DepartmentID,
[FirstName]=@FirstName,
[LastName]=@LastName,
[Age]=@Age,
[HireDate]=@HireDate,
[Salary]=@Salary,
[IsActive]=@IsActive
WHERE
[ID]=@ID";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetDeleteCommand()
{
VistaDBCommand cmd = new VistaDBCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"DELETE FROM [AggregateTest]
WHERE
[ID]=@ID";
VistaDBParameter p;
p = cmd.Parameters.Add(Parameters.ID);
p.SourceColumn = ColumnNames.ID;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
private IDbCommand CreateParameters(VistaDBCommand cmd)
{
VistaDBParameter p;
p = cmd.Parameters.Add(Parameters.ID);
p.SourceColumn = ColumnNames.ID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.DepartmentID);
p.SourceColumn = ColumnNames.DepartmentID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.FirstName);
p.SourceColumn = ColumnNames.FirstName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.LastName);
p.SourceColumn = ColumnNames.LastName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.Age);
p.SourceColumn = ColumnNames.Age;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.HireDate);
p.SourceColumn = ColumnNames.HireDate;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.Salary);
p.SourceColumn = ColumnNames.Salary;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.IsActive);
p.SourceColumn = ColumnNames.IsActive;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
using OmniSharp.Models.FindImplementations;
using OmniSharp.Roslyn.CSharp.Services.Navigation;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class FindImplementationFacts : AbstractSingleRequestHandlerTestFixture<FindImplementationsService>
{
public FindImplementationFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.FindImplementations;
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindInterfaceTypeImplementation(string filename)
{
const string code = @"
public interface Som$$eInterface {}
public class SomeClass : SomeInterface {}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeClass", implementation.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindInterfaceMethodImplementation(string filename)
{
const string code = @"
public interface SomeInterface { void Some$$Method(); }
public class SomeClass : SomeInterface {
public void SomeMethod() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeMethod", implementation.Name);
Assert.Equal("SomeClass", implementation.ContainingType.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindInterfaceMethodOverride(string filename)
{
const string code = @"
public interface SomeInterface { void Some$$Method(); }
public class SomeClass : SomeInterface {
public virtual void SomeMethod() {}
}
public class SomeChildClass : SomeClass {
public override void SomeMethod() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
Assert.Equal(2, implementations.Count());
Assert.True(implementations.Any(x => x.ContainingType.Name == "SomeClass" && x.Name == "SomeMethod"), "Couldn't find SomeClass.SomeMethod in the discovered implementations");
Assert.True(implementations.Any(x => x.ContainingType.Name == "SomeChildClass" && x.Name == "SomeMethod"), "Couldn't find SomeChildClass.SomeMethod in the discovered implementations");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindOverride(string filename)
{
const string code = @"
public abstract class BaseClass { public abstract void Some$$Method(); }
public class SomeClass : BaseClass
{
public override void SomeMethod() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeMethod", implementation.Name);
Assert.Equal("SomeClass", implementation.ContainingType.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindSubclass(string filename)
{
const string code = @"
public abstract class BaseClass {}
public class SomeClass : Base$$Class {}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeClass", implementation.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindTypeDeclaration(string filename)
{
const string code = @"
public class MyClass
{
public MyClass() { var other = new Other$$Class(); }
}
public class OtherClass
{
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("OtherClass", implementation.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindMethodDeclaration(string filename)
{
const string code = @"
public class MyClass
{
public MyClass() { Fo$$o(); }
public void Foo() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("Foo", implementation.Name);
Assert.Equal("MyClass", implementation.ContainingType.Name);
Assert.Equal(SymbolKind.Method, implementation.Kind);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindPartialClass(string filename)
{
const string code = @"
public partial class Some$$Class { void SomeMethod() {} }
public partial class SomeClass { void AnotherMethod() {} }";
var implementations = await FindImplementationsAsync(code, filename);
Assert.Equal(2, implementations.Count());
Assert.True(implementations.All(x => x.Name == "SomeClass"));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindPartialMethod(string filename)
{
const string code = @"
public partial class SomeClass { partial void Some$$Method(); }
public partial class SomeClass { partial void SomeMethod() { /* this is implementation of the partial method */ } }";
var implementations = await FindImplementationsAsync(code, filename);
Assert.Single(implementations);
var implementation = implementations.First();
Assert.Equal("SomeMethod", implementation.Name);
// Assert that the actual implementation part is returned.
Assert.True(implementation is IMethodSymbol method && method.PartialDefinitionPart != null && method.PartialImplementationPart == null);
}
private async Task<IEnumerable<ISymbol>> FindImplementationsAsync(string code, string filename)
{
var testFile = new TestFile(filename, code);
SharedOmniSharpTestHost.AddFilesToWorkspace(testFile);
var point = testFile.Content.GetPointFromPosition();
var requestHandler = GetRequestHandler(SharedOmniSharpTestHost);
var request = new FindImplementationsRequest
{
Line = point.Line,
Column = point.Offset,
FileName = testFile.FileName,
Buffer = testFile.Content.Code
};
var implementations = await requestHandler.Handle(request);
return await SymbolsFromQuickFixesAsync(SharedOmniSharpTestHost.Workspace, implementations.QuickFixes);
}
private async Task<IEnumerable<ISymbol>> SymbolsFromQuickFixesAsync(OmniSharpWorkspace workspace, IEnumerable<QuickFix> quickFixes)
{
var symbols = new List<ISymbol>();
foreach (var quickfix in quickFixes)
{
var document = workspace.GetDocument(quickfix.FileName);
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(quickfix.Line, quickfix.Column));
var semanticModel = await document.GetSemanticModelAsync();
var symbol = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace);
symbols.Add(symbol);
}
return symbols;
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using Weborb.Config;
using Weborb.Types;
using Weborb.Util.Logging;
namespace Weborb.Util
{
public class ObjectFactories
{
private Dictionary<String, IServiceObjectFactory> serviceObjectFactories = new Dictionary<String, IServiceObjectFactory>();
private Dictionary<String, IArgumentObjectFactory> argumentObjectFactories = new Dictionary<String, IArgumentObjectFactory>();
#if (FULL_BUILD)
public static Object GetObjectOfType( String basePath, Type baseType )
{
AppDomain domain = AppDomain.CurrentDomain;
String path;
try
{
if( basePath == null )
basePath = domain.BaseDirectory;
path = Path.Combine( basePath, "bin" );
DirectoryInfo assemlyDirectory = new DirectoryInfo( path );
if( !assemlyDirectory.Exists )
assemlyDirectory = new DirectoryInfo( basePath );
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "loading asseblies from " + assemlyDirectory.ToString() );
FileInfo[] files = assemlyDirectory.GetFiles( "*.dll" );
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "got " + files.Length + " assembly files" );
foreach( FileInfo file in files )
{
String assemblyName = file.Name.Substring( 0, file.Name.ToLower().IndexOf( ".dll" ) );
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "loading assembly " + assemblyName );
try
{
AssemblyName assemblyNameObj = AssemblyName.GetAssemblyName( file.FullName );
Assembly assembly = domain.Load( assemblyNameObj );
Type[] types = assembly.GetTypes();
foreach( Type type in types )
if( baseType.IsAssignableFrom( type ) )
return CreateServiceObject( type );
}
catch( Exception exception )
{
Log.log( LoggingConstants.ERROR, "could not load assembly - " + assemblyName, exception );
}
}
}
catch( Exception exception )
{
Log.log( LoggingConstants.ERROR, "could not load assembly", exception );
}
return null;
}
#endif
public static object CreateServiceObject( String className )
{
//return ThreadContext.getORBConfig().getObjectFactories()._CreateServiceObject( className );
return ORBConfig.GetInstance().getObjectFactories()._CreateServiceObject( className );
}
public object _CreateServiceObject( String className )
{
IServiceObjectFactory factory;
serviceObjectFactories.TryGetValue( className, out factory );
if( factory == null )
{
//Type type = Type.GetType( className );
Type type = TypeLoader.LoadType( className );
if( type == null )
throw new Exception( String.Format( "Unable to find type {0}", className ) );
try
{
return Activator.CreateInstance( type );
}
catch( TargetInvocationException exception )
{
if( Log.isLogging( LoggingConstants.EXCEPTION ) )
Log.log( LoggingConstants.EXCEPTION, "Unable to create object instance", exception.InnerException );
throw exception.InnerException;
}
}
else
{
return factory.createObject();
}
}
public static object CreateServiceObject( Type type )
{
//return ThreadContext.getORBConfig().getObjectFactories()._CreateServiceObject( type );
return ORBConfig.GetInstance().getObjectFactories()._CreateServiceObject( type );
}
public object _CreateServiceObject( Type type )
{
bool logDebug = Log.isLogging( LoggingConstants.DEBUG );
if( logDebug )
Log.log( LoggingConstants.DEBUG, "looking up service factory for " + type.FullName );
IServiceObjectFactory factory;
serviceObjectFactories.TryGetValue( type.FullName, out factory );
if( factory == null )
{
if( logDebug )
Log.log( LoggingConstants.DEBUG, "factory is null" );
if( type.IsInterface || type.IsAbstract )
{
if( logDebug )
Log.log( LoggingConstants.DEBUG, "type is an interface or abstract/static" );
Type mappedType = Weborb.Types.Types.GetAbstractClassMapping( type );
if( mappedType == null )
throw new Exception( "unable to create an instance of abstract class/interface. Abstract/Interface class mapping is missing for type " + type.FullName );
else
type = mappedType;
}
return Activator.CreateInstance( type );
}
else
{
if( logDebug )
Log.log( LoggingConstants.DEBUG, "factory is " + factory.GetType().FullName );
return factory.createObject();
}
}
public static object CreateArgumentObject( Type type, IAdaptingType argument )
{
return ORBConfig.GetInstance().getObjectFactories()._CreateArgumentObject( type, argument );
}
public static object CreateArgumentObject( String typeName, IAdaptingType argument )
{
Type type = TypeLoader.LoadType( typeName );
return ORBConfig.GetInstance().getObjectFactories()._CreateArgumentObject( type, argument );
}
public object _CreateArgumentObject( Type type, IAdaptingType argument )
{
String typeName = type.FullName;
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "checking argument factory for " + typeName );
if( !argumentObjectFactories.ContainsKey( typeName ) )
{
/*
if( type.IsInterface || type.IsAbstract )
{
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "type is an interface or abstract/static" );
Type mappedType = Weborb.Types.Types.GetAbstractClassMapping( type );
if( mappedType != null )
return ObjectFactories.CreateServiceObject( mappedType );
}*/
return null;
}
IArgumentObjectFactory objectFactory;
argumentObjectFactories.TryGetValue( typeName, out objectFactory );
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "will use argument factory " + objectFactory.ToString() );
return objectFactory.createObject( argument );
}
public void AddServiceObjectFactory( String typeName, IServiceObjectFactory objectFactory )
{
serviceObjectFactories[ typeName ] = objectFactory;
}
public void AddArgumentObjectFactory( String typeName, IArgumentObjectFactory objectFactory )
{
argumentObjectFactories[ typeName ] = objectFactory;
}
public static String[] GetMappedServiceClasses()
{
//return ThreadContext.getORBConfig().getObjectFactories()._GetMappedServiceClasses();
return ORBConfig.GetInstance().getObjectFactories()._GetMappedServiceClasses();
}
public String[] _GetMappedServiceClasses()
{
List<String> serviceTypes = new List<String>();
foreach( String typeName in serviceObjectFactories.Keys )
serviceTypes.Add( typeName );
return serviceTypes.ToArray();
}
public static IServiceObjectFactory GetServiceObjectFactory( String serviceTypeName )
{
//return ThreadContext.getORBConfig().getObjectFactories()._GetServiceObjectFactory( serviceTypeName );
return ORBConfig.GetInstance().getObjectFactories()._GetServiceObjectFactory( serviceTypeName );
}
public IServiceObjectFactory _GetServiceObjectFactory( String serviceTypeName )
{
IServiceObjectFactory factory;
serviceObjectFactories.TryGetValue( serviceTypeName, out factory );
return factory;
}
public void RemoveServiceFactoryFor( String serviceTypeName )
{
serviceObjectFactories.Remove( serviceTypeName );
}
public static String[] GetMappedArgumentClasses()
{
//return ThreadContext.getORBConfig().getObjectFactories()._GetMappedArgumentClasses();
return ORBConfig.GetInstance().getObjectFactories()._GetMappedArgumentClasses();
}
public String[] _GetMappedArgumentClasses()
{
List<String> argumentTypes = new List<String>();
foreach( String typeName in argumentObjectFactories.Keys )
argumentTypes.Add( typeName );
return argumentTypes.ToArray();
}
public static IArgumentObjectFactory GetArgumentObjectFactory( String argumentTypeName )
{
//return ThreadContext.getORBConfig().getObjectFactories()._GetArgumentObjectFactory( argumentTypeName );
return ORBConfig.GetInstance().getObjectFactories()._GetArgumentObjectFactory( argumentTypeName );
}
public IArgumentObjectFactory _GetArgumentObjectFactory( String argumentTypeName )
{
IArgumentObjectFactory factory;
argumentObjectFactories.TryGetValue( argumentTypeName, out factory );
return factory;
}
public void RemoveArgumentFactoryFor( String argumentTypeName )
{
argumentObjectFactories.Remove( argumentTypeName );
}
}
}
| |
// 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: Platform independent integer
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
using System.Diagnostics.Contracts;
[Serializable]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
[SecurityCritical]
unsafe private void* m_value;
public static readonly UIntPtr Zero;
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(uint value)
{
m_value = (void *)value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
m_value = (void *)value;
#else // 32
m_value = (void*)checked((uint)value);
#endif
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(void* value)
{
m_value = value;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe UIntPtr(SerializationInfo info, StreamingContext context) {
ulong l = info.GetUInt64("value");
if (Size==4 && l>UInt32.MaxValue) {
throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue"));
}
m_value = (void *)l;
}
[System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
info.AddValue("value", (ulong)m_value);
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override bool Equals(Object obj) {
if (obj is UIntPtr) {
return (m_value == ((UIntPtr)obj).m_value);
}
return false;
}
[SecuritySafeCritical]
unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr other)
{
return m_value == other.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
#if FEATURE_CORECLR
#if BIT64
ulong l = (ulong)m_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // 32
return unchecked((int)m_value);
#endif
#else
return unchecked((int)((long)m_value)) & 0x7fffffff;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe uint ToUInt32() {
#if BIT64
return checked((uint)m_value);
#else // 32
return (uint)m_value;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe ulong ToUInt64() {
return (ulong)m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
return ((ulong)m_value).ToString(CultureInfo.InvariantCulture);
#else // 32
return ((uint)m_value).ToString(CultureInfo.InvariantCulture);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator UIntPtr (uint value)
{
return new UIntPtr(value);
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator UIntPtr (ulong value)
{
return new UIntPtr(value);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator uint(UIntPtr value)
{
#if BIT64
return checked((uint)value.m_value);
#else // 32
return (uint)value.m_value;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value.m_value;
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator UIntPtr (void* value)
{
return new UIntPtr(value);
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator == (UIntPtr value1, UIntPtr value2)
{
return value1.m_value == value2.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator != (UIntPtr value1, UIntPtr value2)
{
return value1.m_value != value2.m_value;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset) {
return pointer + offset;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset) {
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else // 32
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset) {
return pointer - offset;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset) {
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else // 32
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
public static int Size
{
[System.Runtime.Versioning.NonVersionable]
get
{
#if BIT64
return 8;
#else // 32
return 4;
#endif
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
return m_value;
}
}
}
| |
//
// 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 NLog.Internal.Pooling.Pools;
namespace NLog
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using NLog.Time;
using Internal.Pooling;
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
private static int globalSequenceId;
private readonly object layoutCacheLock = new object();
private string formattedMessage;
private string message;
private object[] parameters;
private IFormatProvider formatProvider;
private IDictionary<Layout, string> layoutCache;
private IDictionary<object, object> properties;
private IDictionary eventContextAdapter;
private LogEventInfoPool pool;
internal LogEventInfo(LogEventInfoPool pool) : this()
{
this.pool = pool;
this.CreatePutbackDelegate();
}
private void CreatePutbackDelegate()
{
if (this.PutBackDelegate != null)
{
return;
}
this.PutBackDelegate = ex =>
{
try
{
if (ex != null)
{
if (ex.MustBeRethrown())
{
throw ex;
}
}
}
finally
{
this.PutBack();
}
};
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
Init();
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception): this()
{
this.Level = level;
this.LoggerName = loggerName;
this.Message = message;
this.Parameters = parameters;
this.FormatProvider = formatProvider;
this.Exception = exception;
if (NeedToPreformatMessage(parameters))
{
this.CalcFormattedMessage();
}
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")]
public int SequenceID { get; private set; }
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace
{
get { return this.StackTrace != null; }
}
/// <summary>
/// Gets the stack frame of the method that did the logging.
/// </summary>
public StackFrame UserStackFrame
{
get { return (this.StackTrace != null) ? this.StackTrace.GetFrame(this.UserStackFrameNumber) : null; }
}
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber { get; private set; }
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace { get; private set; }
/// <summary>
/// Gets or sets the exception information.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
public string LoggerName { get; set; }
/// <summary>
/// Gets the logger short name.
/// </summary>
[Obsolete("This property should not be used.")]
public string LoggerShortName
{
get
{
int lastDot = this.LoggerName.LastIndexOf('.');
if (lastDot >= 0)
{
return this.LoggerName.Substring(lastDot + 1);
}
return this.LoggerName;
}
}
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message
{
get { return message; }
set
{
message = value;
ResetFormattedMessage();
}
}
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")]
public object[] Parameters
{
get { return parameters; }
set
{
parameters = value;
ResetFormattedMessage();
}
}
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider
{
get { return formatProvider; }
set
{
if (formatProvider != value)
{
formatProvider = value;
ResetFormattedMessage();
}
}
}
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (this.formattedMessage == null)
{
this.CalcFormattedMessage();
}
return this.formattedMessage;
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties
{
get
{
if (this.properties == null)
{
this.InitEventContext();
}
return this.properties;
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
[Obsolete("Use LogEventInfo.Properties instead.", true)]
public IDictionary Context
{
get
{
if (this.eventContextAdapter == null)
{
this.InitEventContext();
}
return this.eventContextAdapter;
}
}
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return Create(LogLevel.Off, string.Empty, string.Empty);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return Create(logLevel, loggerName, null, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
return Create(logLevel, loggerName, null, formatProvider,"{0}", new[] { message });
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
[Obsolete("use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message)")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception)
{
return Create(logLevel, loggerName, exception, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message)
{
return Create(logLevel, loggerName, exception, formatProvider, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return "Log Event: Logger='" + this.LoggerName + "' Level=" + this.Level + " Message='" + this.FormattedMessage + "' SequenceID=" + this.SequenceID;
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
this.StackTrace = stackTrace;
this.UserStackFrameNumber = userStackFrame;
}
internal string AddCachedLayoutValue(Layout layout, string value)
{
lock (this.layoutCacheLock)
{
if (this.layoutCache == null)
{
this.layoutCache = new Dictionary<Layout, string>();
}
this.layoutCache[layout] = value;
}
return value;
}
internal bool TryGetCachedLayoutValue(Layout layout, out string value)
{
lock (this.layoutCacheLock)
{
if (this.layoutCache == null)
{
value = null;
return false;
}
return this.layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters == null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 3)
{
// too many parameters, too costly to check
return true;
}
if (!IsSafeToDeferFormatting(parameters[0]))
{
return true;
}
if (parameters.Length >= 2)
{
if (!IsSafeToDeferFormatting(parameters[1]))
{
return true;
}
}
if (parameters.Length >= 3)
{
if (!IsSafeToDeferFormatting(parameters[2]))
{
return true;
}
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
if (value == null)
{
return true;
}
return value.GetType().IsPrimitive || (value is string);
}
internal void CalcFormattedMessageIfNeeded()
{
if (NeedToPreformatMessage(this.Parameters))
{
this.CalcFormattedMessage();
}
}
private void CalcFormattedMessage()
{
if (this.Parameters == null || this.Parameters.Length == 0)
{
this.formattedMessage = this.Message;
}
else
{
try
{
this.formattedMessage = string.Format(this.FormatProvider ?? CultureInfo.CurrentCulture, this.Message, this.Parameters);
}
catch (Exception exception)
{
this.formattedMessage = this.Message;
InternalLogger.Warn(exception, "Error when formatting a message.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
private void ResetFormattedMessage()
{
this.formattedMessage = null;
}
private void InitEventContext()
{
this.properties = new Dictionary<object, object>();
this.eventContextAdapter = new DictionaryAdapter<object, object>(this.properties);
}
/// <summary>
/// Clears the log event info for reuse purposes
/// </summary>
internal void Clear()
{
this.properties = null;
this.eventContextAdapter = null;
this.parameters=null;
this.formatProvider=null;
if (this.layoutCache != null)
{
// just reset, so we dont have to allocate another dictionary
this.layoutCache.Clear();
}
this.Exception = null;
this.formattedMessage = null;
this.Level = null;
this.LoggerName = null;
this.message = null;
this.SequenceID = 0;
this.StackTrace = null;
this.TimeStamp = default(DateTime);
this.UserStackFrameNumber = 0;
}
internal void Init()
{
this.TimeStamp = TimeSource.Current.Time;
this.SequenceID = Interlocked.Increment(ref globalSequenceId);
this.CreatePutbackDelegate();
}
internal void SetPool(LogEventInfoPool pool)
{
this.pool = pool;
}
internal void PutBack()
{
try
{
//InternalLogger.Trace(" - trying to put pooled LogEventInfo back into the pool");
var infoPool = Interlocked.Exchange(ref this.pool, null);
if (infoPool != null)
{
infoPool.PutBack(this);
}
else
{
InternalLogger.Trace("No pool available for LogEventInfo to be put back to");
}
}
catch (Exception e)
{
InternalLogger.Error(" - Error occured while putting back log event into the pool:{0}", e);
}
}
internal AsyncContinuation PutBackDelegate;
// Remember to update this when adding new properties that is required for message rendering in layouts or rendererer
// TODO: create a test that assign values to all properties and clone it.
internal LogEventInfo Clone()
{
LogEventInfo info;
if (this.pool != null)
{
info = this.pool.Get(
this.Level,
this.LoggerName,
this.FormatProvider,
this.message,
this.parameters,
this.Exception);
}
else
{
info = new LogEventInfo(
this.Level,
this.LoggerName,
this.FormatProvider,
this.message,
this.parameters,
this.Exception);
}
foreach (var key in this.Properties.Keys)
{
info.Properties[key] = this.Properties[key];
}
info.StackTrace = this.StackTrace;
info.SequenceID = this.SequenceID;
info.TimeStamp = this.TimeStamp;
info.UserStackFrameNumber = this.UserStackFrameNumber;
info.CalcFormattedMessageIfNeeded();
return info;
}
/// <summary>
/// Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
/// </summary>
~LogEventInfo()
{
#if !SILVERLIGHT
if (!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
if (InternalLogger.IsTraceEnabled)
{
if (this.pool != null)
{
InternalLogger.Trace(string.Format("Pooled LogEventInfo with SequenceID:{0} was collected by garbage collector even if not shutting down",this.SequenceID));
}
}
}
#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 Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class GetStrTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
[ActiveIssue(2769, PlatformID.AnyUnix)]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] Get(int) on empty collection
//
if (nvc.Get(null) != null)
{
Assert.False(true, "Error, returned non-null");
}
if (nvc.Get("some_string") != null)
{
Assert.False(true, "Error, returned non-null");
}
// [] Get(int) on collection filled with simple strings
//
cnt = nvc.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
//
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc.Get(keys[i]), values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc.Get(keys[i]), values[i]));
}
}
//
// Intl strings
// [] Get(int) on collection filled with Intl strings
//
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]);
}
if (nvc.Count != (len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
}
for (int i = 0; i < len; i++)
{
//
if (String.Compare(nvc.Get(intlValues[i + len]), intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(intlValues[i + len]), intlValues[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
if (String.Compare(nvc.Get(intlValues[i + len]), intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(intlValues[i + len]), intlValues[i]));
}
// lowercase key
if (String.Compare(nvc.Get(intlValuesLower[i + len]), intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(intlValuesLower[i + len]), intlValues[i]));
}
if (!caseInsensitive && String.Compare(nvc.Get(intlValues[i + len]), intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
}
}
// [] Get(int) on filled collection - with multiple items with the same keys
//
nvc.Clear();
len = values.Length;
string k = "keykey";
string k1 = "hm1";
string exp = "";
string exp1 = "";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
nvc.Add(k1, "iTem" + i);
if (i < len - 1)
{
exp += "Value" + i + ",";
exp1 += "iTem" + i + ",";
}
else
{
exp += "Value" + i;
exp1 += "iTem" + i;
}
}
if (nvc.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
}
if (String.Compare(nvc.Get(k), exp) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(k), exp));
}
if (String.Compare(nvc.Get(k1), exp1) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(k1), exp1));
}
//
// [] Get(-1)
//
cnt = nvc.Count;
nvc.Add(null, "nullValue");
if (String.Compare(nvc.Get(null), "nullValue") != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(null), "nullValue"));
}
//
// [] Get(null) - when no item with null key
//
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
string res = nvc.Get(null);
if (res != null)
{
Assert.False(true, "Error, returned non-null ");
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Text;
using rho.protocol.shared;
using rho.collections;
using ZSDK_API.ApiException;
using ZSDK_API.Comm;
using ZSDK_API.Printer;
using Newtonsoft.Json;
using PrintingService;
namespace rho
{
namespace PrinterZebraImpl
{
public class PrinterZebra
{
public enum EPrinterConnectionType
{
eBluetooth,
eTCP,
eUSB,
eOnBoard,
}
private ZebraPrinterConnection m_connection = null;
private ZebraPrinter m_printer = null;
private int m_maxTimeoutForRead = 0;
private int m_timeToWaitForMoreData = 0;
public string ID { get; set; }
public Int32 Port { get; set; }
public EPrinterConnectionType connectionType { get; set; }
public MainForm applicationForm { get; set; }
private PrinterStatus getStatus()
{
object[] args = new object[] { connectionType, ID, Port };
object result = applicationForm.Invoke(new PrintingService.MainForm.GetPrinterStatusCallback(applicationForm.getPrinterStatus), args);
return (PrinterStatus)result;
}
/// common functionality
public void connect(IMethodResult oResult)
{
Logger.Write("connect call");
IReadOnlyDictionary<string, string> options = new IReadOnlyDictionary<string, string>();
connectWithOptions(options, oResult);
}
public void connectWithOptions(IReadOnlyDictionary<string, string> options, IMethodResult oResult)
{
Logger.Write("connectWithOptions call");
Logger.Write("options:", options);
string valueObj = null;
Int32 connectionTimeout = 0;
if (m_connection != null && m_connection.IsConnected() && m_printer != null)
{
m_connection.Close();
Thread.Sleep(1000);
m_connection = null;
m_printer = null;
}
if (options.ContainsKey(ZebraConstants.HK_TIMEOUT))
{
valueObj = options[ZebraConstants.HK_TIMEOUT];
if ((valueObj != null) && (valueObj is String))
{
try
{
connectionTimeout = Int32.Parse(valueObj.ToString());
}
catch (System.FormatException)
{
m_maxTimeoutForRead = 0;
}
}
}
if (options.ContainsKey(ZebraConstants.PROPERTY_MAX_TIMEOUT_FOR_READ))
{
valueObj = options[ZebraConstants.PROPERTY_MAX_TIMEOUT_FOR_READ];
if ((valueObj != null) && (valueObj is String))
{
try
{
m_maxTimeoutForRead = Int32.Parse(valueObj.ToString());
}
catch (System.FormatException)
{
m_maxTimeoutForRead = 0;
}
}
}
if (options.ContainsKey(ZebraConstants.PROPERTY_TIME_TO_WAIT_FOR_MORE_DATA))
{
valueObj = options[ZebraConstants.PROPERTY_TIME_TO_WAIT_FOR_MORE_DATA];
if ((valueObj != null) && (valueObj is String))
{
try
{
m_timeToWaitForMoreData = Int32.Parse(valueObj.ToString());
}
catch (System.FormatException)
{
m_maxTimeoutForRead = 0;
}
}
}
ConnecttionJob job = new ConnecttionJob();
job.Address = ID;
job.Port = Port;
job.ConnectionType = connectionType;
job.MaxTimeoutForRead = m_maxTimeoutForRead;
job.TimeToWaitForMoreData = m_timeToWaitForMoreData;
if (connectionTimeout == 0)
{
job.Connect();
}
else
{
if (!job.Connect(connectionTimeout))
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_TIMEOUT);
return;
}
}
if (job.Connection != null && job.Printer != null)
{
m_connection = job.Connection;
m_printer = job.Printer;
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
}
public void disconnect(IMethodResult oResult)
{
Logger.Write("disconnect call");
if (m_connection != null && m_connection.IsConnected())
{
Thread.Sleep(1000);
m_connection.Close();
Thread.Sleep(1000);
}
m_connection = null;
m_printer = null;
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
}
public void getIsConnected(IMethodResult oResult)
{
Logger.Write("getIsConnected call");
if (m_connection != null)
{
oResult.set(m_connection.IsConnected());
}
else
{
oResult.set(false);
}
}
public void printFile(string fileURI, IReadOnlyDictionary<string, string> options, IMethodResult oResult)
{
Logger.Write("printFile call");
Logger.Write("fileURI: " + fileURI);
Logger.Write("options:", options);
if (m_connection != null && m_printer != null)
{
try
{
if (Path.GetExtension(fileURI) == ".jpg" || Path.GetExtension(fileURI) == ".png")
{
m_printer.GetGraphicsUtil().PrintImage(fileURI, 0, 0);
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
}
catch (Exception ex)
{
}
}
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
}
public void printRawString(string command, IReadOnlyDictionary<string, string> options, IMethodResult oResult)
{
Logger.Write("printRawString call: " + command);
Logger.Write("command: " + command);
Logger.Write("options:", options);
if (m_connection != null && m_printer != null)
{
try
{
byte[] commandStr = Encoding.UTF8.GetBytes(command);
m_connection.Write(commandStr);
Thread.Sleep(500);
byte[] printerResponse = m_connection.Read();
string printerResponseStr = Encoding.UTF8.GetString(printerResponse, 0, printerResponse.Length);
IReadOnlyDictionary<string, string> response = new IReadOnlyDictionary<string, string>();
response.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_SUCCESS);
response.Add(ZebraConstants.HK_STRING_RESPONCE, printerResponseStr);
oResult.set(response);
}
catch (Exception ex)
{
IReadOnlyDictionary<string, string> errResponse = new IReadOnlyDictionary<string, string>();
errResponse.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_ERROR);
errResponse.Add(ZebraConstants.HK_MESSAGE, ex.Message.ToString());
oResult.set(errResponse);
}
}
else
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
}
}
public void getDeviceName(IMethodResult oResult)
{
Logger.Write("getDeviceName call");
if (m_connection != null && m_connection is BluetoothPrinterConnection)
{
BluetoothPrinterConnection conn = (BluetoothPrinterConnection)m_connection;
oResult.set(conn.GetFriendlyName());
}
}
public void enumerateSupportedControlLanguages(IMethodResult oResult)
{
Logger.Write("enumerateSupportedControlLanguages call");
if (m_printer != null)
{
IReadOnlyDictionary<string, string> controlLanguage = new IReadOnlyDictionary<string, string>();
switch (m_printer.GetPrinterControlLanguage())
{
case PrinterLanguage.CPCL:
controlLanguage.Add(ZebraConstants.PRINTER_LANGUAGE_CPCL, "");
break;
case PrinterLanguage.ZPL:
controlLanguage.Add(ZebraConstants.PRINTER_LANGUAGE_ZPL, "");
controlLanguage.Add(ZebraConstants.PRINTER_LANGUAGE_CPCL, "");
break;
}
oResult.set(controlLanguage);
return;
}
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
}
public void printImageFromFile(string path, int x, int y, IReadOnlyDictionary<string, string> options, IMethodResult oResult)
{
Logger.Write("printImageFromFile call");
Logger.Write("path: " + path);
Logger.Write("x: " + x);
Logger.Write("y: " + y);
Logger.Write("options:", options);
object valueObj = null;
int imgWitdh = -1;
int imgHeight = -1;
bool insideFormat = false;
if (m_connection != null && m_connection.IsConnected() && m_printer != null)
{
if (options.ContainsKey(ZebraConstants.HK_WIDTH))
{
valueObj = options[ZebraConstants.HK_WIDTH];
if ((valueObj != null) && (valueObj is String))
{
try
{
imgWitdh = Int32.Parse(valueObj.ToString());
}
catch (System.FormatException)
{
}
}
}
if (options.ContainsKey(ZebraConstants.HK_HEIGHT))
{
valueObj = options[ZebraConstants.HK_HEIGHT];
if ((valueObj != null) && (valueObj is String))
{
try
{
imgHeight = Int32.Parse(valueObj.ToString());
}
catch (System.FormatException)
{
}
}
}
if (options.ContainsKey(ZebraConstants.HK_IS_INSIDE_FORMAT))
{
valueObj = options[ZebraConstants.HK_IS_INSIDE_FORMAT];
if ((valueObj != null) && (valueObj is String))
{
try
{
insideFormat = Boolean.Parse(valueObj.ToString());
}
catch(System.FormatException)
{
}
}
}
if (Path.GetExtension(path) == ".jpg" || Path.GetExtension(path) == ".png")
{
if (imgHeight == -1 && imgWitdh == -1)
{
m_printer.GetGraphicsUtil().PrintImage(path, x, y);
Logger.Write("printImageFromFile call PRINTER_STATUS_SUCCESS");
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
else if (imgHeight != 0 && imgWitdh != 0)
{
m_printer.GetGraphicsUtil().PrintImage(path, x, y, imgWitdh, imgHeight, insideFormat);
Logger.Write("printImageFromFile call PRINTER_STATUS_SUCCESS");
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
}
}
else
{
Logger.Write("printImageFromFile call PRINTER_STATUS_ERR_NOT_CONNECTED");
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
return;
}
Logger.Write("printImageFromFile call PRINTER_STATUS_ERROR");
oResult.set(ZebraConstants.PRINTER_STATUS_ERROR);
}
public void sendFileContents(string filePath, IMethodResult oResult)
{
Logger.Write("sendFileContents call");
Logger.Write("fileParh: " + filePath);
if (m_connection != null && m_connection.IsConnected() && m_printer != null)
{
m_printer.GetFileUtil().SendFileContents(filePath);
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
}
else
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
}
}
public void retrieveFileNames(IMethodResult oResult)
{
Logger.Write("call retrieveFileNames ");
IReadOnlyDictionary<string, object> resultHash = new IReadOnlyDictionary<string, object>();
if (m_connection != null && m_connection.IsConnected())
{
RetriveParser parser = new RetriveParser(m_connection);
List<string> resultNames = parser.getAllFileNames();
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_SUCCESS);
resultHash.Add(ZebraConstants.HK_FILE_NAMES, resultNames);
oResult.set(resultHash);
return;
}
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_ERROR);
resultHash.Add(ZebraConstants.HK_FILE_NAMES, new List<string>());
oResult.set(resultHash);
}
public void retrieveFileNamesWithExtensions(IReadOnlyList<string> extensions, IMethodResult oResult)
{
Logger.Write("retrieveFileNamesWithExtensions call");
Logger.Write("extensions:", extensions);
IReadOnlyDictionary<string, object> resultHash = new IReadOnlyDictionary<string, object>();
if (m_printer != null)
{
RetriveParser parser = new RetriveParser(m_connection);
List<string> resultNames = parser.getAllFileNames(extensions);
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_SUCCESS);
resultHash.Add(ZebraConstants.HK_FILE_NAMES, resultNames);
oResult.set(resultHash);
return;
}
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_ERROR);
resultHash.Add(ZebraConstants.HK_FILE_NAMES, new List<string>());
oResult.set(resultHash);
}
public void printStoredFormatWithHash(string formatPathOnPrinter, IReadOnlyDictionary<string, string> vars, IMethodResult oResult)
{
Logger.Write("printStoredFormatWithHash call");
Logger.Write("formatPathOnPrinter: " + formatPathOnPrinter);
Logger.Write("vars: ", vars);
if (m_printer != null)
{
Dictionary<int, string> _params = new Dictionary<int, string>();
foreach (KeyValuePair<string, string> pair in vars)
{
try
{
_params.Add(Int32.Parse(pair.Key), pair.Value);
}
catch(Exception e)
{
}
}
m_printer.GetFormatUtil().PrintStoredFormat(formatPathOnPrinter, _params);
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
oResult.set(ZebraConstants.PRINTER_STATUS_ERROR);
}
public void printStoredFormatWithArray(string formatPathOnPrinter, IReadOnlyList<string> vars, IMethodResult oResult)
{
Logger.Write("printStoredFormatWithArray call");
Logger.Write("formatPathOnPrinter: " + formatPathOnPrinter);
Logger.Write("vars: ", vars);
if (m_printer != null)
{
m_printer.GetFormatUtil().PrintStoredFormat(formatPathOnPrinter, vars.ToArray());
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
oResult.set(ZebraConstants.PRINTER_STATUS_ERROR);
}
public void storeImage(string printerDriveAndFileName, string imageFilePathOnDevice, int width, int height, IMethodResult oResult)
{
Logger.Write("storeImage call");
Logger.Write("printerDriveAndFileName: " + printerDriveAndFileName);
Logger.Write("imageFilePathOnDevice: " + imageFilePathOnDevice);
Logger.Write("width: " + width.ToString());
Logger.Write("height: " + height.ToString());
try
{
if (m_printer != null && width != 0 && height != 0 &&
Path.GetExtension(imageFilePathOnDevice) != ".bmp" && Path.GetExtension(imageFilePathOnDevice) != ".gif")
{
m_printer.GetGraphicsUtil().StoreImage(printerDriveAndFileName, imageFilePathOnDevice, width, height);
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
return;
}
}
catch(ZebraPrinterConnectionException)
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_NETWORK);
return;
}
catch(ZebraIllegalArgumentException)
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_IO);
return;
}
catch(ArgumentException)
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERR_PARAM);
return;
}
catch (Exception)
{
oResult.set(ZebraConstants.PRINTER_STATUS_ERROR);
return;
}
oResult.set(ZebraConstants.PRINTER_STATUS_ERROR);
}
public void requestState(IReadOnlyList<string> listOfParameters, IMethodResult oResult)
{
Logger.Write("requestState call");
Logger.Write("listOfParameters:", listOfParameters);
IReadOnlyDictionary<string, object> resultHash = new IReadOnlyDictionary<string, object>();
if (m_connection != null && m_connection.IsConnected() && m_printer != null)
{
PrinterStatus currStatus = getStatus();
if (currStatus != null)
{
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_SUCCESS);
resultHash.Add(ZebraConstants.HK_MESSAGE, "");
foreach (string parameter in listOfParameters)
{
switch(parameter)
{
case ZebraConstants.PRINTER_STATE_IS_HEAD_COLD:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_HEAD_COLD, currStatus.IsHeadCold);
break;
case ZebraConstants.PRINTER_STATE_IS_HEAD_OPEN:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_HEAD_OPEN, currStatus.IsHeadOpen);
break;
case ZebraConstants.PRINTER_STATE_IS_HEAD_TOO_HOT:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_HEAD_TOO_HOT, currStatus.IsHeadTooHot);
break;
case ZebraConstants.PRINTER_STATE_IS_PAPER_OUT:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_PAPER_OUT, currStatus.IsPaperOut);
break;
case ZebraConstants.PRINTER_STATE_IS_PARTIAL_FORMAT_IN_PROGRESS:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_PARTIAL_FORMAT_IN_PROGRESS, currStatus.IsPartialFormatInProgress);
break;
case ZebraConstants.PRINTER_STATE_IS_PAUSED:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_BATTERY_LOW, currStatus.IsPaused);
break;
case ZebraConstants.PRINTER_STATE_IS_READY_TO_PRINT:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_READY_TO_PRINT, currStatus.IsReadyToPrint);
break;
case ZebraConstants.PRINTER_STATE_IS_RECEIVE_BUFFER_FULL:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_RECEIVE_BUFFER_FULL, currStatus.IsReceiveBufferFull);
break;
case ZebraConstants.PRINTER_STATE_IS_RIBBON_OUT:
resultHash.Add(ZebraConstants.PRINTER_STATE_IS_RIBBON_OUT, currStatus.IsRibbonOut);
break;
case ZebraConstants.PRINTER_STATE_LABELS_REMAINING_IN_BATCH:
resultHash.Add(ZebraConstants.PRINTER_STATE_LABELS_REMAINING_IN_BATCH, currStatus.LabelsRemainingInBatch);
break;
case ZebraConstants.PRINTER_STATE_LABEL_LENGTH_IN_DOTS:
resultHash.Add(ZebraConstants.PRINTER_STATE_LABEL_LENGTH_IN_DOTS, currStatus.LabelLengthInDots);
break;
case ZebraConstants.PRINTER_STATE_NUMBER_OF_FORMATS_IN_RECEIVE_BUFFER:
resultHash.Add(ZebraConstants.PRINTER_STATE_NUMBER_OF_FORMATS_IN_RECEIVE_BUFFER, currStatus.NumberOfFormatsInReceiveBuffer);
break;
case ZebraConstants.PRINTER_STATE_PRINT_MODE:
switch (currStatus.PrintMode)
{
case ZplPrintMode.REWIND:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_REWIND);
break;
case ZplPrintMode.PEEL_OFF:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_PEEL_OFF);
break;
case ZplPrintMode.TEAR_OFF:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_TEAR_OFF);
break;
case ZplPrintMode.CUTTER:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_CUTTER);
break;
case ZplPrintMode.APPLICATOR:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_APPLICATOR);
break;
case ZplPrintMode.DELAYED_CUT:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_DELAYED_CUT);
break;
case ZplPrintMode.LINERLESS_PEEL:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_LINERLESS_PEEL);
break;
case ZplPrintMode.LINERLESS_REWIND:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_REWIND);
break;
case ZplPrintMode.PARTIAL_CUTTER:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_PARTIAL_CUTTER);
break;
case ZplPrintMode.RFID:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_RFID);
break;
case ZplPrintMode.KIOSK:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_KIOSK);
break;
case ZplPrintMode.UNKNOWN:
resultHash.Add(ZebraConstants.PRINTER_STATE_PRINT_MODE, ZebraConstants.PRINT_MODE_UNKNOWN);
break;
}
break;
}
}
}
else
{
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_ERROR);
resultHash.Add(ZebraConstants.HK_MESSAGE, "");
}
}
else
{
resultHash.Add(ZebraConstants.HK_STATUS, ZebraConstants.PRINTER_STATUS_ERR_NOT_CONNECTED);
resultHash.Add(ZebraConstants.HK_MESSAGE, "");
}
oResult.set(resultHash);
}
}
public class PrinterZebraSingleton
{
private Int32 getTimeout(IReadOnlyDictionary<string, string> options)
{
Object valueObj = null;
if (options.ContainsKey("timeout"))
{
valueObj = options["timeout"];
if ((valueObj != null) && (valueObj is String))
{
try
{
return Int32.Parse(valueObj.ToString());
}
catch (System.FormatException ex)
{
}
}
}
return 0;
}
private string getConnectionType(IReadOnlyDictionary<string, string> options)
{
Object valueObj = null;
if (options.ContainsKey("connectionType"))
{
valueObj = options["connectionType"];
if ((valueObj != null) && (valueObj is String))
{
return (String)valueObj;
}
}
return ZebraConstants.CONNECTION_TYPE_ANY;
}
private string getDeviceAdress(IReadOnlyDictionary<string, string> options)
{
Object valueObj = null;
if (options.ContainsKey("deviceAddress"))
{
valueObj = options["deviceAddress"];
if ((valueObj != null) && (valueObj is String))
{
return (String)valueObj;
}
}
return null;
}
private Int32 getDevicePort(IReadOnlyDictionary<string, string> options)
{
Object valueObj = null;
if (options.ContainsKey("devicePort"))
{
valueObj = options["devicePort"];
if (valueObj == null && options.ContainsKey("port"))
{
valueObj = options["port"];
}
try
{
return Int32.Parse(valueObj.ToString());
}
catch (System.FormatException)
{
}
}
return 6101;
}
public void sendConnectFinish(string status, IMethodResult oResult)
{
IReadOnlyDictionary<string, string> printerResult = new IReadOnlyDictionary<string, string>();
printerResult[ZebraConstants.HK_STATUS] = status;
oResult.set(printerResult);
}
public void sendConnectResult(string deviceName, string deviceAdress, Int32 devicePort, PrinterZebra.EPrinterConnectionType connType, IMethodResult oResult)
{
IReadOnlyDictionary<string, string> printerResult = new IReadOnlyDictionary<string, string>();
printerResult[ZebraConstants.HK_STATUS] = ZebraConstants.PRINTER_STATUS_SUCCESS;
printerResult[ZebraConstants.HK_PRINTER_ID] = deviceAdress;
printerResult[ZebraConstants.PROPERTY_DEVICE_ADDRESS] = deviceAdress;
printerResult[ZebraConstants.PROPERTY_DEVICE_PORT] = devicePort.ToString();
printerResult[ZebraConstants.PROPERTY_PRINTER_TYPE] = ZebraConstants.PRINTER_TYPE_ZEBRA;
printerResult[ZebraConstants.PROPERTY_DEVICE_NAME] = deviceName;
if (connType == PrinterZebra.EPrinterConnectionType.eBluetooth)
{
printerResult[ZebraConstants.PROPERTY_CONNECTION_TYPE] = ZebraConstants.CONNECTION_TYPE_BLUETOOTH;
}
else if (connType == PrinterZebra.EPrinterConnectionType.eTCP)
{
printerResult[ZebraConstants.PROPERTY_CONNECTION_TYPE] = ZebraConstants.CONNECTION_TYPE_TCP;
}
else if (connType == PrinterZebra.EPrinterConnectionType.eOnBoard)
{
printerResult[ZebraConstants.PROPERTY_CONNECTION_TYPE] = ZebraConstants.CONNECTION_TYPE_ON_BOARD;
}
else if (connType == PrinterZebra.EPrinterConnectionType.eUSB)
{
printerResult[ZebraConstants.PROPERTY_CONNECTION_TYPE] = ZebraConstants.CONNECTION_TYPE_USB;
}
oResult.set(printerResult);
}
public ConnecttionJob tryToConnect(Int32 port, string deviceAdress, int timeout, PrinterZebra.EPrinterConnectionType connType)
{
Logger.Write("tryToConnect: " + port.ToString() + ", " + deviceAdress + ", " + timeout.ToString());
ConnecttionJob job = new ConnecttionJob();
job.MaxTimeoutForRead = 0;
job.TimeToWaitForMoreData = 0;
job.Port = port;
job.Address = deviceAdress;
job.ConnectionType = connType;
job.Connect(timeout);
return job;
}
private void tryToConnectInFoundPrinters(IMethodResult oResult)
{
IMethodResult result = new SleepMethodResult(500);
List<string> badPrinters = new List<string>();
Logger.Write("tryToConnect start [found printers]");
List<string> printerKeys = PrinterManager.Instance.getPrintersKeys();
foreach (string printerKey in printerKeys)
{
PrinterZebra printer = PrinterManager.Instance.getPrinter(printerKey);
string deviceAdress = printer.ID;
Int32 port = printer.Port;
Logger.Write("searching in address [found printers]: " + deviceAdress);
ConnecttionJob job = tryToConnect(port, deviceAdress, ZebraConstants.connectionTimeout, printer.connectionType);
if (job.Connection != null)
{
Logger.Write("Found printer on address [found printers]: " + deviceAdress);
sendConnectResult(job.FriendlyName, deviceAdress, port, printer.connectionType, oResult);
job.Close();
}
else
{
Logger.Write("remove printer on address [found printers]: " + deviceAdress + " from cache.");
badPrinters.Add(printerKey);
}
}
PrinterManager.Instance.removePrinters(badPrinters);
}
public void searchPrinters(IReadOnlyDictionary<string, string> options, IMethodResult oResult)
{
Logger.Write("searchPrinters call");
Logger.Write("options", options);
tryToConnectInFoundPrinters(oResult);
DiscoveryPrintersJob job = new DiscoveryPrintersJob();
Object valueObj = null;
int discoveryTimeout = getTimeout(options);
Logger.Write("set timeout: " + discoveryTimeout.ToString());
job.connectionType = getConnectionType(options);
job.deviceAdress = getDeviceAdress(options);
job.devicePort = getDevicePort(options);
job.oResult = oResult;
job.zebraSingleton = this;
job.isSearchStopped = false;
if (options.ContainsKey("printerType"))
{
valueObj = options["printerType"];
if ((valueObj != null) && (valueObj is String))
{
String printerType = (String)valueObj;
if (!printerType.Equals(ZebraConstants.PRINTER_TYPE_ZEBRA))
{
sendConnectFinish(ZebraConstants.PRINTER_STATUS_ERR_UNSUPPORTED, oResult);
return;
}
}
}
if (discoveryTimeout == 0)
{
job.Connect();
}
else
{
job.Connect(discoveryTimeout);
}
job.isSearchStopped = true;
sendConnectFinish(ZebraConstants.PRINTER_STATUS_SUCCESS, oResult);
Logger.Write("searchPrinters call end");
}
public void stopSearch(IMethodResult oResult)
{
oResult.set(ZebraConstants.PRINTER_STATUS_SUCCESS);
}
public void closeServiceRequest(IMethodResult oResult)
{
Logger.Write("kill printing service");
// ClientThread.Close();
//Process.GetCurrentProcess().Kill();
}
}
}
}
| |
namespace System.Workflow.ComponentModel.Compiler
{
using System;
using System.Runtime.InteropServices;
internal sealed class PDBReader : IDisposable
{
#region Data Members
private const string IMetaDataImportGuid = "7DAC8207-D3AE-4c75-9B67-92801A497D44";
private ISymUnmanagedReader symReader;
#endregion
#region Constructor and Dispose
public PDBReader(string assemblyPath)
{
object metaDataImport = null;
IMetaDataDispenser dispenser = null;
try
{
Guid metaDataImportIID = new Guid(IMetaDataImportGuid);
dispenser = (IMetaDataDispenser)(new MetaDataDispenser());
dispenser.OpenScope(assemblyPath, 0, ref metaDataImportIID, out metaDataImport);
this.symReader = (ISymUnmanagedReader)(new CorSymReader_SxS());
this.symReader.Initialize(metaDataImport, assemblyPath, null, null);
}
finally
{
// Release COM objects so that files don't remain locked.
if (metaDataImport != null)
Marshal.ReleaseComObject(metaDataImport);
if (dispenser != null)
Marshal.ReleaseComObject(dispenser);
}
}
~PDBReader()
{
Dispose();
}
void IDisposable.Dispose()
{
Dispose();
GC.SuppressFinalize(this);
}
private void Dispose()
{
if (this.symReader != null)
{
Marshal.ReleaseComObject(this.symReader);
this.symReader = null;
}
}
#endregion
#region Public methods
public void GetSourceLocationForOffset(uint methodDef, uint offset, out string fileLocation, out uint line, out uint column)
{
fileLocation = null;
line = 0;
column = 0;
ISymUnmanagedMethod symMethod = null;
ISymUnmanagedDocument[] documents = null;
uint sequencePointCount = 0;
try
{
symMethod = this.symReader.GetMethod(methodDef);
sequencePointCount = symMethod.GetSequencePointCount();
documents = new ISymUnmanagedDocument[sequencePointCount];
uint[] offsets = new uint[sequencePointCount];
uint[] lines = new uint[sequencePointCount];
uint[] columns = new uint[sequencePointCount];
uint[] endLines = new uint[sequencePointCount];
uint[] endColumns = new uint[sequencePointCount];
symMethod.GetSequencePoints(sequencePointCount, out sequencePointCount, offsets, documents, lines, columns, endLines, endColumns);
uint index = 1;
for (; index < sequencePointCount; index++)
{ if (offsets[index] > offset) break; }
index = index - 1;
// Work Around: AkashS - The SymReader returns bad line-column data for unconditional branch
// instructions. The line number is whacky and the column number is 0. Need to verify why this is so.
// We just look for a good sequence point data, it should be close enough in the source code.
while (columns[index] == 0 && index > 0)
index--;
while (index < sequencePointCount && columns[index] == 0)
index++;
// What more can we do?
if (index >= sequencePointCount || columns[index] == 0)
index = 0;
// End Work around
line = lines[index];
column = columns[index];
ISymUnmanagedDocument document = documents[index];
uint urlLength = 261;
string url = new string('\0', (int)urlLength);
document.GetURL(urlLength, out urlLength, url);
fileLocation = url.Substring(0, (int)urlLength - 1);
}
finally
{
// Release COM objects so that files don't remain locked.
for (uint i = 0; i < sequencePointCount; i++)
if (documents[i] != null)
Marshal.ReleaseComObject(documents[i]);
if (symMethod != null)
Marshal.ReleaseComObject(symMethod);
}
}
#endregion
}
#region Interop declarations
//
// Note:
// These interop declaration are sufficient for our purposes of reading the symbol information from
// the PDB. They are not complete otherwise!
//
[ComImport, Guid("0A3976C5-4529-4ef8-B0B0-42EED37082CD")]
internal class CorSymReader_SxS
{ }
[ComImport,
CoClass(typeof(CorSymReader_SxS)),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("B4CE6286-2A6B-3712-A3B7-1EE1DAD467B5")]
internal interface ISymUnmanagedReader
{
// NYI.
void GetDocument();
void GetDocuments();
void GetUserEntryPoint();
ISymUnmanagedMethod GetMethod(uint methodDef);
// NYI.
void GetMethodByVersion();
void GetVariables();
void GetGlobalVariables();
void GetMethodFromDocumentPosition();
void GetSymAttribute();
void GetNamespaces();
// Incomplete - We don't use the Stream
void Initialize([In, MarshalAs(UnmanagedType.IUnknown)] object metaDataImport, [In, MarshalAs(UnmanagedType.LPWStr)] string pdbPath, [In, MarshalAs(UnmanagedType.LPWStr)] string searchPath, [In, MarshalAs(UnmanagedType.IUnknown)] object stream);
// NYI.
void UpdateSymbolStore();
void ReplaceSymbolStore();
void GetSymbolStoreFileName();
void GetMethodsFromDocumentPosition();
void GetDocumentVersion();
void GetMethodVersion();
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("B62B923C-B500-3158-A543-24F307A8B7E1")]
internal interface ISymUnmanagedMethod
{
uint GetToken();
uint GetSequencePointCount();
// Incomplete - Don't need to define ISymUnmanagedScope.
object GetRootScope();
// Incomplete - Don't need to define ISymUnmanagedScope.
object GetScopeFromOffset(uint offset);
uint GetOffset([In, MarshalAs(UnmanagedType.IUnknown)] ISymUnmanagedDocument document, uint line, uint column);
void GetRanges([In, MarshalAs(UnmanagedType.IUnknown)] ISymUnmanagedDocument document, uint line, uint column, uint rangeCount, [Out] out uint actualRangeCount, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] ranges);
// NYI.
void GetParameters();
// NYI.
void GetNamespace();
void GetSourceStartEnd([In, Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedDocument[] documents, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] lines, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] columns, [Out, MarshalAs(UnmanagedType.Bool)] out bool positionsDefined);
void GetSequencePoints(uint pointsCount, [Out] out uint actualPointsCount, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] offsets, [In, Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedDocument[] documents, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] lines, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] columns, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] endLines, [In, Out, MarshalAs(UnmanagedType.LPArray)] uint[] endColumns);
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("40DE4037-7C81-3E1E-B022-AE1ABFF2CA08")]
internal interface ISymUnmanagedDocument
{
void GetURL(uint urlLength, [Out] out uint actualUrlLength, [In, Out, MarshalAs(UnmanagedType.LPWStr)] string url);
// The rest are NYI.
void GetDocumentType();
void GetLanguage();
void GetLanguageVendor();
void GetCheckSumAlgorithmId();
void GetCheckSum();
void FindClosestLine();
void HasEmbeddedSource();
void GetSourceLength();
void GetSourceRange();
}
[ComImport,
Guid("E5CB7A31-7512-11d2-89CE-0080C792E5D8")]
internal class MetaDataDispenser
{
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
CoClass(typeof(MetaDataDispenser)),
Guid("809C652E-7396-11d2-9771-00A0C9B4D50C")]
internal interface IMetaDataDispenser
{
// NYI
void DefineScope();
// Incomplete - I don't really need to define IMetaDataImport.
void OpenScope([In, MarshalAs(UnmanagedType.LPWStr)] string scope, uint flags, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.IUnknown)] out object unknown);
// NYI
void OpenScopeOnMemory();
}
#endregion
}
| |
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using MS.Utility;
using MS.Internal;
using MS.Internal.Interop;
using MS.Win32;
using MS.Internal.PresentationCore;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Interop
{
internal sealed class HwndKeyboardInputProvider : DispatcherObject, IKeyboardInputProvider, IDisposable
{
/// <SecurityNote>
/// Accesses and store critical data. This class is also critical (_site and _source)
/// </SecurityNote>
[SecurityCritical]
internal HwndKeyboardInputProvider(HwndSource source)
{
(new UIPermission(PermissionState.Unrestricted)).Assert();
try //Blessed assert for InputManager.Current.RegisterInputProvider
{
_site = new SecurityCriticalDataClass<InputProviderSite>(InputManager.Current.RegisterInputProvider(this));
}
finally
{
UIPermission.RevertAssert();
}
_source = new SecurityCriticalDataClass<HwndSource>(source);
}
/// <SecurityNote>
/// Critical:This class accesses critical data, _site.
/// TreatAsSafe: This class does not expose the critical data
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public void Dispose()
{
if(_site != null)
{
_site.Value.Dispose();
_site = null;
}
_source = null;
}
public void OnRootChanged(Visual oldRoot, Visual newRoot)
{
if(_active && newRoot != null)
{
Keyboard.Focus(null); // internally we will set the focus to the root.
}
}
/// <SecurityNote>
/// Critical: As this accesses critical data HwndSource
/// TreatAsSafe:Information about whether a given input provider services
/// a visual is safe to expose. This method does not expose the critical data either.
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
bool IInputProvider.ProvidesInputForRootVisual(Visual v)
{
Debug.Assert( null != _source );
return _source.Value.RootVisual == v;
}
void IInputProvider.NotifyDeactivate()
{
_active = false;
_partialActive = false;
}
/// <SecurityNote>
/// SecurityCritical: This code calls a variety of critical native
/// methods related to keyboard focus and window styles. None of
/// this information is returned, but focus can be changed which
/// impacts the functioning of a great deal of native code.
/// </SecurityNote>
[SecurityCritical]
bool IKeyboardInputProvider.AcquireFocus(bool checkOnly)
{
bool result = false;
Debug.Assert( null != _source );
try
{
// Acquiring focus into this window should clear any pending focus restoration.
if(!checkOnly)
{
_acquiringFocusOurselves = true;
_restoreFocusWindow = IntPtr.Zero;
_restoreFocus = null;
}
HandleRef thisWindow = new HandleRef(this, _source.Value.CriticalHandle);
IntPtr focus = UnsafeNativeMethods.GetFocus();
int windowStyle = UnsafeNativeMethods.GetWindowLong(thisWindow, NativeMethods.GWL_EXSTYLE);
if ((windowStyle & NativeMethods.WS_EX_NOACTIVATE) == NativeMethods.WS_EX_NOACTIVATE || _source.Value.IsInExclusiveMenuMode)
{
// If this window has the WS_EX_NOACTIVATE style, then we
// do not set Win32 keyboard focus to this window because
// that would actually activate the window. This is
// typically for the menu Popup.
//
// If this window is in "menu mode", then we do not set
// Win32 focus to this window because we don't want to
// move Win32 focus from where it is. This is typically
// for the main window.
//
// In either case, the window must be enabled.
if(SafeNativeMethods.IsWindowEnabled(thisWindow))
{
if (SecurityHelper.AppDomainGrantedUnrestrictedUIPermission)
{
// In fully-trusted AppDomains, the only hard requirement
// is that Win32 keyboard focus be on some window owned
// by a thread that is attached to our Win32 queue. This
// presumes that the thread's message pump will cooperate
// by calling ComponentDispatcher.RaiseThreadMessage.
// If so, WPF will be able to route the keyboard events to the
// element with WPF keyboard focus, regardless of which
// window has Win32 keyboard focus.
//
// Menus/ComboBoxes use this feature.
//
// Dev11 is moving more towards cross-process designer
// support. They make sure to call AttachThreadInput so
// the the two threads share the same Win32 queue. In
// addition, they repost the keyboard messages to the
// main UI process/thread for handling.
//
// We rely on the behavior of GetFocus to only return a
// window handle for windows attached to the calling
// thread's queue.
//
result = focus != IntPtr.Zero;
}
else
{
// In partially-trusted AppDomains, we do not want to expose input
// intended for other native windows, or for WPF windows in other
// AppDomains.
result = IsOurWindow(focus);
}
}
}
else
{
// This is the normal case. We want to keep WPF keyboard
// focus and Win32 keyboard focus in [....].
if(!checkOnly)
{
// Due to IsInExclusiveMenuMode, it is possible that an
// HWND keeps Win32 focus even though WPF has moved
// element focus somewhere else. When the element focus
// moves somewhere else, this input provider will get
// deactivated. If element focus is set back to an
// element within this provider, the HWND already has
// Win32 focus and so will not receive another
// WM_SETFOCUS, causing the provider to remain
// deactivated. Now we detect that we already have
// Win32 focus but are not activated and treat it the
// same as getting focus.
if (!_active && focus == _source.Value.CriticalHandle)
{
OnSetFocus(focus);
}
else
{
UnsafeNativeMethods.TrySetFocus(thisWindow);
// Fetch the HWND with Win32 focus again, to double
// check we got it.
focus = UnsafeNativeMethods.GetFocus();
}
}
result = (focus == _source.Value.CriticalHandle);
}
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: AcquireFocus failed!");
}
finally
{
_acquiringFocusOurselves = false;
}
return result;
}
/// <SecurityNote>
/// Critical:
/// This code is critical since it handles all keyboard messages
/// and could be used to spoof input.
/// For HANDLED_KEYDOWN_STILL_GENERATES_CHARS we also cause the
/// Dispatcher to defer processing the queue until after any
/// currently pending messages.
/// </SecurityNote>
[SecurityCritical]
internal IntPtr FilterMessage(IntPtr hwnd, WindowMessage message, IntPtr wParam, IntPtr lParam, ref bool handled)
{
IntPtr result = IntPtr.Zero ;
// It is possible to be re-entered during disposal. Just return.
if(null == _source || null == _source.Value)
{
return result;
}
_msgTime = 0;
try
{
_msgTime = SafeNativeMethods.GetMessageTime();
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndKeyboardInputProvider: GetMessageTime failed!");
}
switch(message)
{
// WM_KEYDOWN is sent when a nonsystem key is pressed.
// A nonsystem key is a key that is pressed when the ALT key
// is not pressed.
// WM_SYSKEYDOWN is sent when a system key is pressed.
case WindowMessage.WM_SYSKEYDOWN:
case WindowMessage.WM_KEYDOWN:
{
// If we have a IKeyboardInputSite, then we should have already
// called ProcessKeyDown (from TranslateAccelerator)
// But there are several paths (our message pump / app's message
// pump) where we do (or don't) call through IKeyboardInputSink.
// So the best way is to just check here if we already did it.
if(_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam))
{
break;
}
// We will use the current time before generating KeyDown events so we can filter
// the later posted WM_CHAR.
int currentTime = 0;
try
{
currentTime = SafeNativeMethods.GetTickCount();
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetTickCount failed!");
}
// MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
// In case a nested message pump is used before we return
// from processing this message, we disable processing the
// next WM_CHAR message because if the code pumps messages
// it should really mark the message as handled.
HwndSource._eatCharMessages = true;
DispatcherOperation restoreCharMessages = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(HwndSource.RestoreCharMessages), null);
// Force the Dispatcher to post a new message to service any
// pending operations, so that the operation we just posted
// is guaranteed to get dispatched after any pending WM_CHAR
// messages are dispatched.
Dispatcher.CriticalRequestProcessing(true);
MSG msg = new MSG(hwnd, (int)message, wParam, lParam, _msgTime, 0, 0);
ProcessKeyAction(ref msg, ref handled);
if(!handled)
{
// MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
// We did not handle the WM_KEYDOWN, so it is OK to process WM_CHAR messages.
// We can also abort the pending restore operation since we don't need it.
HwndSource._eatCharMessages = false;
restoreCharMessages.Abort();
}
// System.Console.WriteLine("KEYDOWN(message={0}, wParam={1})={2}", message, wParam, handled);
}
break;
// WM_KEYUP is sent when a nonsystem key is released.
// A nonsystem key is a key that is pressed when the ALT key
// is not pressed.
// WM_SYSKEYUP is sent when a system key is released.
case WindowMessage.WM_SYSKEYUP:
case WindowMessage.WM_KEYUP:
{
if(_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam))
{
break;
}
MSG msg = new MSG(hwnd, (int)message, wParam, lParam, _msgTime, 0, 0);
ProcessKeyAction(ref msg, ref handled);
// System.Console.WriteLine("KEYUP (message={0}, wParam={1})={2}", message, wParam, handled);
}
break;
//
case WindowMessage.WM_CHAR:
case WindowMessage.WM_DEADCHAR:
case WindowMessage.WM_SYSCHAR:
case WindowMessage.WM_SYSDEADCHAR:
{
if(_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam))
{
break;
}
// MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
if(HwndSource._eatCharMessages)
{
break;
}
ProcessTextInputAction(hwnd, message, wParam, lParam, ref handled);
// System.Console.WriteLine("CHAR(message={0}, wParam={1})={2}", message, wParam, handled);
}
break;
case WindowMessage.WM_EXITMENULOOP:
case WindowMessage.WM_EXITSIZEMOVE:
{
// MITIGATION: KEYBOARD_STATE_OUT_OF_[....]
//
// Avalon relies on keeping it's copy of the keyboard
// state. This is for a number of reasons, including that
// we need to be able to give this state to worker threads.
//
// There are a number of cases where Win32 eats the
// keyboard messages, and this can cause our keyboard
// state to become stale. Obviously this can happen when
// another app is in the foreground, but we handle that
// by re-synching our keyboard state when we get focus.
//
// Other times are when Win32 enters a nested loop. While
// any one could enter a nested loop at any time for any
// reason, Win32 is nice enough to let us know when it is
// finished with the two common loops: menus and sizing.
// We re-[....] our keyboard device in response to these.
//
if(_active)
{
_partialActive = true;
ReportInput(hwnd,
InputMode.Foreground,
_msgTime,
RawKeyboardActions.Activate,
0,
false,
false,
0);
}
}
break;
// WM_SETFOCUS is sent immediately after focus is granted.
// This is our clue that the keyboard is active.
case WindowMessage.WM_SETFOCUS:
{
OnSetFocus(hwnd);
handled = true;
}
break;
// WM_KILLFOCUS is sent immediately before focus is removed.
// This is our clue that the keyboard is inactive.
case WindowMessage.WM_KILLFOCUS:
{
if(_active && wParam != _source.Value.CriticalHandle )
{
// Console.WriteLine("WM_KILLFOCUS");
if(_source.Value.RestoreFocusMode == RestoreFocusMode.Auto)
{
// when the window that's acquiring focus (wParam) is
// a descendant of our window, remember the immediate
// child so that we can restore focus to it.
_restoreFocusWindow = GetImmediateChildFor((IntPtr)wParam, _source.Value.CriticalHandle);
_restoreFocus = null;
// If we aren't restoring focus to a child window,
// then restore focus to the element that currently
// has WPF keyboard focus if it is directly in this
// HwndSource.
if (_restoreFocusWindow == IntPtr.Zero)
{
DependencyObject focusedDO = Keyboard.FocusedElement as DependencyObject;
if (focusedDO != null)
{
HwndSource hwndSource = PresentationSource.CriticalFromVisual(focusedDO) as HwndSource;
if (hwndSource == _source.Value)
{
_restoreFocus = focusedDO as IInputElement;
}
}
}
}
PossiblyDeactivate((IntPtr)wParam);
}
handled = true;
}
break;
// WM_UPDATEUISTATE is sent when the user presses ALT, expecting
// the app to display accelerator keys. We don't always hear the
// keystroke - another message loop may handle it. So report it
// here.
case WindowMessage.WM_UPDATEUISTATE:
{
RawUIStateInputReport report =
new RawUIStateInputReport(_source.Value,
InputMode.Foreground,
_msgTime,
(RawUIStateActions)NativeMethods.SignedLOWORD((int)wParam),
(RawUIStateTargets)NativeMethods.SignedHIWORD((int)wParam));
_site.Value.ReportInput(report);
handled = true;
}
break;
}
if (handled && EventTrace.IsEnabled(EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info))
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientInputMessage,
EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info,
Dispatcher.GetHashCode(),
hwnd.ToInt64(),
message,
(int)wParam,
(int)lParam);
}
return result;
}
/// <SecurityNote>
/// Critical: This code is critical since it reports input to WPF.
/// </SecurityNote>
[SecurityCritical]
private void OnSetFocus(IntPtr hwnd)
{
// Normally we get WM_SETFOCUS only when _active is false.
// Dev11 364494 revealed a situation where we get it when _active is true:
// 1. Window contains a WindowsFormsHost, which contains a WF.TextBox that has focus
// 2. User types Alt-Tab to switch to another app
// 3. User types Alt-Tab again to return to this window
// The ALT key sets _active to true, as we are processing keyboard input,
// even though focus is in another window (the WF.TextBox). But Alt-Tab
// sends focus to another app, and we don't get any messages (the WF.TextBox
// gets WM_KILLFOCUS, but doesn't tell us about it). Thus when focus
// returns after the second Alt-Tab, _active is still true.
//
// We need to run the focus restoration logic in this case. To make that
// happen, we set _active to false here. This leaves _active in the
// state we want, even if the code herein encounters errors/exceptions.
// There may be other cases where _active is true here (we don't know of
// any, but we cannot rule them out), but we believe that the code won't
// do any harm.
_active = false;
if (!_active)
{
// There is a chance that external code called during the focus
// changes below will dispose our window, causing _source to get
// cleared. We actually saw this in XDesProc (the Blend XAML
// designer process) in 4.5 Beta, but never tracked down the culprit.
// To be safe, we cache the member variable in a local variable
// for use within this method.
HwndSource thisSource = _source.Value;
// Console.WriteLine("WM_SETFOCUS");
ReportInput(hwnd,
InputMode.Foreground,
_msgTime,
RawKeyboardActions.Activate,
0,
false,
false,
0);
// MITIGATION: KEYBOARD_STATE_OUT_OF_[....]
//
// This is how we deal with the fact that Win32 sometimes sends
// us a WM_SETFOCUS message BEFORE it has updated it's internal
// internal keyboard state information. When we get the
// WM_SETFOCUS message, we activate the keyboard with the
// keyboard state (even though it could be wrong). Then when
// we get the first "real" keyboard input event, we activate
// the keyboard again, since Win32 will have updated the
// keyboard state correctly by then.
//
_partialActive = true;
if (!_acquiringFocusOurselves && thisSource.RestoreFocusMode == RestoreFocusMode.Auto)
{
// Restore the keyboard focus to the child window or element that had
// the focus before we last lost Win32 focus. If nothing
// had focus before, set it to null.
if (_restoreFocusWindow != IntPtr.Zero)
{
IntPtr hwndRestoreFocus = _restoreFocusWindow;
_restoreFocusWindow = IntPtr.Zero;
UnsafeNativeMethods.TrySetFocus(new HandleRef(this, hwndRestoreFocus), ref hwndRestoreFocus);
}
else
{
DependencyObject restoreFocusDO = _restoreFocus as DependencyObject;
_restoreFocus = null;
if (restoreFocusDO != null)
{
// Only restore focus to an element if that
// element still belongs to this HWND.
HwndSource hwndSource = PresentationSource.CriticalFromVisual(restoreFocusDO) as HwndSource;
if (hwndSource != thisSource)
{
restoreFocusDO = null;
}
}
// Try to restore focus to the last element that had focus. Note
// that if restoreFocusDO is null, we will internally set focus
// to the root element.
Keyboard.Focus(restoreFocusDO as IInputElement);
// Lots of things can happen when setting focus to an element,
// including that element may set focus somewhere else, possibly
// even into another HWND. However, if Win32 focus remains on
// this window, we do not allow the focused element to be in
// a different window.
IntPtr focus = UnsafeNativeMethods.GetFocus();
if (focus == thisSource.CriticalHandle)
{
restoreFocusDO = (DependencyObject)Keyboard.FocusedElement;
if (restoreFocusDO != null)
{
HwndSource hwndSource = PresentationSource.CriticalFromVisual(restoreFocusDO) as HwndSource;
if (hwndSource != thisSource)
{
Keyboard.ClearFocus();
}
}
}
}
}
}
}
/// <SecurityNote>
/// Critical:This can be used to spoof input
/// </SecurityNote>
[SecurityCritical]
internal void ProcessKeyAction(ref MSG msg, ref bool handled)
{
// Remember the last message
MSG previousMSG = ComponentDispatcher.UnsecureCurrentKeyboardMessage;
ComponentDispatcher.UnsecureCurrentKeyboardMessage = msg;
try
{
int virtualKey = GetVirtualKey(msg.wParam, msg.lParam);
int scanCode = GetScanCode(msg.wParam, msg.lParam);
bool isExtendedKey = IsExtendedKey(msg.lParam);
bool isSystemKey = (((WindowMessage)msg.message == WindowMessage.WM_SYSKEYDOWN) || ((WindowMessage)msg.message == WindowMessage.WM_SYSKEYUP));
RawKeyboardActions action = GetKeyUpKeyDown((WindowMessage)msg.message);
// Console.WriteLine("WM_KEYDOWN: " + virtualKey + "," + scanCode);
handled = ReportInput(msg.hwnd,
InputMode.Foreground,
_msgTime,
action,
scanCode,
isExtendedKey,
isSystemKey,
virtualKey);
}
finally
{
// Restore the last message
ComponentDispatcher.UnsecureCurrentKeyboardMessage = previousMSG;
}
}
///<SecurityNote>
/// Critical - calls a critical method _source.Value.
///</SecurityNote>
[SecurityCritical ]
internal void ProcessTextInputAction(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
char charcode = (char)wParam;
bool isDeadChar = ((msg == WindowMessage.WM_DEADCHAR) || (msg == WindowMessage.WM_SYSDEADCHAR));
bool isSystemChar = ((msg == WindowMessage.WM_SYSCHAR) || (msg == WindowMessage.WM_SYSDEADCHAR));
bool isControlChar = false;
// If the control is pressed but Alt is not, the char is control char.
try
{
if (((UnsafeNativeMethods.GetKeyState(NativeMethods.VK_CONTROL) & 0x8000) != 0) &&
((UnsafeNativeMethods.GetKeyState(NativeMethods.VK_MENU) & 0x8000) == 0) &&
Char.IsControl(charcode))
{
isControlChar = true;
}
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetKeyState failed!");
}
RawTextInputReport report = new RawTextInputReport(_source.Value ,
InputMode.Foreground,
_msgTime,
isDeadChar,
isSystemChar,
isControlChar,
charcode);
handled = _site.Value.ReportInput(report);
}
internal static int GetVirtualKey(IntPtr wParam, IntPtr lParam)
{
int virtualKey = NativeMethods.IntPtrToInt32( wParam);
int scanCode = 0;
int keyData = NativeMethods.IntPtrToInt32(lParam);
// Find the left/right instance SHIFT keys.
if(virtualKey == NativeMethods.VK_SHIFT)
{
scanCode = (keyData & 0xFF0000) >> 16;
try
{
virtualKey = SafeNativeMethods.MapVirtualKey(scanCode, 3);
if(virtualKey == 0)
{
virtualKey = NativeMethods.VK_LSHIFT;
}
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: MapVirtualKey failed!");
virtualKey = NativeMethods.VK_LSHIFT;
}
}
// Find the left/right instance ALT keys.
if(virtualKey == NativeMethods.VK_MENU)
{
bool right = ((keyData & 0x1000000) >> 24) != 0;
if(right)
{
virtualKey = NativeMethods.VK_RMENU;
}
else
{
virtualKey = NativeMethods.VK_LMENU;
}
}
// Find the left/right instance CONTROL keys.
if(virtualKey == NativeMethods.VK_CONTROL)
{
bool right = ((keyData & 0x1000000) >> 24) != 0;
if(right)
{
virtualKey = NativeMethods.VK_RCONTROL;
}
else
{
virtualKey = NativeMethods.VK_LCONTROL;
}
}
return virtualKey;
}
internal static int GetScanCode(IntPtr wParam, IntPtr lParam)
{
int keyData = NativeMethods.IntPtrToInt32(lParam);
int scanCode = (keyData & 0xFF0000) >> 16;
if(scanCode == 0)
{
try
{
int virtualKey = GetVirtualKey(wParam, lParam);
scanCode = SafeNativeMethods.MapVirtualKey(virtualKey, 0);
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: MapVirtualKey failed!");
}
}
return scanCode;
}
internal static bool IsExtendedKey(IntPtr lParam)
{
int keyData = NativeMethods.IntPtrToInt32(lParam);
return ((keyData & 0x01000000) != 0) ? true : false;
}
///<summary>
/// Returns the set of modifier keys currently pressed as determined by calling to Win32
///</summary>
///<remarks>
/// Marked as FriendAccessAllowed so HwndHost in PresentationFramework can call it
///</remarks>
///<SecurityNote>
/// Critical: It calls an UnsafeNativeMethod (GetKeyState).
/// TreatAsSafe: It's safe to return whether shift, control or alt keys are being pressed or not.
///</SecurityNote>
[FriendAccessAllowed]
[SecurityCritical,SecurityTreatAsSafe]
internal static ModifierKeys GetSystemModifierKeys()
{
ModifierKeys modifierKeys = ModifierKeys.None;
short keyState = UnsafeNativeMethods.GetKeyState(NativeMethods.VK_SHIFT);
if((keyState & 0x8000) == 0x8000)
{
modifierKeys |= ModifierKeys.Shift;
}
keyState = UnsafeNativeMethods.GetKeyState(NativeMethods.VK_CONTROL);
if((keyState & 0x8000) == 0x8000)
{
modifierKeys |= ModifierKeys.Control;
}
keyState = UnsafeNativeMethods.GetKeyState(NativeMethods.VK_MENU);
if((keyState & 0x8000) == 0x8000)
{
modifierKeys |= ModifierKeys.Alt;
}
return modifierKeys;
}
private RawKeyboardActions GetKeyUpKeyDown(WindowMessage msg)
{
if( msg == WindowMessage.WM_KEYDOWN || msg == WindowMessage.WM_SYSKEYDOWN )
return RawKeyboardActions.KeyDown;
if( msg == WindowMessage.WM_KEYUP || msg == WindowMessage.WM_SYSKEYUP )
return RawKeyboardActions.KeyUp;
throw new ArgumentException(SR.Get(SRID.OnlyAcceptsKeyMessages));
}
/// <SecurityNote>
/// Critical: This code causes this window to loose focus not ok to expose
/// It also calls into a critical code path.
/// </SecurityNote>
[SecurityCritical]
private void PossiblyDeactivate(IntPtr hwndFocus)
{
Debug.Assert( null != _source );
// We are now longer active ourselves, but it is possible that the
// window the keyboard is going to intereact with is in the same
// Dispatcher as ourselves. If so, we don't want to deactivate the
// keyboard input stream because the other window hasn't activated
// it yet, and it may result in the input stream "flickering" between
// active/inactive/active. This is ugly, so we try to supress the
// uneccesary transitions.
//
bool deactivate = !IsOurWindow(hwndFocus);
// This window itself should not be active anymore.
_active = false;
// Only deactivate the keyboard input stream if needed.
if(deactivate)
{
ReportInput(_source.Value.CriticalHandle,
InputMode.Foreground,
_msgTime,
RawKeyboardActions.Deactivate,
0,
false,
false,
0);
}
}
/// <SecurityNote>
/// Critical: This code does not store any critical data, it accesses PresentationSource
/// TreatAsSafe: This information is safe to expose
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
private bool IsOurWindow(IntPtr hwnd)
{
bool isOurWindow = false;
Debug.Assert( null != _source );
if(hwnd != IntPtr.Zero)
{
HwndSource hwndSource = HwndSource.CriticalFromHwnd(hwnd);
if(hwndSource != null)
{
if(hwndSource.Dispatcher == _source.Value.Dispatcher)
{
// The window has the same dispatcher, must be ours.
isOurWindow = true;
}
else
{
// The window has a different dispatcher, must not be ours.
isOurWindow = false;
}
}
else
{
// The window is non-Avalon.
// Such windows are never ours.
isOurWindow = false;
}
}
else
{
// This is not even a window.
isOurWindow = false;
}
return isOurWindow;
}
// return the immediate child (if any) of hwndRoot that governs the
// given hwnd. If hwnd is not a descendant of hwndRoot, return 0.
/// <SecurityNote>
/// Critical:This method calls critical methods
/// </SecurityNote>
[SecurityCritical]
private IntPtr GetImmediateChildFor(IntPtr hwnd, IntPtr hwndRoot)
{
while (hwnd != IntPtr.Zero)
{
// We only care to restore focus to child windows. Notice that WS_POPUP
// windows also have parents but we do not want to track those here.
int windowStyle = UnsafeNativeMethods.GetWindowLong(new HandleRef(this,hwnd), NativeMethods.GWL_STYLE);
if((windowStyle & NativeMethods.WS_CHILD) == 0)
{
break;
}
IntPtr hwndParent = UnsafeNativeMethods.GetParent(new HandleRef(this, hwnd));
if (hwndParent == hwndRoot)
{
return hwnd;
}
hwnd = hwndParent;
}
return IntPtr.Zero;
}
/// <SecurityNote>
/// Critical:This code can cause input simulation and hence is critical.
/// The current code path is only hit under RootBrowserWindow scenario for now.
/// </SecurityNote>
[SecurityCritical]
private bool ReportInput(
IntPtr hwnd,
InputMode mode,
int timestamp,
RawKeyboardActions actions,
int scanCode,
bool isExtendedKey,
bool isSystemKey,
int virtualKey)
{
Debug.Assert( null != _source );
// The first event should also activate the keyboard device.
if((actions & RawKeyboardActions.Deactivate) == 0)
{
if(!_active || _partialActive)
{
try
{
// Include the activation action.
actions |= RawKeyboardActions.Activate;
// Remember that we are active.
_active = true;
_partialActive = false;
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetKeyboardState failed!");
// We'll go ahead and report the input, but we'll try to "activate" next time.
}
}
}
// Get the extra information sent along with the message.
IntPtr extraInformation = IntPtr.Zero;
try
{
extraInformation = UnsafeNativeMethods.GetMessageExtraInfo();
}
catch(System.ComponentModel.Win32Exception)
{
System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetMessageExtraInfo failed!");
}
RawKeyboardInputReport report = new RawKeyboardInputReport(_source.Value,
mode,
timestamp,
actions,
scanCode,
isExtendedKey,
isSystemKey,
virtualKey,
extraInformation);
bool handled = _site.Value.ReportInput(report);
return handled;
}
private int _msgTime;
/// <SecurityNote>
/// This is got under an elevation and is hence critical. This data is not ok to expose.
/// </SecurityNote>
private SecurityCriticalDataClass<HwndSource> _source;
/// <SecurityNote>
/// This is got under an elevation and is hence critical.This data is not ok to expose.
/// </SecurityNote>
private SecurityCriticalDataClass<InputProviderSite> _site;
private IInputElement _restoreFocus;
/// <SecurityNote>
/// This is got under an elevation and is hence critical.This data is not ok to expose.
/// </SecurityNote>
[SecurityCritical]
private IntPtr _restoreFocusWindow;
private bool _active;
private bool _partialActive;
private bool _acquiringFocusOurselves;
}
}
| |
// ***********************************************************************
// Assembly : MetroFramework
// Author : velez
// Created : 12-09-2015
//
// Last Modified By : velez
// Last Modified On : 12-11-2015
// ***********************************************************************
// <copyright file="MetroTabControl.cs" company="MetroFrameworkAssembly.Company">
// MetroFrameworkAssembly.Copyright
// </copyright>
// <summary></summary>
// ***********************************************************************
/**
* MetroFramework - Modern UI for WinForms
*
* The MIT License (MIT)
* Copyright (c) 2011 Sven Walter, http://github.com/viperneo
*
* Copyright (c) 2013 Dennis Magno, http://github.com/dennismagno
*
* Copyright (c) 2015 Hector Velez, http://github.com/barecool
*
* 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.
*/
// Based on original work by
// (c) Mick Doherty / Oscar Londono
// http://dotnetrix.co.uk/tabcontrol.htm
// http://www.pcreview.co.uk/forums/adding-custom-tabpages-design-time-t2904262.html
// http://www.codeproject.com/Articles/12185/A-NET-Flat-TabControl-CustomDraw
// http://www.codeproject.com/Articles/278/Fully-owner-drawn-tab-control
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using MetroFramework.Components;
using MetroFramework.Drawing;
using MetroFramework.Interfaces;
using MetroFramework.Native;
using System.Collections.Generic;
using MetroFramework.Controls;
#pragma warning disable 1587
/// <summary>
/// The Controls namespace.
/// </summary>
#pragma warning restore 1587
namespace MetroFramework.Controls
{
#region MetroTabPageCollection
/// <summary>
/// Class MetroTabPageCollection.
/// </summary>
[ToolboxItem(false)]
[Editor("MetroFramework.Design.MetroTabPageCollectionEditor, " + AssemblyRef.MetroFrameworkDesignSN, typeof(UITypeEditor))]
public class MetroTabPageCollection : TabControl.TabPageCollection
{
/// <summary>
/// Initializes a new instance of the <see cref="MetroTabPageCollection"/> class.
/// </summary>
/// <param name="owner">The owner.</param>
public MetroTabPageCollection(MetroTabControl owner) : base(owner)
{ }
}
#endregion
#region HiddenTabClass
/// <summary>
/// Class HiddenTabs.
/// </summary>
public class HiddenTabs
{
/// <summary>
/// Initializes a new instance of the <see cref="HiddenTabs"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="page">The page.</param>
public HiddenTabs(int id, string page)
{
_index = id;
_tabpage = page;
}
/// <summary>
/// The _index
/// </summary>
private int _index;
/// <summary>
/// The _tabpage
/// </summary>
private string _tabpage;
/// <summary>
/// Gets the index.
/// </summary>
/// <value>The index.</value>
public int index { get { return _index; } }
/// <summary>
/// Gets the tabpage.
/// </summary>
/// <value>The tabpage.</value>
public string tabpage { get { return _tabpage; } }
}
#endregion HiddenTabClass
/// <summary>
/// Class MetroTabControl.
/// </summary>
[Designer("MetroFramework.Design.Controls.MetroTabControlDesigner, " + AssemblyRef.MetroFrameworkDesignSN)]
[ToolboxBitmap(typeof(TabControl))]
public class MetroTabControl : TabControl, IMetroControl
{
#region Interface
/// <summary>
/// Occurs when [custom paint background].
/// </summary>
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintBackground;
/// <summary>
/// Handles the <see cref="E:CustomPaintBackground" /> event.
/// </summary>
/// <param name="e">The <see cref="MetroPaintEventArgs"/> instance containing the event data.</param>
protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null)
{
CustomPaintBackground(this, e);
}
}
/// <summary>
/// Occurs when [custom paint].
/// </summary>
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaint;
/// <summary>
/// Handles the <see cref="E:CustomPaint" /> event.
/// </summary>
/// <param name="e">The <see cref="MetroPaintEventArgs"/> instance containing the event data.</param>
protected virtual void OnCustomPaint(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null)
{
CustomPaint(this, e);
}
}
/// <summary>
/// Occurs when [custom paint foreground].
/// </summary>
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintForeground;
/// <summary>
/// Handles the <see cref="E:CustomPaintForeground" /> event.
/// </summary>
/// <param name="e">The <see cref="MetroPaintEventArgs"/> instance containing the event data.</param>
protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null)
{
CustomPaintForeground(this, e);
}
}
/// <summary>
/// Occurs when [tab page closed].
/// </summary>
[Category(MetroDefaults.PropertyCategory.Behaviour)]
public event EventHandler<TabPageClosedEventArgs> TabPageClosed;
/// <summary>
/// The metro style
/// </summary>
private MetroColorStyle metroStyle = MetroColorStyle.Default;
/// <summary>
/// Gets or sets the style.
/// </summary>
/// <value>The style.</value>
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroColorStyle.Default)]
public MetroColorStyle Style
{
get
{
if (DesignMode || metroStyle != MetroColorStyle.Default)
{
return metroStyle;
}
if (StyleManager != null && metroStyle == MetroColorStyle.Default)
{
return StyleManager.Style;
}
if (StyleManager == null && metroStyle == MetroColorStyle.Default)
{
return MetroDefaults.Style;
}
return metroStyle;
}
set { metroStyle = value; }
}
/// <summary>
/// The metro theme
/// </summary>
private MetroThemeStyle metroTheme = MetroThemeStyle.Default;
/// <summary>
/// Gets or sets the theme.
/// </summary>
/// <value>The theme.</value>
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroThemeStyle.Default)]
public MetroThemeStyle Theme
{
get
{
if (DesignMode || metroTheme != MetroThemeStyle.Default)
{
return metroTheme;
}
if (StyleManager != null && metroTheme == MetroThemeStyle.Default)
{
return StyleManager.Theme;
}
if (StyleManager == null && metroTheme == MetroThemeStyle.Default)
{
return MetroDefaults.Theme;
}
return metroTheme;
}
set { metroTheme = value; }
}
/// <summary>
/// The metro style manager
/// </summary>
private MetroStyleManager metroStyleManager = null;
/// <summary>
/// Gets or sets the style manager.
/// </summary>
/// <value>The style manager.</value>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MetroStyleManager StyleManager
{
get { return metroStyleManager; }
set { metroStyleManager = value; }
}
/// <summary>
/// The use custom back color
/// </summary>
private bool useCustomBackColor = false;
/// <summary>
/// Gets or sets a value indicating whether [use custom back color].
/// </summary>
/// <value><c>true</c> if [use custom back color]; otherwise, <c>false</c>.</value>
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomBackColor
{
get { return useCustomBackColor; }
set { useCustomBackColor = value; }
}
/// <summary>
/// The use custom fore color
/// </summary>
private bool useCustomForeColor = false;
/// <summary>
/// Gets or sets a value indicating whether [use custom fore color].
/// </summary>
/// <value><c>true</c> if [use custom fore color]; otherwise, <c>false</c>.</value>
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomForeColor
{
get { return useCustomForeColor; }
set { useCustomForeColor = value; }
}
/// <summary>
/// The use style colors
/// </summary>
private bool useStyleColors = false;
/// <summary>
/// Gets or sets a value indicating whether [use style colors].
/// </summary>
/// <value><c>true</c> if [use style colors]; otherwise, <c>false</c>.</value>
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseStyleColors
{
get { return useStyleColors; }
set { useStyleColors = value; }
}
/// <summary>
/// Gets or sets a value indicating whether [use selectable].
/// </summary>
/// <value><c>true</c> if [use selectable]; otherwise, <c>false</c>.</value>
[Browsable(false)]
[Category(MetroDefaults.PropertyCategory.Behaviour)]
[DefaultValue(false)]
public bool UseSelectable
{
get { return GetStyle(ControlStyles.Selectable); }
set { SetStyle(ControlStyles.Selectable, value); }
}
/// <summary>
/// Gets or sets a value indicating whether [allow close].
/// </summary>
/// <value><c>true</c> if [allow close]; otherwise, <c>false</c>.</value>
[Browsable(true)]
[Category(MetroDefaults.PropertyCategory.Behaviour)]
[DefaultValue(false)]
public bool AllowClose { get; set; }
#endregion
#region Fields
//Additional variables to be used by HideTab and ShowTab
/// <summary>
/// The tab disable
/// </summary>
private List<string> tabDisable = new List<string>();
/// <summary>
/// The tab order
/// </summary>
private List<string> tabOrder = new List<string>();
/// <summary>
/// The hid tabs
/// </summary>
private List<HiddenTabs> hidTabs = new List<HiddenTabs>();
/// <summary>
/// The sc up down
/// </summary>
private SubClass scUpDown = null;
/// <summary>
/// The b up down
/// </summary>
private bool bUpDown = false;
/// <summary>
/// The tab bottom border height
/// </summary>
private const int TabBottomBorderHeight = 3;
/// <summary>
/// The close button offset
/// </summary>
private const int CloseButtonOffset = 8;
/// <summary>
/// The metro label size
/// </summary>
private MetroTabControlSize metroLabelSize = MetroTabControlSize.Medium;
/// <summary>
/// Gets or sets the size of the font.
/// </summary>
/// <value>The size of the font.</value>
[DefaultValue(MetroTabControlSize.Medium)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroTabControlSize FontSize
{
get { return metroLabelSize; }
set { metroLabelSize = value; }
}
/// <summary>
/// The metro label weight
/// </summary>
private MetroTabControlWeight metroLabelWeight = MetroTabControlWeight.Light;
/// <summary>
/// Gets or sets the font weight.
/// </summary>
/// <value>The font weight.</value>
[DefaultValue(MetroTabControlWeight.Light)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroTabControlWeight FontWeight
{
get { return metroLabelWeight; }
set { metroLabelWeight = value; }
}
/// <summary>
/// The text align
/// </summary>
private ContentAlignment textAlign = ContentAlignment.MiddleLeft;
/// <summary>
/// Gets or sets the text align.
/// </summary>
/// <value>The text align.</value>
[DefaultValue(ContentAlignment.MiddleLeft)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public ContentAlignment TextAlign
{
get
{
return textAlign;
}
set
{
textAlign = value;
}
}
/// <summary>
/// Gets the collection of tab pages in this tab control.
/// </summary>
/// <value>The tab pages.</value>
[Editor("MetroFramework.Design.MetroTabPageCollectionEditor, " + AssemblyRef.MetroFrameworkDesignSN, typeof(UITypeEditor))]
public new TabPageCollection TabPages
{
get
{
return base.TabPages;
}
}
/// <summary>
/// The is mirrored
/// </summary>
private bool isMirrored;
/// <summary>
/// Gets a value indicating whether the control is mirrored.
/// </summary>
/// <value><c>true</c> if this instance is mirrored; otherwise, <c>false</c>.</value>
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public new bool IsMirrored
{
get
{
return isMirrored;
}
set
{
if (isMirrored == value)
{
return;
}
isMirrored = value;
UpdateStyles();
}
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="MetroTabControl"/> class.
/// </summary>
public MetroTabControl()
{
SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor, true);
Padding = new Point(10, 8);
this.Selecting += MetroTabControl_Selecting;
}
#endregion
#region Paint Methods
/// <summary>
/// Handles the <see cref="E:PaintBackground" /> event.
/// </summary>
/// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
try
{
Color backColor = BackColor;
if (!useCustomBackColor)
{
backColor = MetroPaint.BackColor.Form(Theme);
}
if (backColor.A == 255 && BackgroundImage == null)
{
e.Graphics.Clear(backColor);
return;
}
base.OnPaintBackground(e);
OnCustomPaintBackground(new MetroPaintEventArgs(backColor, Color.Empty, e.Graphics));
}
catch
{
Invalidate();
}
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.Paint" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs" /> that contains the event data.</param>
protected override void OnPaint(PaintEventArgs e)
{
try
{
if (GetStyle(ControlStyles.AllPaintingInWmPaint))
{
OnPaintBackground(e);
}
OnCustomPaint(new MetroPaintEventArgs(Color.Empty, Color.Empty, e.Graphics));
OnPaintForeground(e);
}
catch
{
Invalidate();
}
}
/// <summary>
/// Handles the <see cref="E:PaintForeground" /> event.
/// </summary>
/// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
protected virtual void OnPaintForeground(PaintEventArgs e)
{
for (var index = 0; index < TabPages.Count; index++)
{
if (index != SelectedIndex)
{
DrawTab(index, e.Graphics);
}
}
if (SelectedIndex <= -1)
{
return;
}
DrawTabBottomBorder(SelectedIndex, e.Graphics);
DrawTab(SelectedIndex, e.Graphics);
DrawTabSelected(SelectedIndex, e.Graphics);
OnCustomPaintForeground(new MetroPaintEventArgs(Color.Empty, Color.Empty, e.Graphics));
}
/// <summary>
/// Draws the tab bottom border.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="graphics">The graphics.</param>
private void DrawTabBottomBorder(int index, Graphics graphics)
{
using (Brush bgBrush = new SolidBrush(MetroPaint.BorderColor.TabControl.Normal(Theme)))
{
Rectangle borderRectangle = new Rectangle(DisplayRectangle.X, GetTabRect(index).Bottom + 2 - TabBottomBorderHeight, DisplayRectangle.Width, TabBottomBorderHeight);
graphics.FillRectangle(bgBrush, borderRectangle);
}
}
/// <summary>
/// Draws the tab selected.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="graphics">The graphics.</param>
private void DrawTabSelected(int index, Graphics graphics)
{
using (Brush selectionBrush = new SolidBrush(MetroPaint.GetStyleColor(Style)))
{
Rectangle selectedTabRect = GetTabRect(index);
Rectangle borderRectangle = new Rectangle(selectedTabRect.X + ((index == 0) ? 2 : 0), GetTabRect(index).Bottom + 2 - TabBottomBorderHeight, selectedTabRect.Width + ((index == 0) ? 0 : 2), TabBottomBorderHeight);
graphics.FillRectangle(selectionBrush, borderRectangle);
}
}
/// <summary>
/// Measures the text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>Size.</returns>
private Size MeasureText(string text)
{
Size preferredSize;
using (Graphics g = CreateGraphics())
{
Size proposedSize = new Size(int.MaxValue, int.MaxValue);
preferredSize = TextRenderer.MeasureText(g, text, MetroFonts.TabControl(metroLabelSize, metroLabelWeight),
proposedSize,
MetroPaint.GetTextFormatFlags(TextAlign) |
TextFormatFlags.NoPadding);
}
return preferredSize;
}
/// <summary>
/// Draws the tab.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="graphics">The graphics.</param>
private void DrawTab(int index, Graphics graphics)
{
Color foreColor;
Color backColor = BackColor;
if (!useCustomBackColor)
{
backColor = MetroPaint.BackColor.Form(Theme);
}
TabPage tabPage = TabPages[index];
Rectangle tabRect = GetTabRect(index);
if (!Enabled || tabDisable.Contains(tabPage.Name))
{
foreColor = MetroPaint.ForeColor.Label.Disabled(Theme);
}
else
{
if (useCustomForeColor)
{
foreColor = DefaultForeColor;
}
else
{
foreColor = !useStyleColors ? MetroPaint.ForeColor.TabControl.Normal(Theme) : MetroPaint.GetStyleColor(Style);
}
}
if (index == 0)
{
tabRect.X = DisplayRectangle.X;
}
Rectangle bgRect = tabRect;
tabRect.Width += 20;
using (Brush bgBrush = new SolidBrush(backColor))
{
graphics.FillRectangle(bgBrush, bgRect);
}
TextRenderer.DrawText(graphics, tabPage.Text, MetroFonts.TabControl(metroLabelSize, metroLabelWeight),
tabRect, foreColor, backColor, MetroPaint.GetTextFormatFlags(TextAlign));
if (CanCloseTab((MetroTabPage)tabPage))
DrawCloseButton(graphics, bgRect);
}
/// <summary>
/// Draws the close button.
/// </summary>
/// <param name="graphics">The graphics.</param>
/// <param name="tabRectangle">The tab rectangle.</param>
private void DrawCloseButton(Graphics graphics, Rectangle tabRectangle)
{
var rectangle = GetCloseButtonRectangle(tabRectangle);
using (var pen = GetCloseButtonPen(rectangle))
{
graphics.DrawLine(pen, rectangle.X, rectangle.Y, rectangle.X + CloseButtonOffset, rectangle.Y + CloseButtonOffset);
graphics.DrawLine(pen, rectangle.X + CloseButtonOffset, rectangle.Y, rectangle.X, rectangle.Y + CloseButtonOffset);
}
}
/// <summary>
/// Gets the close button pen.
/// </summary>
/// <param name="closeRectangle">The close rectangle.</param>
/// <returns>Pen.</returns>
private Pen GetCloseButtonPen(Rectangle closeRectangle)
{
Color foreColor = IsInCloseButtonArea(closeRectangle, PointToClient(MousePosition))
? MetroPaint.GetStyleColor(Style)
: MetroPaint.ForeColor.TabControl.Disabled(Theme);
return new Pen(foreColor, 2.8F);
}
/// <summary>
/// Draws up down.
/// </summary>
/// <param name="graphics">The graphics.</param>
private void DrawUpDown(Graphics graphics)
{
Color backColor = Parent != null ? Parent.BackColor : MetroPaint.BackColor.Form(Theme);
Rectangle borderRect = new Rectangle();
WinApi.GetClientRect(scUpDown.Handle, ref borderRect);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.Clear(backColor);
using (Brush b = new SolidBrush(MetroPaint.BorderColor.TabControl.Normal(Theme)))
{
GraphicsPath gp = new GraphicsPath(FillMode.Winding);
PointF[] pts = { new PointF(6, 6), new PointF(16, 0), new PointF(16, 12) };
gp.AddLines(pts);
graphics.FillPath(b, gp);
gp.Reset();
PointF[] pts2 = { new PointF(borderRect.Width - 15, 0), new PointF(borderRect.Width - 5, 6), new PointF(borderRect.Width - 15, 12) };
gp.AddLines(pts2);
graphics.FillPath(b, gp);
gp.Dispose();
}
}
#endregion
#region Overridden Methods
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.EnabledChanged" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
Invalidate();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.BackColorChanged" /> event when the <see cref="P:System.Windows.Forms.Control.BackColor" /> property value of the control's container changes.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
protected override void OnParentBackColorChanged(EventArgs e)
{
base.OnParentBackColorChanged(e);
Invalidate();
}
/// <summary>
/// This member overrides <see cref="M:System.Windows.Forms.Control.OnResize(System.EventArgs)" />.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
/// <summary>
/// This member overrides <see cref="M:System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message@)" />.
/// </summary>
/// <param name="m">A Windows Message Object.</param>
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (!DesignMode)
{
WinApi.ShowScrollBar(Handle, (int)WinApi.ScrollBar.SB_BOTH, 0);
}
}
/// <summary>
/// This member overrides <see cref="P:System.Windows.Forms.Control.CreateParams" />.
/// </summary>
/// <value>The create parameters.</value>
protected override CreateParams CreateParams
{
//[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
const int WS_EX_LAYOUTRTL = 0x400000;
const int WS_EX_NOINHERITLAYOUT = 0x100000;
var cp = base.CreateParams;
if (isMirrored)
{
cp.ExStyle = cp.ExStyle | WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT;
}
return cp;
}
}
/// <summary>
/// Returns the bounding rectangle for a specified tab in this tab control.
/// </summary>
/// <param name="index">The zero-based index of the tab you want.</param>
/// <returns>A <see cref="T:System.Drawing.Rectangle" /> that represents the bounds of the specified tab.</returns>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
/// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
private new Rectangle GetTabRect(int index)
{
if (index < 0)
return new Rectangle();
Rectangle baseRect = base.GetTabRect(index);
return baseRect;
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.MouseWheel" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs" /> that contains the event data.</param>
protected override void OnMouseWheel(MouseEventArgs e)
{
if (SelectedIndex != -1)
{
if (!TabPages[SelectedIndex].Focused)
{
bool subControlFocused = false;
foreach (Control ctrl in TabPages[SelectedIndex].Controls)
{
if (ctrl.Focused)
{
subControlFocused = true;
return;
}
}
if (!subControlFocused)
{
TabPages[SelectedIndex].Select();
TabPages[SelectedIndex].Focus();
}
}
}
base.OnMouseWheel(e);
}
/// <summary>
/// Raises the <see cref="M:System.Windows.Forms.Control.CreateControl" /> method.
/// </summary>
protected override void OnCreateControl()
{
base.OnCreateControl();
this.OnFontChanged(EventArgs.Empty);
FindUpDown();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.ControlAdded" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.ControlEventArgs" /> that contains the event data.</param>
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
FindUpDown();
UpdateUpDown();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.ControlRemoved" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.ControlEventArgs" /> that contains the event data.</param>
protected override void OnControlRemoved(ControlEventArgs e)
{
base.OnControlRemoved(e);
FindUpDown();
UpdateUpDown();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TabControl.SelectedIndexChanged" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged(e);
UpdateUpDown();
Invalidate();
}
//send font change to properly resize tab page header rects
//http://www.codeproject.com/Articles/13305/Painting-Your-Own-Tabs?msg=2707590#xx2707590xx
/// <summary>
/// Sends the message.
/// </summary>
/// <param name="hWnd">The h WND.</param>
/// <param name="Msg">The MSG.</param>
/// <param name="wParam">The w parameter.</param>
/// <param name="lParam">The l parameter.</param>
/// <returns>IntPtr.</returns>
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// The w m_ setfont
/// </summary>
private const int WM_SETFONT = 0x30;
/// <summary>
/// The w m_ fontchange
/// </summary>
private const int WM_FONTCHANGE = 0x1d;
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.FontChanged" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
IntPtr hFont = MetroFonts.TabControl(metroLabelSize, metroLabelWeight).ToHfont();
SendMessage(this.Handle, WM_SETFONT, hFont, (IntPtr)(-1));
SendMessage(this.Handle, WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
this.UpdateStyles();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.MouseDown" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs" /> that contains the event data.</param>
protected override void OnMouseDown(MouseEventArgs e)
{
MetroTabPage page = GetTabPageAtPoint(e.Location);
if (CanCloseTab(page) && IsCloseButtonClick(page, e.Location))
CloseTabPage(page);
base.OnMouseDown(e);
}
/// <summary>
/// The _hover tab
/// </summary>
private MetroTabPage _hoverTab;
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.MouseMove" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs" /> that contains the event data.</param>
protected override void OnMouseMove(MouseEventArgs e)
{
SetHoverTab(GetTabPageAtPoint(e.Location));
base.OnMouseMove(e);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.MouseLeave" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
protected override void OnMouseLeave(EventArgs e)
{
SetHoverTab(null);
base.OnMouseLeave(e);
}
/// <summary>
/// Sets the hover tab.
/// </summary>
/// <param name="page">The page.</param>
private void SetHoverTab(MetroTabPage page)
{
_hoverTab = page;
if (DesignMode)
return;
Invalidate();
}
/// <summary>
/// Determines whether [is close button click] [the specified page].
/// </summary>
/// <param name="page">The page.</param>
/// <param name="location">The location.</param>
/// <returns><c>true</c> if [is close button click] [the specified page]; otherwise, <c>false</c>.</returns>
private bool IsCloseButtonClick(MetroTabPage page, Point location)
{
var index = TabPages.IndexOf(page);
var rectangle = GetTabRect(index);
var closeRectagle = GetCloseButtonRectangle(rectangle);
return IsInCloseButtonArea(closeRectagle, location);
}
/// <summary>
/// Gets the close button rectangle.
/// </summary>
/// <param name="tabRectangle">The tab rectangle.</param>
/// <returns>Rectangle.</returns>
private static Rectangle GetCloseButtonRectangle(Rectangle tabRectangle)
{
var closeRectangle = tabRectangle;
closeRectangle.Offset(closeRectangle.Width - 2 * CloseButtonOffset + CloseButtonOffset / 2, CloseButtonOffset);
closeRectangle.Size = new Size(CloseButtonOffset, CloseButtonOffset);
return closeRectangle;
}
/// <summary>
/// Determines whether [is in close button area] [the specified rectangle].
/// </summary>
/// <param name="rectangle">The rectangle.</param>
/// <param name="location">The location.</param>
/// <returns><c>true</c> if [is in close button area] [the specified rectangle]; otherwise, <c>false</c>.</returns>
private static bool IsInCloseButtonArea(Rectangle rectangle, Point location)
{
var center = new Point(
(rectangle.Left + rectangle.Right) / 2,
(rectangle.Top + rectangle.Bottom) / 2);
double distance = Math.Sqrt(
Math.Pow(center.X - location.X, 2) +
Math.Pow(center.Y - location.Y, 2));
return distance <= 1.2 * CloseButtonOffset;
}
/// <summary>
/// Closes the tab page.
/// </summary>
/// <param name="page">The page.</param>
private void CloseTabPage(MetroTabPage page)
{
TabPages.Remove(page);
OnTabPageClosed(page);
}
/// <summary>
/// Called when [tab page closed].
/// </summary>
/// <param name="page">The page.</param>
protected virtual void OnTabPageClosed(MetroTabPage page)
{
var pageClosed = TabPageClosed;
if (pageClosed != null)
pageClosed(this, new TabPageClosedEventArgs(page));
}
/// <summary>
/// Determines whether this instance [can close tab] the specified tab page.
/// </summary>
/// <param name="tabPage">The tab page.</param>
/// <returns><c>true</c> if this instance [can close tab] the specified tab page; otherwise, <c>false</c>.</returns>
private bool CanCloseTab(MetroTabPage tabPage)
{
if (tabPage == null)
return false;
if (!tabPage.AllowClose)
return false;
return tabPage == _hoverTab || tabPage == SelectedTab;
}
/// <summary>
/// Gets the tab page at point.
/// </summary>
/// <param name="location">The location.</param>
/// <returns>MetroTabPage.</returns>
private MetroTabPage GetTabPageAtPoint(Point location)
{
for (int i = 0; i < TabPages.Count; i++)
if (GetTabRect(i).Contains(location))
return (MetroTabPage)TabPages[i];
return null;
}
/// <summary>
/// Handles the Selecting event of the MetroTabControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="TabControlCancelEventArgs"/> instance containing the event data.</param>
void MetroTabControl_Selecting(object sender, TabControlCancelEventArgs e)
{
if (tabDisable.Count > 0 && tabDisable.Contains(e.TabPage.Name))
{
e.Cancel = true;
}
}
#endregion
#region Helper Methods
/// <summary>
/// Finds up down.
/// </summary>
private void FindUpDown()
{
if (!DesignMode)
{
bool bFound = false;
IntPtr pWnd = WinApi.GetWindow(Handle, WinApi.GW_CHILD);
while (pWnd != IntPtr.Zero)
{
char[] className = new char[33];
int length = WinApi.GetClassName(pWnd, className, 32);
string s = new string(className, 0, length);
if (s == "msctls_updown32")
{
bFound = true;
if (!bUpDown)
{
this.scUpDown = new SubClass(pWnd, true);
this.scUpDown.SubClassedWndProc += new SubClass.SubClassWndProcEventHandler(scUpDown_SubClassedWndProc);
bUpDown = true;
}
break;
}
pWnd = WinApi.GetWindow(pWnd, WinApi.GW_HWNDNEXT);
}
if ((!bFound) && (bUpDown))
bUpDown = false;
}
}
/// <summary>
/// Updates up down.
/// </summary>
private void UpdateUpDown()
{
if (bUpDown && !DesignMode)
{
if (WinApi.IsWindowVisible(scUpDown.Handle))
{
Rectangle rect = new Rectangle();
WinApi.GetClientRect(scUpDown.Handle, ref rect);
WinApi.InvalidateRect(scUpDown.Handle, ref rect, true);
}
}
}
/// <summary>
/// Scs up down_ sub classed WND proc.
/// </summary>
/// <param name="m">The m.</param>
/// <returns>System.Int32.</returns>
private int scUpDown_SubClassedWndProc(ref Message m)
{
switch (m.Msg)
{
case (int)WinApi.Messages.WM_PAINT:
IntPtr hDC = WinApi.GetWindowDC(scUpDown.Handle);
Graphics g = Graphics.FromHdc(hDC);
DrawUpDown(g);
g.Dispose();
WinApi.ReleaseDC(scUpDown.Handle, hDC);
m.Result = IntPtr.Zero;
Rectangle rect = new Rectangle();
WinApi.GetClientRect(scUpDown.Handle, ref rect);
WinApi.ValidateRect(scUpDown.Handle, ref rect);
return 1;
}
return 0;
}
#endregion
#region Additional functions by DenRic Denise
/// <summary>
/// This will hide MetroTabPage from MetroTabControl
/// Hidden MetroTabPage can be displayed by calling ShowTab functions
/// </summary>
/// <param name="tabpage">The tabpage.</param>
public void HideTab(MetroTabPage tabpage)
{
if (this.TabPages.Contains(tabpage))
{
int _tabid = this.TabPages.IndexOf(tabpage);
hidTabs.Add(new HiddenTabs(_tabid, tabpage.Name));
this.TabPages.Remove(tabpage);
}
}
/// <summary>
/// This will show hiddent MetroTabPage from MetroTabControl
/// </summary>
/// <param name="tabpage">The tabpage.</param>
public void ShowTab(MetroTabPage tabpage)
{
HiddenTabs result = hidTabs.Find(
delegate(HiddenTabs bk)
{
return bk.tabpage == tabpage.Name;
}
);
if (result != null)
{
this.TabPages.Insert(result.index,tabpage);
hidTabs.Remove(result);
}
}
/// <summary>
/// This will disable a MetroTabPage from MetroTabControl
/// </summary>
/// <param name="tabpage">The tabpage.</param>
public void DisableTab(MetroTabPage tabpage)
{
if (!tabDisable.Contains(tabpage.Name))
{
if (this.SelectedTab == tabpage && this.TabCount == 1) return;
if (this.SelectedTab == tabpage)
{
if (SelectedIndex == this.TabCount - 1)
{ SelectedIndex = 0; }
else { SelectedIndex++; }
}
int _tabid = this.TabPages.IndexOf(tabpage);
tabDisable.Add(tabpage.Name);
Graphics e = this.CreateGraphics();
DrawTab(_tabid, e);
DrawTabBottomBorder(SelectedIndex, e);
DrawTabSelected(SelectedIndex, e);
}
}
/// <summary>
/// This will enable a MetroTabPage from MetroTabControl
/// </summary>
/// <param name="tabpage">The tabpage.</param>
public void EnableTab(MetroTabPage tabpage)
{
if (tabDisable.Contains(tabpage.Name))
{
tabDisable.Remove(tabpage.Name);
int _tabid = this.TabPages.IndexOf(tabpage);
Graphics e = this.CreateGraphics();
DrawTab(_tabid, e);
DrawTabBottomBorder(SelectedIndex, e);
DrawTabSelected(SelectedIndex, e);
}
}
/// <summary>
/// This will check if MetroTabPage is enable or not
/// true if enable otherwise false
/// </summary>
/// <param name="tabpage">The tabpage.</param>
/// <returns><c>true</c> if [is tab enable] [the specified tabpage]; otherwise, <c>false</c>.</returns>
public bool IsTabEnable(MetroTabPage tabpage)
{
return tabDisable.Contains(tabpage.Name);
}
/// <summary>
/// This will check if MetroTabPage is hidden or not
/// true if hidden otherwise false
/// </summary>
/// <param name="tabpage">The tabpage.</param>
/// <returns><c>true</c> if [is tab hidden] [the specified tabpage]; otherwise, <c>false</c>.</returns>
public bool IsTabHidden(MetroTabPage tabpage)
{
HiddenTabs result = hidTabs.Find(
delegate(HiddenTabs bk)
{
return bk.tabpage == tabpage.Name;
}
);
return (result != null);
}
#endregion
}
}
| |
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
//
// NServiceKit: Useful extensions to simplify parsing xml with XLinq
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of reddis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
namespace NServiceKit.ServiceModel.Extensions
{
/// <summary>A linq extensions.</summary>
public static class XLinqExtensions
{
/// <summary>An XElement extension method that gets a string.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The string.</returns>
public static string GetString(this XElement el, string name)
{
return el == null ? null : GetElementValueOrDefault(el, name, x => x.Value);
}
/// <summary>An XElement extension method that gets a bool.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool GetBool(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (bool)GetElement(el, name);
}
/// <summary>An XElement extension method that gets bool or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool GetBoolOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (bool)x);
}
/// <summary>An XElement extension method that gets nullable bool.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable bool.</returns>
public static bool? GetNullableBool(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (bool?)childEl;
}
/// <summary>An XElement extension method that gets an int.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The int.</returns>
public static int GetInt(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (int)GetElement(el, name);
}
/// <summary>An XElement extension method that gets int or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The int or default.</returns>
public static int GetIntOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (int) x);
}
/// <summary>An XElement extension method that gets nullable int.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable int.</returns>
public static int? GetNullableInt(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (int?) childEl;
}
/// <summary>An XElement extension method that gets a long.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The long.</returns>
public static long GetLong(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (long)GetElement(el, name);
}
/// <summary>An XElement extension method that gets long or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The long or default.</returns>
public static long GetLongOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (long)x);
}
/// <summary>An XElement extension method that gets nullable long.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable long.</returns>
public static long? GetNullableLong(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (long?)childEl;
}
/// <summary>An XElement extension method that gets a decimal.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The decimal.</returns>
public static decimal GetDecimal(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (decimal)GetElement(el, name);
}
/// <summary>An XElement extension method that gets decimal or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The decimal or default.</returns>
public static decimal GetDecimalOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (decimal)x);
}
/// <summary>An XElement extension method that gets nullable decimal.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable decimal.</returns>
public static decimal? GetNullableDecimal(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (decimal?)childEl;
}
/// <summary>An XElement extension method that gets date time.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The date time.</returns>
public static DateTime GetDateTime(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (DateTime)GetElement(el, name);
}
/// <summary>An XElement extension method that gets date time or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The date time or default.</returns>
public static DateTime GetDateTimeOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (DateTime)x);
}
/// <summary>An XElement extension method that gets nullable date time.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable date time.</returns>
public static DateTime? GetNullableDateTime(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (DateTime?)childEl;
}
/// <summary>An XElement extension method that gets time span.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The time span.</returns>
public static TimeSpan GetTimeSpan(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (TimeSpan)GetElement(el, name);
}
/// <summary>An XElement extension method that gets time span or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The time span or default.</returns>
public static TimeSpan GetTimeSpanOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (TimeSpan)x);
}
/// <summary>An XElement extension method that gets nullable time span.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable time span.</returns>
public static TimeSpan? GetNullableTimeSpan(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (TimeSpan?)childEl;
}
/// <summary>An XElement extension method that gets a unique identifier.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The unique identifier.</returns>
public static Guid GetGuid(this XElement el, string name)
{
AssertElementHasValue(el, name);
return (Guid)GetElement(el, name);
}
/// <summary>An XElement extension method that gets unique identifier or default.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The unique identifier or default.</returns>
public static Guid GetGuidOrDefault(this XElement el, string name)
{
return GetElementValueOrDefault(el, name, x => (Guid)x);
}
/// <summary>An XElement extension method that gets nullable unique identifier.</summary>
///
/// <param name="el"> The el to act on.</param>
/// <param name="name">The name.</param>
///
/// <returns>The nullable unique identifier.</returns>
public static Guid? GetNullableGuid(this XElement el, string name)
{
var childEl = GetElement(el, name);
return childEl == null || string.IsNullOrEmpty(childEl.Value) ? null : (Guid?)childEl;
}
/// <summary>An XElement extension method that gets element value or default.</summary>
///
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="element"> The element to act on.</param>
/// <param name="name"> The name.</param>
/// <param name="converter">The converter.</param>
///
/// <returns>The element value or default.</returns>
public static T GetElementValueOrDefault<T>(this XElement element, string name, Func<XElement, T> converter)
{
if (converter == null)
{
throw new ArgumentNullException("converter");
}
var el = GetElement(element, name);
return el == null || string.IsNullOrEmpty(el.Value) ? default(T) : converter(el);
}
/// <summary>An XElement extension method that gets an element.</summary>
///
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
///
/// <param name="element">The element to act on.</param>
/// <param name="name"> The name.</param>
///
/// <returns>The element.</returns>
public static XElement GetElement(this XElement element, string name)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return element.AnyElement(name);
}
/// <summary>An XElement extension method that assert element has value.</summary>
///
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
///
/// <param name="element">The element to act on.</param>
/// <param name="name"> The name.</param>
public static void AssertElementHasValue(this XElement element, string name)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
var childEl = element.AnyElement(name);
if (childEl == null || string.IsNullOrEmpty(childEl.Value))
{
throw new ArgumentNullException(name, string.Format("{0} is required", name));
}
}
/// <summary>An IEnumerable<XElement> extension method that gets the values.</summary>
///
/// <param name="els">The els to act on.</param>
///
/// <returns>The values.</returns>
public static List<string> GetValues(this IEnumerable<XElement> els)
{
var values = new List<string>();
foreach (var el in els)
{
values.Add(el.Value);
}
return values;
}
/// <summary>An XElement extension method that any attribute.</summary>
///
/// <param name="element">The element to act on.</param>
/// <param name="name"> The name.</param>
///
/// <returns>An XAttribute.</returns>
public static XAttribute AnyAttribute(this XElement element, string name)
{
if (element == null) return null;
foreach (var attribute in element.Attributes())
{
if (attribute.Name.LocalName == name)
{
return attribute;
}
}
return null;
}
/// <summary>Enumerates all elements in this collection.</summary>
///
/// <param name="element">The element to act on.</param>
/// <param name="name"> The name.</param>
///
/// <returns>An enumerator that allows foreach to be used to process all elements in this collection.</returns>
public static IEnumerable<XElement> AllElements(this XElement element, string name)
{
var els = new List<XElement>();
if (element == null) return els;
foreach (var node in element.Nodes())
{
if (node.NodeType != XmlNodeType.Element) continue;
var childEl = (XElement)node;
if (childEl.Name.LocalName == name)
{
els.Add(childEl);
}
}
return els;
}
/// <summary>An IEnumerable<XElement> extension method that any element.</summary>
///
/// <param name="element">The element to act on.</param>
/// <param name="name"> The name.</param>
///
/// <returns>An XElement.</returns>
public static XElement AnyElement(this XElement element, string name)
{
if (element == null) return null;
foreach (var node in element.Nodes())
{
if (node.NodeType != XmlNodeType.Element) continue;
var childEl = (XElement)node;
if (childEl.Name.LocalName == name)
{
return childEl;
}
}
return null;
}
/// <summary>An IEnumerable<XElement> extension method that any element.</summary>
///
/// <param name="elements">The elements to act on.</param>
/// <param name="name"> The name.</param>
///
/// <returns>An XElement.</returns>
public static XElement AnyElement(this IEnumerable<XElement> elements, string name)
{
foreach (var element in elements)
{
if (element.Name.LocalName == name)
{
return element;
}
}
return null;
}
/// <summary>Enumerates all elements in this collection.</summary>
///
/// <param name="elements">The elements to act on.</param>
/// <param name="name"> The name.</param>
///
/// <returns>An enumerator that allows foreach to be used to process all elements in this collection.</returns>
public static IEnumerable<XElement> AllElements(this IEnumerable<XElement> elements, string name)
{
var els = new List<XElement>();
foreach (var element in elements)
{
els.AddRange(AllElements(element, name));
}
return els;
}
/// <summary>An XElement extension method that first element.</summary>
///
/// <param name="element">The element to act on.</param>
///
/// <returns>An XElement.</returns>
public static XElement FirstElement(this XElement element)
{
if (element.FirstNode.NodeType == XmlNodeType.Element)
{
return (XElement) element.FirstNode;
}
return null;
}
}
}
#endif
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Internal;
namespace Boo.Lang.Compiler.Steps
{
public class ResolveImports : AbstractTransformerCompilerStep
{
private readonly Dictionary<string, Import> _namespaces = new Dictionary<string, Import>();
override public void Run()
{
NameResolutionService.Reset();
Visit(CompileUnit.Modules);
}
override public void OnModule(Module module)
{
Visit(module.Imports);
_namespaces.Clear();
}
public override void OnImport(Import import)
{
if (IsAlreadyBound(import))
return;
if (import.AssemblyReference != null)
{
ImportFromAssemblyReference(import);
return;
}
var entity = ResolveImport(import);
if (HandledAsImportError(import, entity) || HandledAsDuplicatedNamespace(import))
return;
Context.TraceInfo("{1}: import reference '{0}' bound to {2}.", import, import.LexicalInfo, entity);
import.Entity = ImportedNamespaceFor(import, entity);
}
private bool HandledAsImportError(Import import, IEntity entity)
{
if (entity == null)
{
ImportError(import, CompilerErrorFactory.InvalidNamespace(import));
return true;
}
if (!IsValidImportTarget(entity))
{
ImportError(import, CompilerErrorFactory.NotANamespace(import, entity));
return true;
}
return false;
}
private void ImportError(Import import, CompilerError error)
{
Errors.Add(error);
BindError(import);
}
private void BindError(Import import)
{
Bind(import, Error.Default);
}
private static string EffectiveNameForImportedNamespace(Import import)
{
return null != import.Alias ? import.Alias.Name : import.Namespace;
}
private bool HandledAsDuplicatedNamespace(Import import)
{
var actualName = EffectiveNameForImportedNamespace(import);
//only add unique namespaces
Import cachedImport;
if (!_namespaces.TryGetValue(actualName, out cachedImport))
{
_namespaces[actualName] = import;
return false;
}
//ignore for partial classes in separate files
if (cachedImport.LexicalInfo.FileName == import.LexicalInfo.FileName)
Warnings.Add(CompilerWarningFactory.DuplicateNamespace(import, import.Namespace));
BindError(import);
return true;
}
private IEntity ImportedNamespaceFor(Import import, IEntity entity)
{
var ns = entity as INamespace;
if (ns == null)
return entity;
var selectiveImportSpec = import.Expression as MethodInvocationExpression;
var imported = selectiveImportSpec != null ? SelectiveImportFor(ns, selectiveImportSpec) : ns;
var actualNamespace = null != import.Alias ? AliasedNamespaceFor(imported, import) : imported;
return new ImportedNamespace(import, actualNamespace);
}
private INamespace SelectiveImportFor(INamespace ns, MethodInvocationExpression selectiveImportSpec)
{
var importedNames = selectiveImportSpec.Arguments;
var entities = new List<IEntity>(importedNames.Count);
foreach (ReferenceExpression nameExpression in importedNames)
{
var name = nameExpression.Name;
if (!ns.Resolve(entities, name, EntityType.Any))
Errors.Add(
CompilerErrorFactory.MemberNotFound(
nameExpression, name, ns, NameResolutionService.GetMostSimilarMemberName(ns, name, EntityType.Any)));
}
return new SimpleNamespace(null, entities);
}
private static INamespace AliasedNamespaceFor(IEntity entity, Import import)
{
var aliasedNamespace = new AliasedNamespace(import.Alias.Name, entity);
import.Alias.Entity = aliasedNamespace;
return aliasedNamespace;
}
private void ImportFromAssemblyReference(Import import)
{
var resolvedNamespace = ResolveImportAgainstReferencedAssembly(import);
if (HandledAsImportError(import, resolvedNamespace))
return;
if (HandledAsDuplicatedNamespace(import))
return;
import.Entity = ImportedNamespaceFor(import, resolvedNamespace);
}
private IEntity ResolveImportAgainstReferencedAssembly(Import import)
{
return NameResolutionService.ResolveQualifiedName(GetBoundReference(import.AssemblyReference).RootNamespace, import.Namespace);
}
private static bool IsAlreadyBound(Import import)
{
return import.Entity != null;
}
private IEntity ResolveImport(Import import)
{
var entity = ResolveImportOnParentNamespace(import) ?? NameResolutionService.ResolveQualifiedName(import.Namespace);
if (null != entity)
return entity;
//if 'import X', try 'import X from X'
if (!TryAutoAddAssemblyReference(import))
return null;
return NameResolutionService.ResolveQualifiedName(import.Namespace);
}
private IEntity ResolveImportOnParentNamespace(Import import)
{
var current = NameResolutionService.CurrentNamespace;
try
{
INamespace parentNamespace = NameResolutionService.CurrentNamespace.ParentNamespace;
if (parentNamespace != null)
{
NameResolutionService.EnterNamespace(parentNamespace);
return NameResolutionService.ResolveQualifiedName(import.Namespace);
}
}
finally
{
NameResolutionService.EnterNamespace(current);
}
return null;
}
private bool TryAutoAddAssemblyReference(Import import)
{
var existingReference = Parameters.FindAssembly(import.Namespace);
if (existingReference != null)
return false;
var asm = TryToLoadAssemblyContainingNamespace(import.Namespace);
if (asm == null)
return false;
Parameters.References.Add(asm);
import.AssemblyReference = new ReferenceExpression(import.LexicalInfo, asm.FullName).WithEntity(asm);
NameResolutionService.ClearResolutionCacheFor(asm.Name);
return true;
}
private ICompileUnit TryToLoadAssemblyContainingNamespace(string @namespace)
{
ICompileUnit asm = Parameters.LoadAssembly(@namespace, false);
if (asm != null)
return asm;
//try to load assemblies name after the parent namespaces
var namespaces = @namespace.Split('.');
if (namespaces.Length == 1)
return null;
for (var level = namespaces.Length - 1; level > 0; level--)
{
var parentNamespace = string.Join(".", namespaces, 0, level);
var existingReference = Parameters.FindAssembly(parentNamespace);
if (existingReference != null)
return null;
var parentNamespaceAssembly = Parameters.LoadAssembly(parentNamespace, false);
if (parentNamespaceAssembly != null)
return parentNamespaceAssembly;
}
return null;
}
private static bool IsValidImportTarget(IEntity entity)
{
var type = entity.EntityType;
return type == EntityType.Namespace || type == EntityType.Type;
}
static ICompileUnit GetBoundReference(ReferenceExpression reference)
{
return ((ICompileUnit)TypeSystemServices.GetEntity(reference));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Services_Common.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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Photogaleries.Services.Areas.HelpPage.ModelDescriptions;
using Photogaleries.Services.Areas.HelpPage.Models;
namespace Photogaleries.Services.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Text;
using LanguageExt;
using LanguageExt.ClassInstances;
using static LanguageExt.Prelude;
namespace LanguageExt.Pretty
{
/// <summary>
/// Document building functions
/// </summary>
/// <remarks>
/// Carries annotation, for unit only annotations, use `Doc`
/// </remarks>
public static class DocAnn
{
public static Doc<A> Annotate<A>(A annotation, Doc<A> doc) =>
new DocAnnotate<A>(annotation, doc);
public static Doc<A> Fail<A>() =>
DocFail<A>.Default;
public static Doc<A> Empty<A>() =>
DocEmpty<A>.Default;
public static Doc<A> Char<A>(char c) =>
c == '\n'
? LineOrSpace<A>()
: new DocChar<A>(c);
public static Doc<A> Text<A>(string text) =>
string.IsNullOrEmpty(text)
? DocEmpty<A>.Default
: text.Length == 1
? Char<A>(text[0])
: text.Contains("\n")
? text.Split('\n')
.Map(Text<A>)
.Intersperse(DocLine<A>.Default)
.Reduce(Cat<A>)
: new DocText<A>(text);
public static Doc<A> FlatAlt<A>(Doc<A> da, Doc<A> db) =>
new DocFlatAlt<A>(da, db);
public static Doc<A> Union<A>(Doc<A> da, Doc<A> db) =>
new DocFlatAlt<A>(da, db);
public static Doc<A> Cat<A>(Doc<A> da, Doc<A> db) =>
(da, db) switch
{
(DocEmpty<A>, DocEmpty<A>) => da,
(DocEmpty<A>, _) => db,
(_, DocEmpty<A>) => da,
_ => new DocCat<A>(da, db)
};
public static Doc<A> Nest<A>(int indent, Doc<A> doc) =>
indent == 0
? doc
: new DocNest<A>(indent, doc);
public static Doc<A> Column<A>(Func<int, Doc<A>> f) =>
new DocColumn<A>(f);
public static Doc<A> PageWidth<A>(Func<PageWidth, Doc<A>> f) =>
new DocPageWidth<A>(f);
public static Doc<A> Nesting<A>(Func<int, Doc<A>> f) =>
new DocNesting<A>(f);
/// <summary>
/// A hardline is always laid out as a line break, even when 'grouped or
/// when there is plenty of space. Note that it might still be simply discarded
/// if it is part of a 'FlatAlt' inside a 'Group'.
/// </summary>
public static Doc<A> HardLine<A>() =>
DocLine<A>.Default;
/// <summary>
/// LineOrSpace is a line-break, but behaves like space if the line break
/// is undone by Group
/// </summary>
public static Doc<A> LineOrSpace<A>() =>
FlatAlt(DocLine<A>.Default, Char<A>(' '));
/// <summary>
/// LineOrEmpty is a line-break, but behaves like Empty if the line break
/// is undone by Group
/// </summary>
public static Doc<A> LineOrEmpty<A>() =>
FlatAlt(DocLine<A>.Default, Empty<A>());
/// <summary>
/// softline behaves like space if the resulting output fits the page,
/// otherwise like line
/// </summary>
public static Doc<A> SoftLineOrSpace<A>() =>
Union(Char<A>(' '), DocLine<A>.Default);
/// <summary>
/// softline behaves like Empty if the resulting output fits the page,
/// otherwise like line
/// </summary>
public static Doc<A> SoftLineOrEmpty<A>() =>
Union(Empty<A>(), DocLine<A>.Default);
/// <summary>
/// Group tries laying out doc into a single line by removing the
/// contained line breaks; if this does not fit the page, or when a 'hardline'
/// within doc prevents it from being flattened, doc is laid out without any
/// changes.
///
/// The 'group' function is key to layouts that adapt to available space nicely.
/// </summary>
public static Doc<A> Group<A>(Doc<A> doc) =>
doc switch
{
DocUnion<A> _ => doc,
DocFlatAlt<A> (var a, var b) => b.ChangesUponFlattening() switch
{
Flattened<Doc<A>> (var b1) => DocAnn.Union<A>(b1, a),
AlreadyFlat<Doc<A>> => DocAnn.Union<A>(b, a),
_ => a
},
_ => doc.ChangesUponFlattening() switch
{
Flattened<Doc<A>> (var x1) => DocAnn.Union<A>(x1, doc),
_ => doc
},
};
/// <summary>
/// Align lays out the document with the nesting level set to the
/// current column. It is used for example to implement 'hang'.
///
/// As an example, we will put a document right above another one, regardless of
/// the current nesting level. Without alignment, the second line is put simply
/// below everything we've had so far,
///
/// Text("lorem") + VertSep(["ipsum", "dolor"])
///
/// lorem ipsum
/// dolor
///
/// If we add an 'Align' to the mix, the VertSep's contents all start in the
/// same column,
///
/// >>> Text("lorem") + Align (VertSep(["ipsum", "dolor"]))
/// lorem ipsum
/// dolor
/// </summary>
public static Doc<A> Align<A>(Doc<A> doc) =>
Column(k => Nesting(i => Nest(k - i, doc)));
/// <summary>
/// Hang lays out the document with a nesting level set to the
/// /current column/ plus offset. Negative values are allowed, and decrease the
/// nesting level accordingly.
///
/// >>> var doc = Reflow("Indenting these words with hang")
/// >>> PutDocW(24, ("prefix" + Hang(4, doc)))
/// prefix Indenting these
/// words with
/// hang
///
/// This differs from Nest, which is based on the /current nesting level/ plus
/// offset. When you're not sure, try the more efficient 'nest' first. In our
/// example, this would yield
///
/// >>> var doc = Reflow("Indenting these words with nest")
/// >>> PutDocW(24, "prefix" + Nest(4, doc))
/// prefix Indenting these
/// words with nest
/// </summary>
public static Doc<A> Hang<A>(int offset, Doc<A> doc) =>
Align(Nest(offset, doc));
/// <summary>
/// Indents document `indent` columns, starting from the
/// current cursor position.
///
/// >>> var doc = Reflow("The indent function indents these words!")
/// >>> PutDocW(24, ("prefix" + Indent(4, doc))
/// prefix The indent
/// function
/// indents these
/// words!
///
/// </summary>
public static Doc<A> Indent<A>(int indent, Doc<A> doc) =>
Hang(indent, Spaces<A>(indent) | doc);
/// <summary>
/// Intersperse the documents with a separator
/// </summary>
public static Doc<A> Sep<A>(Doc<A> sep, Seq<Doc<A>> docs)
{
if (docs.IsEmpty) return DocAnn.Empty<A>();
var d = docs.Head;
foreach (var doc in docs.Tail)
{
d = d | sep | doc;
}
return d;
}
/// <summary>
/// Delimit and intersperse the documents with a separator
/// </summary>
public static Doc<A> BetweenSep<A>(Doc<A> leftDelim, Doc<A> rightDelim, Doc<A> sep, Seq<Doc<A>> docs) =>
leftDelim | Sep(sep, docs) | rightDelim;
/// <summary>
/// Delimit and intersperse the documents with a separator
/// </summary>
public static Doc<A> BetweenSep<A>(Doc<A> leftDelim, Doc<A> rightDelim, Doc<A> sep, params Doc<A>[] docs) =>
BetweenSep(leftDelim, rightDelim, sep, toSeq(docs));
/// <summary>
/// Haskell-inspired array/list formatting
/// </summary>
public static Doc<A> List<A>(Seq<Doc<A>> docs) =>
Group(BetweenSep<A>(
FlatAlt<A>("[ ", "["),
FlatAlt<A>(" ]", "]"),
", ",
docs));
/// <summary>
/// Haskell-inspired tuple formatting
/// </summary>
public static Doc<A> Tuple<A>(Seq<Doc<A>> docs) =>
Group(BetweenSep<A>(
FlatAlt<A>("( ", "("),
FlatAlt<A>(" )", ")"),
", ",
docs));
/// <summary>
/// Haskell-inspired array/list formatting
/// </summary>
public static Doc<A> List<A>(params Doc<A>[] docs) =>
Group(BetweenSep<A>(
FlatAlt<A>("[ ", "["),
FlatAlt<A>(" ]", "]"),
", ",
docs));
/// <summary>
/// Haskell-inspired tuple formatting
/// </summary>
public static Doc<A> Tuple<A>(params Doc<A>[] docs) =>
Group(BetweenSep<A>(
FlatAlt<A>("( ", "("),
FlatAlt<A>(" )", ")"),
", ",
docs));
/// <summary>
/// Insert a number of spaces. Negative values count as 0.
/// </summary>
public static Doc<A> Spaces<A>(int n)
{
return (n < 0 ? 0 : n) switch
{
0 => Empty<A>(),
1 => Char<A>(' '),
2 => Text<A>(" "),
3 => Text<A>(" "),
4 => Text<A>(" "),
5 => Text<A>(" "),
6 => Text<A>(" "),
7 => Text<A>(" "),
8 => Text<A>(" "),
_ => Text<A>(FastSpace(n - 8))
};
string FastSpace(int x)
{
var sb = new StringBuilder();
sb.Append(" ");
for (var i = 0; i < x; i++)
{
sb.Append(' ');
}
return sb.ToString();
}
}
/// <summary>
/// HorizSep concatenates all documents horizontally with `+`
/// i.e. it puts a space between all entries.
///
/// HorizSep does not introduce line breaks on its own, even when the page is too
/// narrow:
///
/// For automatic line breaks, consider using 'fillSep' instead.
/// </summary>
public static Doc<A> HorizSep<A>(Seq<Doc<A>> docs) =>
docs.IsEmpty
? DocEmpty<A>.Default
: docs.Tail.Fold(docs.Head, (s, d) => s + d);
/// <summary>
/// VertSep concatenates all documents above each other. If a
/// Group undoes the line breaks inserted by VertSep, the documents are
/// separated with a 'space' instead.
///
/// Grouping a VertSep separates the documents with a 'space' if it fits the
/// page (and does nothing otherwise). See the Sep convenience function for
/// this use case.
///
/// The Align function can be used to align the documents under their first
/// element:
///
/// Since Grouping a VertSep is rather common, Sep is a built-in for doing
/// that.
/// </summary>
public static Doc<A> VertSep<A>(Seq<Doc<A>> docs) =>
docs.IsEmpty
? DocEmpty<A>.Default
: docs.Tail.Fold(docs.Head, (s, d) => s | LineOrSpace<A>() | d);
/// <summary>
/// Sep tries laying out the documents separated with 'space's,
/// and if this does not fit the page, separates them with newlines. This is what
/// differentiates it from VerSep, which always lays out its contents beneath
/// each other.
/// </summary>
public static Doc<A> Sep<A>(Seq<Doc<A>> docs) =>
Group(VertSep(docs));
/// <summary>
/// FillSep concatenates the documents horizontally with `+` (inserting a space)
/// as long as it fits the page, then inserts a Line and continues doing that
/// for all documents in (Line means that if Grouped, the documents
/// are separated with a Space instead of newlines. Use 'FillCat' if you do not
/// want a 'space'.)
/// </summary>
public static Doc<A> FillSep<A>(Seq<Doc<A>> docs) =>
docs.IsEmpty
? DocEmpty<A>.Default
: docs.Tail.Fold(docs.Head, (s, d) => s | SoftLineOrSpace<A>() | d);
/// <summary>
/// Hard line separator
/// </summary>
public static Doc<A> HardSep<A>(Seq<Doc<A>> docs) =>
docs.IsEmpty
? DocEmpty<A>.Default
: docs.Tail.Fold(docs.Head, (s, d) => (s, d) switch
{
(DocLine<A>, DocLine<A>) => s,
(DocLine<A>, _) => d,
(_, DocLine<A>) => s,
_ => s | HardLine<A>() | d
});
/// <summary>
/// HorizCat concatenates all documents horizontally with |
/// (i.e. without any spacing).
///
/// It is provided only for consistency, since it is identical to 'Cat'.
/// </summary>
public static Doc<A> HorizCat<A>(Seq<Doc<A>> docs) =>
docs.IsEmpty
? DocEmpty<A>.Default
: docs.Tail.Fold(docs.Head, (s, d) => s | d);
/// <summary>
/// VertCat vertically concatenates the documents. If it is
/// Grouped, the line breaks are removed.
///
/// In other words VertCat is like VertSep, with newlines removed instead of
/// replaced by spaces.
/// </summary>
public static Doc<A> VertCat<A>(Seq<Doc<A>> docs) =>
docs.IsEmpty
? DocEmpty<A>.Default
: docs.Tail.Fold(docs.Head, (s, d) => s | LineOrEmpty<A>() | d);
/// <summary>
/// Width lays out the document 'doc', and makes the column width
/// of it available to a function.
/// </summary>
public static Doc<A> Width<A>(Doc<A> doc, Func<int, Doc<A>> f) =>
Column<A>(colStart =>
doc | Column<A>(colEnd =>
f(colEnd - colStart)));
/// <summary>
/// Fill lays out the document. It then appends spaces until
/// the width is equal to `width`. If the width is already larger, nothing is
/// appended.
/// </summary>
public static Doc<A> Fill<A>(int width, Doc<A> doc) =>
Width<A>(doc, w => Spaces<A>(width - w));
/// <summary>
/// Enclose
/// </summary>
public static Doc<A> Between<A>(Doc<A> left, Doc<A> middle, Doc<A> right) =>
left | middle | right;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public static partial class DscNodeReportsOperationsExtensions
{
/// <summary>
/// Retrieve the Dsc node report data by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The Dsc node id.
/// </param>
/// <param name='reportId'>
/// Required. The report id.
/// </param>
/// <returns>
/// The response model for the get dsc node report operation.
/// </returns>
public static DscNodeReportGetResponse Get(this IDscNodeReportsOperations operations, string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDscNodeReportsOperations)s).GetAsync(resourceGroupName, automationAccount, nodeId, reportId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the Dsc node report data by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The Dsc node id.
/// </param>
/// <param name='reportId'>
/// Required. The report id.
/// </param>
/// <returns>
/// The response model for the get dsc node report operation.
/// </returns>
public static Task<DscNodeReportGetResponse> GetAsync(this IDscNodeReportsOperations operations, string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId)
{
return operations.GetAsync(resourceGroupName, automationAccount, nodeId, reportId, CancellationToken.None);
}
/// <summary>
/// Retrieve the Dsc node reports by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The Dsc node id.
/// </param>
/// <param name='reportId'>
/// Required. The report id.
/// </param>
/// <returns>
/// The response model for the get node report content operation.
/// </returns>
public static DscNodeReportGetContentResponse GetContent(this IDscNodeReportsOperations operations, string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDscNodeReportsOperations)s).GetContentAsync(resourceGroupName, automationAccount, nodeId, reportId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the Dsc node reports by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The Dsc node id.
/// </param>
/// <param name='reportId'>
/// Required. The report id.
/// </param>
/// <returns>
/// The response model for the get node report content operation.
/// </returns>
public static Task<DscNodeReportGetContentResponse> GetContentAsync(this IDscNodeReportsOperations operations, string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId)
{
return operations.GetContentAsync(resourceGroupName, automationAccount, nodeId, reportId, CancellationToken.None);
}
/// <summary>
/// Retrieve the Dsc node report list by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list operation.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public static DscNodeReportListResponse List(this IDscNodeReportsOperations operations, string resourceGroupName, string automationAccount, DscNodeReportListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDscNodeReportsOperations)s).ListAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the Dsc node report list by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list operation.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public static Task<DscNodeReportListResponse> ListAsync(this IDscNodeReportsOperations operations, string resourceGroupName, string automationAccount, DscNodeReportListParameters parameters)
{
return operations.ListAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Retrieve the Dsc node report list by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public static DscNodeReportListResponse ListNext(this IDscNodeReportsOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDscNodeReportsOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the Dsc node report list by node id and report id. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IDscNodeReportsOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public static Task<DscNodeReportListResponse> ListNextAsync(this IDscNodeReportsOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Reflection;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
namespace OpenSim.Region.CoreModules.Avatar.Gods
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GodsModule")]
public class GodsModule : INonSharedRegionModule, IGodsModule
{
protected IDialogModule m_dialogModule;
protected Scene m_scene;
/// <summary>Special UUID for actions that apply to all agents</summary>
private static readonly UUID ALL_AGENTS = new UUID("44e87126-e794-4ded-05b3-7c42da3d5cdb");
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "Gods Module"; } }
public Type ReplaceableInterface
{
get { return null; }
}
protected IDialogModule DialogModule
{
get
{
if (m_dialogModule == null)
m_dialogModule = m_scene.RequestModuleInterface<IDialogModule>();
return m_dialogModule;
}
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IGodsModule>(this);
m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
scene.EventManager.OnIncomingInstantMessage +=
OnIncomingInstantMessage;
}
public void Close()
{
}
public void Initialise(IConfigSource source)
{
}
/// <summary>
/// Kicks User specified from the simulator. This logs them off of the grid
/// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
/// that you're kicking it even if the avatar's UUID isn't the UUID that the
/// agent is assigned
/// </summary>
/// <param name="godID">The person doing the kicking</param>
/// <param name="sessionID">The session of the person doing the kicking</param>
/// <param name="agentID">the person that is being kicked</param>
/// <param name="kickflags">Tells what to do to the user</param>
/// <param name="reason">The message to send to the user after it's been turned into a field</param>
public void KickUser(UUID godID, UUID sessionID, UUID agentID, uint kickflags, byte[] reason)
{
if (!m_scene.Permissions.IsGod(godID))
return;
ScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp == null && agentID != ALL_AGENTS)
{
IMessageTransferModule transferModule =
m_scene.RequestModuleInterface<IMessageTransferModule>();
if (transferModule != null)
{
m_log.DebugFormat("[GODS]: Sending nonlocal kill for agent {0}", agentID);
transferModule.SendInstantMessage(new GridInstantMessage(
m_scene, godID, "God", agentID, (byte)250, false,
Utils.BytesToString(reason), UUID.Zero, true,
new Vector3(), new byte[] { (byte)kickflags }, true),
delegate(bool success) { });
}
return;
}
switch (kickflags)
{
case 0:
if (sp != null)
{
KickPresence(sp, Utils.BytesToString(reason));
}
else if (agentID == ALL_AGENTS)
{
m_scene.ForEachRootScenePresence(
delegate(ScenePresence p)
{
if (p.UUID != godID && (!m_scene.Permissions.IsGod(p.UUID)))
KickPresence(p, Utils.BytesToString(reason));
}
);
}
break;
case 1:
if (sp != null)
{
sp.AllowMovement = false;
m_dialogModule.SendAlertToUser(agentID, Utils.BytesToString(reason));
m_dialogModule.SendAlertToUser(godID, "User Frozen");
}
break;
case 2:
if (sp != null)
{
sp.AllowMovement = true;
m_dialogModule.SendAlertToUser(agentID, Utils.BytesToString(reason));
m_dialogModule.SendAlertToUser(godID, "User Unfrozen");
}
break;
default:
break;
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
m_scene.UnregisterModuleInterface<IGodsModule>(this);
m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
m_scene = null;
}
public void RequestGodlikePowers(
UUID agentID, UUID sessionID, UUID token, bool godLike, IClientAPI controllingClient)
{
ScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null)
{
if (godLike == false)
{
sp.GrantGodlikePowers(agentID, sessionID, token, godLike);
return;
}
// First check that this is the sim owner
if (m_scene.Permissions.IsGod(agentID))
{
// Next we check for spoofing.....
UUID testSessionID = sp.ControllingClient.SessionId;
if (sessionID == testSessionID)
{
if (sessionID == controllingClient.SessionId)
{
//m_log.Info("godlike: " + godLike.ToString());
sp.GrantGodlikePowers(agentID, testSessionID, token, godLike);
}
}
}
else
{
if (DialogModule != null)
DialogModule.SendAlertToUser(agentID, "Request for god powers denied");
}
}
}
public void SubscribeToClientEvents(IClientAPI client)
{
client.OnGodKickUser += KickUser;
client.OnRequestGodlikePowers += RequestGodlikePowers;
}
public void UnsubscribeFromClientEvents(IClientAPI client)
{
client.OnGodKickUser -= KickUser;
client.OnRequestGodlikePowers -= RequestGodlikePowers;
}
private string HandleUntrustedSimulatorMessage(string request,
string path, string param, IOSHttpRequest httpRequest,
IOSHttpResponse httpResponse)
{
OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request);
string message = osd["message"].AsString();
if (message == "GodKickUser")
{
OSDMap body = (OSDMap)osd["body"];
OSDArray userInfo = (OSDArray)body["UserInfo"];
OSDMap userData = (OSDMap)userInfo[0];
UUID agentID = userData["AgentID"].AsUUID();
UUID godID = userData["GodID"].AsUUID();
UUID godSessionID = userData["GodSessionID"].AsUUID();
uint kickFlags = userData["KickFlags"].AsUInteger();
string reason = userData["Reason"].AsString();
ScenePresence god = m_scene.GetScenePresence(godID);
if (god == null || god.ControllingClient.SessionId != godSessionID)
return String.Empty;
KickUser(godID, godSessionID, agentID, kickFlags, Util.StringToBytes1024(reason));
}
else
{
m_log.ErrorFormat("[GOD]: Unhandled UntrustedSimulatorMessage: {0}", message);
}
return String.Empty;
}
private void KickPresence(ScenePresence sp, string reason)
{
if (sp.IsChildAgent)
return;
sp.ControllingClient.Kick(reason);
sp.Scene.CloseAgent(sp.UUID, true);
}
private void OnIncomingInstantMessage(GridInstantMessage msg)
{
if (msg.dialog == (uint)250) // Nonlocal kick
{
UUID agentID = new UUID(msg.toAgentID);
string reason = msg.message;
UUID godID = new UUID(msg.fromAgentID);
uint kickMode = (uint)msg.binaryBucket[0];
KickUser(godID, UUID.Zero, agentID, kickMode, Util.StringToBytes1024(reason));
}
}
private void OnRegisterCaps(UUID agentID, Caps caps)
{
string uri = "/CAPS/" + UUID.Random();
caps.RegisterHandler(
"UntrustedSimulatorMessage",
new RestStreamHandler("POST", uri, HandleUntrustedSimulatorMessage, "UntrustedSimulatorMessage", null));
}
}
}
| |
using System;
using System.Globalization;
using System.Resources;
using System.Threading;
namespace System.Management
{
internal sealed class SR
{
internal const string ASSEMBLY_NOT_REGISTERED = "ASSEMBLY_NOT_REGISTERED";
internal const string FAILED_TO_BUILD_GENERATED_ASSEMBLY = "FAILED_TO_BUILD_GENERATED_ASSEMBLY";
internal const string COMMENT_SHOULDSERIALIZE = "COMMENT_SHOULDSERIALIZE";
internal const string COMMENT_ISPROPNULL = "COMMENT_ISPROPNULL";
internal const string COMMENT_RESETPROP = "COMMENT_RESETPROP";
internal const string COMMENT_DATECONVFUNC = "COMMENT_DATECONVFUNC";
internal const string COMMENT_TIMESPANCONVFUNC = "COMMENT_TIMESPANCONVFUNC";
internal const string COMMENT_ATTRIBPROP = "COMMENT_ATTRIBPROP";
internal const string COMMENT_GETINSTANCES = "COMMENT_GETINSTANCES";
internal const string COMMENT_CLASSBEGIN = "COMMENT_CLASSBEGIN";
internal const string COMMENT_PRIVAUTOCOMMIT = "COMMENT_PRIVAUTOCOMMIT";
internal const string COMMENT_CONSTRUCTORS = "COMMENT_CONSTRUCTORS";
internal const string COMMENT_ORIGNAMESPACE = "COMMENT_ORIGNAMESPACE";
internal const string COMMENT_CLASSNAME = "COMMENT_CLASSNAME";
internal const string COMMENT_SYSOBJECT = "COMMENT_SYSOBJECT";
internal const string COMMENT_LATEBOUNDOBJ = "COMMENT_LATEBOUNDOBJ";
internal const string COMMENT_MGMTSCOPE = "COMMENT_MGMTSCOPE";
internal const string COMMENT_AUTOCOMMITPROP = "COMMENT_AUTOCOMMITPROP";
internal const string COMMENT_MGMTPATH = "COMMENT_MGMTPATH";
internal const string COMMENT_PROPTYPECONVERTER = "COMMENT_PROPTYPECONVERTER";
internal const string COMMENT_SYSPROPCLASS = "COMMENT_SYSPROPCLASS";
internal const string COMMENT_ENUMIMPL = "COMMENT_ENUMIMPL";
internal const string COMMENT_LATEBOUNDPROP = "COMMENT_LATEBOUNDPROP";
internal const string COMMENT_CREATEDCLASS = "COMMENT_CREATEDCLASS";
internal const string COMMENT_CREATEDWMINAMESPACE = "COMMENT_CREATEDWMINAMESPACE";
internal const string COMMENT_STATICMANAGEMENTSCOPE = "COMMENT_STATICMANAGEMENTSCOPE";
internal const string COMMENT_STATICSCOPEPROPERTY = "COMMENT_STATICSCOPEPROPERTY";
internal const string COMMENT_TODATETIME = "COMMENT_TODATETIME";
internal const string COMMENT_TODMTFDATETIME = "COMMENT_TODMTFDATETIME";
internal const string COMMENT_TODMTFTIMEINTERVAL = "COMMENT_TODMTFTIMEINTERVAL";
internal const string COMMENT_TOTIMESPAN = "COMMENT_TOTIMESPAN";
internal const string COMMENT_EMBEDDEDOBJ = "COMMENT_EMBEDDEDOBJ";
internal const string COMMENT_CURRENTOBJ = "COMMENT_CURRENTOBJ";
internal const string COMMENT_FLAGFOREMBEDDED = "COMMENT_FLAGFOREMBEDDED";
internal const string EMBEDDED_COMMENT1 = "EMBEDDED_COMMENT1";
internal const string EMBEDDED_COMMENT2 = "EMBEDDED_COMMENT2";
internal const string EMBEDDED_COMMENT3 = "EMBEDDED_COMMENT3";
internal const string EMBEDDED_COMMENT4 = "EMBEDDED_COMMENT4";
internal const string EMBEDDED_COMMENT5 = "EMBEDDED_COMMENT5";
internal const string EMBEDDED_COMMENT6 = "EMBEDDED_COMMENT6";
internal const string EMBEDDED_COMMENT7 = "EMBEDDED_COMMENT7";
internal const string EMBEDED_VB_CODESAMP4 = "EMBEDED_VB_CODESAMP4";
internal const string EMBEDED_VB_CODESAMP5 = "EMBEDED_VB_CODESAMP5";
internal const string EMBEDDED_COMMENT8 = "EMBEDDED_COMMENT8";
internal const string EMBEDED_CS_CODESAMP4 = "EMBEDED_CS_CODESAMP4";
internal const string EMBEDED_CS_CODESAMP5 = "EMBEDED_CS_CODESAMP5";
internal const string CLASSNOT_FOUND_EXCEPT = "CLASSNOT_FOUND_EXCEPT";
internal const string NULLFILEPATH_EXCEPT = "NULLFILEPATH_EXCEPT";
internal const string EMPTY_FILEPATH_EXCEPT = "EMPTY_FILEPATH_EXCEPT";
internal const string NAMESPACE_NOTINIT_EXCEPT = "NAMESPACE_NOTINIT_EXCEPT";
internal const string CLASSNAME_NOTINIT_EXCEPT = "CLASSNAME_NOTINIT_EXCEPT";
internal const string UNABLE_TOCREATE_GEN_EXCEPT = "UNABLE_TOCREATE_GEN_EXCEPT";
internal const string FORCE_UPDATE = "FORCE_UPDATE";
internal const string FILETOWRITE_MOF = "FILETOWRITE_MOF";
internal const string WMISCHEMA_INSTALLATIONSTART = "WMISCHEMA_INSTALLATIONSTART";
internal const string REGESTRING_ASSEMBLY = "REGESTRING_ASSEMBLY";
internal const string WMISCHEMA_INSTALLATIONEND = "WMISCHEMA_INSTALLATIONEND";
internal const string MOFFILE_GENERATING = "MOFFILE_GENERATING";
internal const string UNSUPPORTEDMEMBER_EXCEPT = "UNSUPPORTEDMEMBER_EXCEPT";
internal const string CLASSINST_EXCEPT = "CLASSINST_EXCEPT";
internal const string MEMBERCONFLILCT_EXCEPT = "MEMBERCONFLILCT_EXCEPT";
internal const string NAMESPACE_ENSURE = "NAMESPACE_ENSURE";
internal const string CLASS_ENSURE = "CLASS_ENSURE";
internal const string CLASS_ENSURECREATE = "CLASS_ENSURECREATE";
internal const string CLASS_NOTREPLACED_EXCEPT = "CLASS_NOTREPLACED_EXCEPT";
internal const string NONCLS_COMPLIANT_EXCEPTION = "NONCLS_COMPLIANT_EXCEPTION";
internal const string INVALID_QUERY = "INVALID_QUERY";
internal const string INVALID_QUERY_DUP_TOKEN = "INVALID_QUERY_DUP_TOKEN";
internal const string INVALID_QUERY_NULL_TOKEN = "INVALID_QUERY_NULL_TOKEN";
internal const string WORKER_THREAD_WAKEUP_FAILED = "WORKER_THREAD_WAKEUP_FAILED";
private static SR loader;
private ResourceManager resources;
private static CultureInfo Culture
{
get
{
return null;
}
}
public static ResourceManager Resources
{
get
{
return SR.GetLoader().resources;
}
}
static SR()
{
}
internal SR()
{
this.resources = new ResourceManager("System.Management", this.GetType().Assembly);
}
private static SR GetLoader()
{
if (SR.loader == null)
{
SR sR = new SR();
Interlocked.CompareExchange<SR>(ref SR.loader, sR, null);
}
return SR.loader;
}
public static object GetObject(string name)
{
SR loader = SR.GetLoader();
if (loader != null)
{
return loader.resources.GetObject(name, SR.Culture);
}
else
{
return null;
}
}
public static string GetString(string name, object[] args)
{
SR loader = SR.GetLoader();
if (loader != null)
{
string str = loader.resources.GetString(name, SR.Culture);
if (args == null || (int)args.Length <= 0)
{
return str;
}
else
{
for (int i = 0; i < (int)args.Length; i++)
{
string str1 = args[i] as string;
if (str1 != null && str1.Length > 0x400)
{
args[i] = string.Concat(str1.Substring(0, 0x3fd), "...");
}
}
return string.Format(CultureInfo.CurrentCulture, str, args);
}
}
else
{
return null;
}
}
public static string GetString(string name)
{
SR loader = SR.GetLoader();
if (loader != null)
{
return loader.resources.GetString(name, SR.Culture);
}
else
{
return null;
}
}
public static string GetString(string name, out bool usedFallback)
{
usedFallback = false;
return SR.GetString(name);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
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.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="KeywordViewServiceClient"/> instances.</summary>
public sealed partial class KeywordViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="KeywordViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="KeywordViewServiceSettings"/>.</returns>
public static KeywordViewServiceSettings GetDefault() => new KeywordViewServiceSettings();
/// <summary>Constructs a new <see cref="KeywordViewServiceSettings"/> object with default settings.</summary>
public KeywordViewServiceSettings()
{
}
private KeywordViewServiceSettings(KeywordViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetKeywordViewSettings = existing.GetKeywordViewSettings;
OnCopy(existing);
}
partial void OnCopy(KeywordViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordViewServiceClient.GetKeywordView</c> and <c>KeywordViewServiceClient.GetKeywordViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetKeywordViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="KeywordViewServiceSettings"/> object.</returns>
public KeywordViewServiceSettings Clone() => new KeywordViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="KeywordViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class KeywordViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public KeywordViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public KeywordViewServiceClientBuilder()
{
UseJwtAccessWithScopes = KeywordViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref KeywordViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override KeywordViewServiceClient Build()
{
KeywordViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<KeywordViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<KeywordViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private KeywordViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return KeywordViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<KeywordViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return KeywordViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => KeywordViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordViewServiceClient.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>KeywordViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage keyword views.
/// </remarks>
public abstract partial class KeywordViewServiceClient
{
/// <summary>
/// The default endpoint for the KeywordViewService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default KeywordViewService scopes.</summary>
/// <remarks>
/// The default KeywordViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
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="KeywordViewServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="KeywordViewServiceClientBuilder"/>
/// .
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="KeywordViewServiceClient"/>.</returns>
public static stt::Task<KeywordViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new KeywordViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="KeywordViewServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="KeywordViewServiceClientBuilder"/>
/// .
/// </summary>
/// <returns>The created <see cref="KeywordViewServiceClient"/>.</returns>
public static KeywordViewServiceClient Create() => new KeywordViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="KeywordViewServiceClient"/> 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="KeywordViewServiceSettings"/>.</param>
/// <returns>The created <see cref="KeywordViewServiceClient"/>.</returns>
internal static KeywordViewServiceClient Create(grpccore::CallInvoker callInvoker, KeywordViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
KeywordViewService.KeywordViewServiceClient grpcClient = new KeywordViewService.KeywordViewServiceClient(callInvoker);
return new KeywordViewServiceClientImpl(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 KeywordViewService client</summary>
public virtual KeywordViewService.KeywordViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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 gagvr::KeywordView GetKeywordView(GetKeywordViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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<gagvr::KeywordView> GetKeywordViewAsync(GetKeywordViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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<gagvr::KeywordView> GetKeywordViewAsync(GetKeywordViewRequest request, st::CancellationToken cancellationToken) =>
GetKeywordViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the keyword view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordView GetKeywordView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordView(new GetKeywordViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the keyword view to fetch.
/// </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<gagvr::KeywordView> GetKeywordViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordViewAsync(new GetKeywordViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the keyword view to fetch.
/// </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<gagvr::KeywordView> GetKeywordViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetKeywordViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the keyword view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordView GetKeywordView(gagvr::KeywordViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordView(new GetKeywordViewRequest
{
ResourceNameAsKeywordViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the keyword view to fetch.
/// </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<gagvr::KeywordView> GetKeywordViewAsync(gagvr::KeywordViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordViewAsync(new GetKeywordViewRequest
{
ResourceNameAsKeywordViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the keyword view to fetch.
/// </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<gagvr::KeywordView> GetKeywordViewAsync(gagvr::KeywordViewName resourceName, st::CancellationToken cancellationToken) =>
GetKeywordViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>KeywordViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage keyword views.
/// </remarks>
public sealed partial class KeywordViewServiceClientImpl : KeywordViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetKeywordViewRequest, gagvr::KeywordView> _callGetKeywordView;
/// <summary>
/// Constructs a client wrapper for the KeywordViewService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="KeywordViewServiceSettings"/> used within this client.</param>
public KeywordViewServiceClientImpl(KeywordViewService.KeywordViewServiceClient grpcClient, KeywordViewServiceSettings settings)
{
GrpcClient = grpcClient;
KeywordViewServiceSettings effectiveSettings = settings ?? KeywordViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetKeywordView = clientHelper.BuildApiCall<GetKeywordViewRequest, gagvr::KeywordView>(grpcClient.GetKeywordViewAsync, grpcClient.GetKeywordView, effectiveSettings.GetKeywordViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetKeywordView);
Modify_GetKeywordViewApiCall(ref _callGetKeywordView);
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_GetKeywordViewApiCall(ref gaxgrpc::ApiCall<GetKeywordViewRequest, gagvr::KeywordView> call);
partial void OnConstruction(KeywordViewService.KeywordViewServiceClient grpcClient, KeywordViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC KeywordViewService client</summary>
public override KeywordViewService.KeywordViewServiceClient GrpcClient { get; }
partial void Modify_GetKeywordViewRequest(ref GetKeywordViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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 gagvr::KeywordView GetKeywordView(GetKeywordViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordViewRequest(ref request, ref callSettings);
return _callGetKeywordView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested keyword view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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 stt::Task<gagvr::KeywordView> GetKeywordViewAsync(GetKeywordViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordViewRequest(ref request, ref callSettings);
return _callGetKeywordView.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
/*=================================ThaiBuddhistCalendar==========================
**
** ThaiBuddhistCalendar is based on Gregorian calendar. Its year value has
** an offset to the Gregorain calendar.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0001/01/01 9999/12/31
** Thai 0544/01/01 10542/12/31
============================================================================*/
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ThaiBuddhistCalendar : Calendar
{
// Initialize our era info.
internal static EraInfo[] thaiBuddhistEraInfo = new EraInfo[] {
new EraInfo( 1, 1, 1, 1, -543, 544, GregorianCalendar.MaxYear + 543) // era #, start year/month/day, yearOffset, minEraYear
};
//
// The era value for the current era.
//
public const int ThaiBuddhistEra = 1;
internal GregorianCalendarHelper helper;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
public ThaiBuddhistCalendar()
{
helper = new GregorianCalendarHelper(this, thaiBuddhistEraInfo);
}
internal override CalendarId ID
{
get
{
return (CalendarId.THAI);
}
}
public override DateTime AddMonths(DateTime time, int months)
{
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years)
{
return (helper.AddYears(time, years));
}
public override int GetDaysInMonth(int year, int month, int era)
{
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era)
{
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time)
{
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time)
{
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time)
{
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era)
{
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era)
{
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2572;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Collections.Generic;
using DSL.POS.Common.Utility;
using DSL.POS.Facade;
using DSL.POS.DTO.DTO;
using DSL.POS.BusinessLogicLayer.Interface;
using DSL.POS.Report;
using DSL.POS.Report.Setup;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
public partial class Report_Stock_StockReport : System.Web.UI.Page
{
private ReportDocument oReportDocument = new ReportDocument();
protected void Page_Load(object sender, EventArgs e)
{
if (!Roles.IsUserInRole(ConfigurationManager.AppSettings["generaluserrolename"]))
{
Response.Redirect("~/CustomErrorPages/NotAuthorized.aspx");
}
this.txtFromDate.Focus();
//this.RbAllBranch.Attributes.Add("onClick", "doAllBranch()");
//this.RbSpecificBranch.Attributes.Add("onClick", "doSpecificBranch()");
this.RbAllCategory.Attributes.Add("onClick", "doAllCategory()");
this.RbSpecificCategory.Attributes.Add("onClick", "doSpecificCategory()");
this.RbAllSubCategory.Attributes.Add("onClick", "doAllSubCategory()");
this.RbSpecificSubCategory.Attributes.Add("onClick", "doSpecificSubCategory()");
this.RbAllBrand.Attributes.Add("onClick", "doAllBrand()");
this.RbSpecificBrand.Attributes.Add("onClick", "doSpecificBrand()");
this.RbAllProduct.Attributes.Add("onClick", "doAllProduct()");
this.RbSpecificProduct.Attributes.Add("onClick", "doSpecificProduct()");
this.txtFromDate.Attributes.Add("onKeyUp", "formatFromDateField()");
this.txtToDate.Attributes.Add("onKeyUp", "formatToDateField()");
this.txtFromDate.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtToDate.Attributes.Add("onkeyPress", "FocusControl_byEnter()");
if (!IsPostBack)
{
try
{
Facade facade = Facade.GetInstance();
DropDownListBrand(facade);
DropDownListProCategory(facade);
DropDownListProductSubCategory(facade);
DropDownListProductName(facade);
}
catch (Exception Exp)
{
throw Exp;
}
}
else
{
}
}
private void DropDownListProCategory(Facade facade)
{
IProductCategoryBL ProductCategoryList = facade.createProductCategoryBL();
List<ProductCategoryInfoDTO> oProCategoryList = ProductCategoryList.GetProductCategoryInfo();
int i = 0;
DDLCategory.Items.Clear();
DDLCategory.Items.Add("(Select Product Category Name)");
this.DDLCategory.Items[i].Value = "00000000-0000-0000-0000-000000000000";
foreach (ProductCategoryInfoDTO newDto in oProCategoryList)
{
i++;
this.DDLCategory.Items.Add(newDto.PC_Description);
this.DDLCategory.Items[i].Value = newDto.PrimaryKey.ToString();
}
}
private void DropDownListProductSubCategory(Facade facade)
{
IProductSubCategoryInfoBL ProductSubCategoryList = facade.createProductSubCategoryBL();
List<ProductSubCategoryInfoDTO> oProSubCategoryList = ProductSubCategoryList.showDataSubCategoryInfo();
int i = 0;
DDLSubCategory.Items.Clear();
DDLSubCategory.Items.Add("(Select Product Sub Category Name)");
this.DDLSubCategory.Items[i].Value = "00000000-0000-0000-0000-000000000000";
foreach (ProductSubCategoryInfoDTO newDto in oProSubCategoryList)
{
i++;
this.DDLSubCategory.Items.Add(newDto.PSC_Description);
this.DDLSubCategory.Items[i].Value = newDto.PrimaryKey.ToString();
}
}
private void DropDownListBrand(Facade facade)
{
IProductBrandBL brandList = facade.GetProductBrandDataList();
List<ProductBrandInfoDTO> oBrandList = brandList.GetProductBrand();
int i = 0;
DDLBrand.Items.Clear();
DDLBrand.Items.Add("(Select Any Brand)");
this.DDLBrand.Items[i].Value = "00000000-0000-0000-0000-000000000000";
foreach (ProductBrandInfoDTO newDto in oBrandList)
{
i++;
this.DDLBrand.Items.Add(newDto.PB_Name);
this.DDLBrand.Items[i].Value = newDto.PrimaryKey.ToString();
}
}
private void DropDownListProductName(Facade facade)
{
IProductInfoBL ProductInfoList = facade.GetPBLImp();
List<ProductInfoDTO> oProInfoList = ProductInfoList.GetProductInfo();
int i = 0;
DDLProductName.Items.Clear();
DDLProductName.Items.Add("(Select Product Name)");
this.DDLProductName.Items[i].Value = "00000000-0000-0000-0000-000000000000";
foreach (ProductInfoDTO newDto in oProInfoList)
{
i++;
this.DDLProductName.Items.Add(newDto.P_Name);
this.DDLProductName.Items[i].Value = newDto.PrimaryKey.ToString();
}
}
protected void btnReport_Click(object sender, EventArgs e)
{
this.lblErrorMessage.Text = "";
if (this.txtFromDate.Text.Trim() == "")
{
this.lblErrorMessage.Text = "Please Insert Start Date.";
return;
}
else if (this.txtToDate.Text.Trim() == "")
{
this.lblErrorMessage.Text = "Please Insert End Date.";
return;
}
else if (this.RbSpecificProduct.Checked == true
&& this.DDLProductName.Text == "00000000-0000-0000-0000-000000000000")
{
this.lblErrorMessage.Text = "Please Select Product Name.";
return;
}
else if (this.RbSpecificCategory.Checked == true
&& this.DDLCategory.Text == "00000000-0000-0000-0000-000000000000")
{
this.lblErrorMessage.Text = "Please Select Category Name.";
return;
}
else if (this.RbSpecificSubCategory.Checked == true
&& this.DDLSubCategory.Text == "00000000-0000-0000-0000-000000000000")
{
this.lblErrorMessage.Text = "Please Select Sub Category Name.";
return;
}
else if (this.RbSpecificBrand.Checked == true
&& this.DDLBrand.Text == "00000000-0000-0000-0000-000000000000")
{
this.lblErrorMessage.Text = "Please Select Brand Name.";
return;
}
else
{
this.lblErrorMessage.Text = "";
}
ReportStockRegisterInfo oReportStocknfo = new ReportStockRegisterInfo();
try
{
DateTime dtFrom, dtTo;
string strReportCaption, crPath, strBranchName, strBrnachType, strBranchAddress, strPhone, strEmail, strPrintedBy, DemandStartDate, DemandEndDate;
strReportCaption = "";
crPath = "";
strBranchName = "";
strBrnachType = "";
strBranchAddress = "";
strPhone = "";
strEmail = "";
strPrintedBy = "Admin";
DemandStartDate = this.txtFromDate.Text;
DemandEndDate = this.txtToDate.Text;
dtFrom = Convert.ToDateTime(this.txtFromDate.Text);
dtTo = Convert.ToDateTime(this.txtToDate.Text);
Guid productCategoryPk = Guid.NewGuid();
Guid productSubCategoryPk = Guid.NewGuid();
Guid productBrandPk = Guid.NewGuid();
Guid productPk = Guid.NewGuid();
productCategoryPk = (Guid)TypeDescriptor.GetConverter(productCategoryPk).ConvertFromString(this.DDLCategory.SelectedValue);
productSubCategoryPk = (Guid)TypeDescriptor.GetConverter(productSubCategoryPk).ConvertFromString(this.DDLSubCategory.SelectedValue);
productBrandPk = (Guid)TypeDescriptor.GetConverter(productBrandPk).ConvertFromString(this.DDLBrand.SelectedValue);
productPk = (Guid)TypeDescriptor.GetConverter(productPk).ConvertFromString(this.DDLProductName.SelectedValue);
DataSet rptDS = new DataSet();
rptDS = oReportStocknfo.GetStockInfo(dtFrom, dtTo,productCategoryPk, productSubCategoryPk, productBrandPk, productPk);
// Retrieving data in cookies
if (Request.Cookies["DPOS"] != null)
{
string strBoothID = "";
if (Request.Cookies["DPOS"]["BoothNo"] != null)
{
strBoothID = Request.Cookies["DPOS"]["BoothNo"];
Guid BoothID = Guid.NewGuid();
BoothInfoDTO dto = new BoothInfoDTO();
// populate dto
Facade facade = Facade.GetInstance();
// PK keep in local variable
BoothID = (Guid)TypeDescriptor.GetConverter(BoothID).ConvertFromString(strBoothID);
// Get the Booth Information Corresponding Booth No. and keep Booth Info Domain Object
dto = facade.getBoothInfo_AllDTO(BoothID);
strBranchName = dto.BranchCode.BranchName;
strBrnachType = dto.BranchCode.BranchTypeInfoDTO.BT_Name;
strBranchAddress = dto.BranchCode.BranchAddress;
strPhone = dto.BranchCode.Telephone1 + "," + dto.BranchCode.Telephone2 + "," + dto.BranchCode.Telephone3;
strEmail = dto.BranchCode.EMail;
}
}
if (rbWithAmount.Checked == true && rbWithoutAmount.Checked == false)
{
strReportCaption = lblWithAmount.Text;
crPath = "CrysStockRegister.rpt";
}
if (rbWithAmount.Checked == false && rbWithoutAmount.Checked == true)
{
strReportCaption = lblWithoutAmount.Text;
crPath = "CrysStockRegisterWithoutAmount.rpt";
}
string reportPath = Server.MapPath(crPath);
oReportDocument.Load(reportPath);
oReportDocument.SetDataSource(rptDS.Tables[0]);
oReportDocument.SetParameterValue("@ReportCaption", strReportCaption);
oReportDocument.SetParameterValue("@DemandStartDate", DemandStartDate);
oReportDocument.SetParameterValue("@DemandEndDate", DemandEndDate);
oReportDocument.SetParameterValue("@BranchName", strBranchName);
oReportDocument.SetParameterValue("@BranchType", strBrnachType);
oReportDocument.SetParameterValue("@BranchAddress", strBranchAddress);
oReportDocument.SetParameterValue("@BranchPhone", strPhone);
oReportDocument.SetParameterValue("@BranchEmail", strEmail);
oReportDocument.SetParameterValue("@PrintedBy", strPrintedBy);
CommonViewer.CRReportDefinition = oReportDocument;
Response.Redirect("~/Report/AllCrystalReportViewer/ReportViewer.aspx");
}
catch (Exception exp)
{
throw exp;
}
}
protected void btnClose_Click(object sender, EventArgs e)
{
Response.Redirect("~\\Report\\Default.aspx");
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeList (read only list).<br/>
/// This is a generated <see cref="ProductTypeList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeInfo"/> objects.
/// No cache. Updated by ProductTypeDynaItem
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeList : ReadOnlyBindingListBase<ProductTypeList, ProductTypeInfo>
#else
public partial class ProductTypeList : ReadOnlyListBase<ProductTypeList, ProductTypeInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="ProductTypeInfo"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeInfo in this)
{
if (productTypeInfo.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeList"/> collection.</returns>
public static ProductTypeList GetProductTypeList()
{
return DataPortal.Fetch<ProductTypeList>();
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeList(EventHandler<DataPortalResult<ProductTypeList>> callback)
{
DataPortal.BeginFetch<ProductTypeList>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeList()
{
// Use factory methods and do not use direct creation.
ProductTypeDynaItemSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="ProductTypeDynaItem"/> to update the list of <see cref="ProductTypeInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (ProductTypeDynaItem)e.NewObject;
if (((ProductTypeDynaItem)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(ProductTypeInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((ProductTypeDynaItem)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.GetProductTypeList", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="ProductTypeList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<ProductTypeInfo>(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
#region ProductTypeDynaItemSaved nested class
// TODO: edit "ProductTypeList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: ProductTypeDynaItemSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="ProductTypeDynaItem"/>
/// to update the list of <see cref="ProductTypeInfo"/> objects.
/// </summary>
private static class ProductTypeDynaItemSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a ProductTypeList instance to handle Saved events.
/// to update the list of <see cref="ProductTypeInfo"/> objects.
/// </summary>
/// <param name="obj">The ProductTypeList instance.</param>
public static void Register(ProductTypeList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (ProductTypeList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
ProductTypeDynaItem.ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="ProductTypeDynaItem"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((ProductTypeList) reference.Target).ProductTypeDynaItemSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered ProductTypeList instances.
/// </summary>
public static void Unregister()
{
ProductTypeDynaItem.ProductTypeDynaItemSaved -= ProductTypeDynaItemSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Query
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Text;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>Use this class to parse an expression in the OData URI format.</summary>
/// <remarks>
/// Literals (non-normative "handy" reference - see spec for correct expression):
/// Null null
/// Boolean true | false
/// Int32 (digit+)
/// Int64 (digit+)(L|l)
/// Decimal (digit+ ['.' digit+])(M|m)
/// Float (digit+ ['.' digit+][e|E [+|-] digit+)(f|F)
/// Double (digit+ ['.' digit+][e|E [+|-] digit+)
/// String "'" .* "'"
/// DateTime datetime"'"dddd-dd-dd[T|' ']dd:mm[ss[.fffffff]]"'"
/// DateTimeOffset datetimeoffset"'"dddd-dd-dd[T|' ']dd:mm[ss[.fffffff]]-dd:mm"'"
/// Time time"'"dd:mm[ss[.fffffff]]"'"
/// Binary (binary|X)'digit*'
/// GUID guid'digit*'
/// </remarks>
[DebuggerDisplay("ExpressionLexer ({text} @ {textPos} [{token}]")]
internal class ExpressionLexer
{
#region Private fields
/// <summary>Suffix for single literals.</summary>
private const char SingleSuffixLower = 'f';
/// <summary>Suffix for single literals.</summary>
private const char SingleSuffixUpper = 'F';
/// <summary>Text being parsed.</summary>
private readonly string text;
/// <summary>Length of text being parsed.</summary>
private readonly int textLen;
/// <summary>Position on text being parsed.</summary>
private int textPos;
/// <summary>Character being processed.</summary>
private char ch;
/// <summary>Token being processed.</summary>
private ExpressionToken token;
#endregion Private fields
#region Constructors
/// <summary>Initializes a new <see cref="ExpressionLexer"/>.</summary>
/// <param name="expression">Expression to parse.</param>
/// <param name="moveToFirstToken">If true, this constructor will call NextToken() to move to the first token.</param>
internal ExpressionLexer(string expression, bool moveToFirstToken)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(expression != null, "expression != null");
this.text = expression;
this.textLen = this.text.Length;
this.SetTextPos(0);
if (moveToFirstToken)
{
this.NextToken();
}
}
#endregion Constructors
#region Internal properties
/// <summary>Token being processed.</summary>
internal ExpressionToken CurrentToken
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.token;
}
set
{
DebugUtils.CheckNoExternalCallers();
this.token = value;
}
}
/// <summary>Text being parsed.</summary>
internal string ExpressionText
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.text;
}
}
/// <summary>Position on text being parsed.</summary>
internal int Position
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.token.Position;
}
}
#endregion Internal properties
#region Internal methods
/// <summary>Whether the specified token identifier is a numeric literal.</summary>
/// <param name="id">Token to check.</param>
/// <returns>true if it's a numeric literal; false otherwise.</returns>
internal static bool IsNumeric(ExpressionTokenKind id)
{
DebugUtils.CheckNoExternalCallers();
return
id == ExpressionTokenKind.IntegerLiteral || id == ExpressionTokenKind.DecimalLiteral ||
id == ExpressionTokenKind.DoubleLiteral || id == ExpressionTokenKind.Int64Literal ||
id == ExpressionTokenKind.SingleLiteral;
}
/// <summary>Creates an exception for a parse error.</summary>
/// <param name="message">Message text.</param>
/// <returns>A new Exception.</returns>
internal static Exception ParseError(string message)
{
DebugUtils.CheckNoExternalCallers();
return new ODataException(message);
}
/// <summary>
/// Determines if the next token can be processed without error without advancing the token.
/// </summary>
/// <param name="resultToken">The next ExpressionToken. This value is undefined if error is defined.</param>
/// <param name="error">Exception generated from trying to process the next token.</param>
/// <returns>True if the next token can be processed, false otherwise.</returns>
internal bool TryPeekNextToken(out ExpressionToken resultToken, out Exception error)
{
DebugUtils.CheckNoExternalCallers();
int savedTextPos = this.textPos;
char savedChar = this.ch;
ExpressionToken savedToken = this.token;
resultToken = this.NextTokenImplementation(out error);
this.textPos = savedTextPos;
this.ch = savedChar;
this.token = savedToken;
return error == null;
}
/// <summary>Reads the next token, skipping whitespace as necessary, advancing the Lexer.</summary>
/// <returns>The next token.</returns>
/// <remarks>Throws on error.</remarks>
internal ExpressionToken NextToken()
{
DebugUtils.CheckNoExternalCallers();
Exception error = null;
ExpressionToken nextToken = this.NextTokenImplementation(out error);
if (error != null)
{
throw error;
}
return nextToken;
}
#if ODATALIB
/// <summary>Reads the next token, checks that it is a literal token type, converts to to a Common Language Runtime value as appropriate, and returns the value.</summary>
/// <returns>The value represented by the next token.</returns>
internal object ReadLiteralToken()
{
DebugUtils.CheckNoExternalCallers();
this.NextToken();
if (ExpressionLexer.IsLiteralType(this.CurrentToken.Kind))
{
return this.TryParseLiteral();
}
throw new ODataException(o.Strings.ExpressionLexer_ExpectedLiteralToken(this.CurrentToken.Text));
}
#endif
/// <summary>
/// Starting from an identifier, reads a sequence of dots and
/// identifiers, and returns the text for it, with whitespace
/// stripped.
/// </summary>
/// <returns>The dotted identifier starting at the current identifier.</returns>
internal string ReadDottedIdentifier()
{
DebugUtils.CheckNoExternalCallers();
this.ValidateToken(ExpressionTokenKind.Identifier);
StringBuilder builder = null;
string result = this.CurrentToken.Text;
this.NextToken();
while (this.CurrentToken.Kind == ExpressionTokenKind.Dot)
{
this.NextToken();
this.ValidateToken(ExpressionTokenKind.Identifier);
if (builder == null)
{
builder = new StringBuilder(result, result.Length + 1 + this.CurrentToken.Text.Length);
}
builder.Append('.');
builder.Append(this.CurrentToken.Text);
this.NextToken();
}
if (builder != null)
{
result = builder.ToString();
}
return result;
}
/// <summary>Returns the next token without advancing the lexer.</summary>
/// <returns>The next token.</returns>
internal ExpressionToken PeekNextToken()
{
DebugUtils.CheckNoExternalCallers();
ExpressionToken outToken;
Exception error;
this.TryPeekNextToken(out outToken, out error);
if (error != null)
{
throw error;
}
return outToken;
}
/// <summary>Validates the current token is of the specified kind.</summary>
/// <param name="t">Expected token kind.</param>
internal void ValidateToken(ExpressionTokenKind t)
{
DebugUtils.CheckNoExternalCallers();
if (this.token.Kind != t)
{
throw ParseError(o.Strings.ExpressionLexer_SyntaxError(this.textPos, this.text));
}
}
#endregion Internal methods
#region Private methods
#if ODATALIB
/// <summary>
/// Returns whether the <paramref name="tokenKind"/> is a primitive literal type:
/// Binary, Boolean, DatTime, Decimal, Double, Guid, In64, Integer, Null, Single, or String.
/// </summary>
/// <param name="tokenKind">Kind of token.</param>
/// <returns>Whether the <paramref name="tokenKind"/> is a literal type.</returns>
private static Boolean IsLiteralType(ExpressionTokenKind tokenKind)
{
switch (tokenKind)
{
case ExpressionTokenKind.BinaryLiteral:
case ExpressionTokenKind.BooleanLiteral:
case ExpressionTokenKind.DateTimeLiteral:
case ExpressionTokenKind.DecimalLiteral:
case ExpressionTokenKind.DoubleLiteral:
case ExpressionTokenKind.GuidLiteral:
case ExpressionTokenKind.Int64Literal:
case ExpressionTokenKind.IntegerLiteral:
case ExpressionTokenKind.NullLiteral:
case ExpressionTokenKind.SingleLiteral:
case ExpressionTokenKind.StringLiteral:
case ExpressionTokenKind.DateTimeOffsetLiteral:
case ExpressionTokenKind.TimeLiteral:
case ExpressionTokenKind.GeographyLiteral:
case ExpressionTokenKind.GeometryLiteral:
return true;
default:
return false;
}
}
#endif
/// <summary>Checks if the <paramref name="tokenText"/> is INF or NaN.</summary>
/// <param name="tokenText">Input token.</param>
/// <returns>true if match found, false otherwise.</returns>
private static bool IsInfinityOrNaNDouble(string tokenText)
{
Debug.Assert(tokenText != null, "tokenText != null");
if (tokenText.Length == 3)
{
if (tokenText[0] == ExpressionConstants.InfinityLiteral[0])
{
return IsInfinityLiteralDouble(tokenText);
}
else
if (tokenText[0] == ExpressionConstants.NaNLiteral[0])
{
return String.CompareOrdinal(tokenText, 0, ExpressionConstants.NaNLiteral, 0, 3) == 0;
}
}
return false;
}
/// <summary>
/// Checks whether <paramref name="text"/> equals to 'INF'
/// </summary>
/// <param name="text">Text to look in.</param>
/// <returns>true if the substring is equal using an ordinal comparison; false otherwise.</returns>
private static bool IsInfinityLiteralDouble(string text)
{
Debug.Assert(text != null, "text != null");
return String.CompareOrdinal(text, 0, ExpressionConstants.InfinityLiteral, 0, text.Length) == 0;
}
/// <summary>Checks if the <paramref name="tokenText"/> is INFf/INFF or NaNf/NaNF.</summary>
/// <param name="tokenText">Input token.</param>
/// <returns>true if match found, false otherwise.</returns>
private static bool IsInfinityOrNanSingle(string tokenText)
{
Debug.Assert(tokenText != null, "tokenText != null");
if (tokenText.Length == 4)
{
if (tokenText[0] == ExpressionConstants.InfinityLiteral[0])
{
return IsInfinityLiteralSingle(tokenText);
}
else if (tokenText[0] == ExpressionConstants.NaNLiteral[0])
{
return (tokenText[3] == ExpressionLexer.SingleSuffixLower || tokenText[3] == ExpressionLexer.SingleSuffixUpper) &&
String.CompareOrdinal(tokenText, 0, ExpressionConstants.NaNLiteral, 0, 3) == 0;
}
}
return false;
}
/// <summary>
/// Checks whether <paramref name="text"/> EQUALS to 'INFf' or 'INFF'.
/// </summary>
/// <param name="text">Text to look in.</param>
/// <returns>true if the substring is equal using an ordinal comparison; false otherwise.</returns>
private static bool IsInfinityLiteralSingle(string text)
{
Debug.Assert(text != null, "text != null");
return text.Length == 4 &&
(text[3] == ExpressionLexer.SingleSuffixLower || text[3] == ExpressionLexer.SingleSuffixUpper) &&
String.CompareOrdinal(text, 0, ExpressionConstants.InfinityLiteral, 0, 3) == 0;
}
/// <summary>Reads the next token, skipping whitespace as necessary.</summary>
/// <param name="error">Error that occurred while trying to process the next token.</param>
/// <returns>The next token, which may be 'bad' if an error occurs.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This parser method is all about the switch statement and would be harder to maintain if it were broken up.")]
private ExpressionToken NextTokenImplementation(out Exception error)
{
DebugUtils.CheckNoExternalCallers();
error = null;
while (Char.IsWhiteSpace(this.ch))
{
this.NextChar();
}
ExpressionTokenKind t;
int tokenPos = this.textPos;
switch (this.ch)
{
case '(':
this.NextChar();
t = ExpressionTokenKind.OpenParen;
break;
case ')':
this.NextChar();
t = ExpressionTokenKind.CloseParen;
break;
case ',':
this.NextChar();
t = ExpressionTokenKind.Comma;
break;
case '-':
bool hasNext = this.textPos + 1 < this.textLen;
if (hasNext && Char.IsDigit(this.text[this.textPos + 1]))
{
this.NextChar();
t = this.ParseFromDigit();
if (IsNumeric(t))
{
break;
}
// If it looked like a numeric but wasn't (because it was a binary 0x... value for example),
// we'll rewind and fall through to a simple '-' token.
this.SetTextPos(tokenPos);
}
else if (hasNext && this.text[tokenPos + 1] == ExpressionConstants.InfinityLiteral[0])
{
this.NextChar();
this.ParseIdentifier();
string currentIdentifier = this.text.Substring(tokenPos + 1, this.textPos - tokenPos - 1);
if (IsInfinityLiteralDouble(currentIdentifier))
{
t = ExpressionTokenKind.DoubleLiteral;
break;
}
else if (IsInfinityLiteralSingle(currentIdentifier))
{
t = ExpressionTokenKind.SingleLiteral;
break;
}
// If it looked like '-INF' but wasn't we'll rewind and fall through to a simple '-' token.
this.SetTextPos(tokenPos);
}
this.NextChar();
t = ExpressionTokenKind.Minus;
break;
case '=':
this.NextChar();
t = ExpressionTokenKind.Equal;
break;
case '/':
this.NextChar();
t = ExpressionTokenKind.Slash;
break;
case '?':
this.NextChar();
t = ExpressionTokenKind.Question;
break;
case ':':
this.NextChar();
t = ExpressionTokenKind.Colon;
break;
case '.':
this.NextChar();
t = ExpressionTokenKind.Dot;
break;
case '\'':
char quote = this.ch;
do
{
this.NextChar();
while (this.textPos < this.textLen && this.ch != quote)
{
this.NextChar();
}
if (this.textPos == this.textLen)
{
error = ParseError(o.Strings.ExpressionLexer_UnterminatedStringLiteral(this.textPos, this.text));
}
this.NextChar();
}
while (this.ch == quote);
t = ExpressionTokenKind.StringLiteral;
break;
case '*':
this.NextChar();
t = ExpressionTokenKind.Star;
break;
default:
if (Char.IsLetter(this.ch) || this.ch == '_' || this.ch == '$')
{
this.ParseIdentifier();
t = ExpressionTokenKind.Identifier;
break;
}
if (Char.IsDigit(this.ch))
{
t = this.ParseFromDigit();
break;
}
if (this.textPos == this.textLen)
{
t = ExpressionTokenKind.End;
break;
}
error = ParseError(o.Strings.ExpressionLexer_InvalidCharacter(this.ch, this.textPos, this.text));
t = ExpressionTokenKind.Unknown;
break;
}
this.token.Kind = t;
this.token.Text = this.text.Substring(tokenPos, this.textPos - tokenPos);
this.token.Position = tokenPos;
// Handle type-prefixed literals such as binary, datetime or guid.
this.HandleTypePrefixedLiterals();
// Handle keywords.
if (this.token.Kind == ExpressionTokenKind.Identifier)
{
if (IsInfinityOrNaNDouble(this.token.Text))
{
this.token.Kind = ExpressionTokenKind.DoubleLiteral;
}
else if (IsInfinityOrNanSingle(this.token.Text))
{
this.token.Kind = ExpressionTokenKind.SingleLiteral;
}
else if (this.token.Text == ExpressionConstants.KeywordTrue || this.token.Text == ExpressionConstants.KeywordFalse)
{
this.token.Kind = ExpressionTokenKind.BooleanLiteral;
}
else if (this.token.Text == ExpressionConstants.KeywordNull)
{
this.token.Kind = ExpressionTokenKind.NullLiteral;
}
}
return this.token;
}
/// <summary>Handles lexemes that are formed by an identifier followed by a quoted string.</summary>
/// <remarks>This method modified the token field as necessary.</remarks>
private void HandleTypePrefixedLiterals()
{
ExpressionTokenKind id = this.token.Kind;
if (id != ExpressionTokenKind.Identifier)
{
return;
}
bool quoteFollows = this.ch == '\'';
if (!quoteFollows)
{
return;
}
string tokenText = this.token.Text;
if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixDateTime, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.DateTimeLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixDateTimeOffset, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.DateTimeOffsetLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixTime, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.TimeLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixGuid, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.GuidLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixBinary, StringComparison.OrdinalIgnoreCase) ||
String.Equals(tokenText, ExpressionConstants.LiteralPrefixShortBinary, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.BinaryLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixGeography, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.GeographyLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixGeometry, StringComparison.OrdinalIgnoreCase))
{
id = ExpressionTokenKind.GeometryLiteral;
}
else
{
return;
}
int tokenPos = this.token.Position;
do
{
this.NextChar();
}
while (this.ch != '\0' && this.ch != '\'');
if (this.ch == '\0')
{
throw ParseError(o.Strings.ExpressionLexer_UnterminatedLiteral(this.textPos, this.text));
}
this.NextChar();
this.token.Kind = id;
this.token.Text = this.text.Substring(tokenPos, this.textPos - tokenPos);
}
/// <summary>Advanced to the next character.</summary>
private void NextChar()
{
if (this.textPos < this.textLen)
{
this.textPos++;
}
this.ch = this.textPos < this.textLen ? this.text[this.textPos] : '\0';
}
/// <summary>Parses a token that starts with a digit.</summary>
/// <returns>The kind of token recognized.</returns>
private ExpressionTokenKind ParseFromDigit()
{
Debug.Assert(Char.IsDigit(this.ch), "Char.IsDigit(this.ch)");
ExpressionTokenKind result;
char startChar = this.ch;
this.NextChar();
if (startChar == '0' && this.ch == 'x' || this.ch == 'X')
{
result = ExpressionTokenKind.BinaryLiteral;
do
{
this.NextChar();
}
while (UriPrimitiveTypeParser.IsCharHexDigit(this.ch));
}
else
{
result = ExpressionTokenKind.IntegerLiteral;
while (Char.IsDigit(this.ch))
{
this.NextChar();
}
if (this.ch == '.')
{
result = ExpressionTokenKind.DoubleLiteral;
this.NextChar();
this.ValidateDigit();
do
{
this.NextChar();
}
while (Char.IsDigit(this.ch));
}
if (this.ch == 'E' || this.ch == 'e')
{
result = ExpressionTokenKind.DoubleLiteral;
this.NextChar();
if (this.ch == '+' || this.ch == '-')
{
this.NextChar();
}
this.ValidateDigit();
do
{
this.NextChar();
}
while (Char.IsDigit(this.ch));
}
if (this.ch == 'M' || this.ch == 'm')
{
result = ExpressionTokenKind.DecimalLiteral;
this.NextChar();
}
else
if (this.ch == 'd' || this.ch == 'D')
{
result = ExpressionTokenKind.DoubleLiteral;
this.NextChar();
}
else if (this.ch == 'L' || this.ch == 'l')
{
result = ExpressionTokenKind.Int64Literal;
this.NextChar();
}
else if (this.ch == 'f' || this.ch == 'F')
{
result = ExpressionTokenKind.SingleLiteral;
this.NextChar();
}
}
return result;
}
/// <summary>Parses an identifier by advancing the current character.</summary>
private void ParseIdentifier()
{
Debug.Assert(Char.IsLetter(this.ch) || this.ch == '_' || this.ch == '$', "Char.IsLetter(this.ch) || this.ch == '_' || this.ch == '$'");
do
{
this.NextChar();
}
while (Char.IsLetterOrDigit(this.ch) || this.ch == '_' || this.ch == '$');
}
#if ODATALIB
/// <summary>
/// Parses null literals.
/// </summary>
/// <returns>The literal token produced by building the given literal.</returns>
private object ParseNullLiteral()
{
Debug.Assert(this.CurrentToken.Kind == ExpressionTokenKind.NullLiteral, "this.lexer.CurrentToken.Kind == ExpressionTokenKind.NullLiteral");
this.NextToken();
ODataUriNullValue nullValue = new ODataUriNullValue();
if (this.ExpressionText == ExpressionConstants.KeywordNull)
{
return nullValue;
}
int nullLiteralLength = ExpressionConstants.LiteralSingleQuote.Length * 2 + ExpressionConstants.KeywordNull.Length;
int startOfTypeIndex = ExpressionConstants.LiteralSingleQuote.Length + ExpressionConstants.KeywordNull.Length;
nullValue.TypeName = this.ExpressionText.Substring(startOfTypeIndex, this.ExpressionText.Length - nullLiteralLength);
return nullValue;
}
/// <summary>
/// Parses typed literals.
/// </summary>
/// <param name="targetTypeReference">Expected type to be parsed.</param>
/// <returns>The literal token produced by building the given literal.</returns>
private object ParseTypedLiteral(IEdmPrimitiveTypeReference targetTypeReference)
{
object targetValue;
if (!UriPrimitiveTypeParser.TryUriStringToPrimitive(this.CurrentToken.Text, targetTypeReference, out targetValue))
{
string message = o.Strings.UriQueryExpressionParser_UnrecognizedLiteral(
targetTypeReference.FullName(),
this.CurrentToken.Text,
this.CurrentToken.Position,
this.ExpressionText);
throw ParseError(message);
}
this.NextToken();
return targetValue;
}
#endif
/// <summary>Sets the text position.</summary>
/// <param name="pos">New text position.</param>
private void SetTextPos(int pos)
{
this.textPos = pos;
this.ch = this.textPos < this.textLen ? this.text[this.textPos] : '\0';
}
#if ODATALIB
/// <summary>
/// Parses a literal.
/// Precondition: lexer is at a literal token type: Boolean, DateTime, Decimal, Null, String, Int64, Integer, Double, Single, Guid, Binary.
/// </summary>
/// <returns>The literal query token or null if something else was found.</returns>
private object TryParseLiteral()
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(ExpressionLexer.IsLiteralType(this.CurrentToken.Kind), "TryParseLiteral called when not at a literal type token");
switch (this.CurrentToken.Kind)
{
case ExpressionTokenKind.BooleanLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetBoolean(false));
case ExpressionTokenKind.DateTimeLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetTemporal(EdmPrimitiveTypeKind.DateTime, false));
case ExpressionTokenKind.DecimalLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetDecimal(false));
case ExpressionTokenKind.NullLiteral:
return this.ParseNullLiteral();
case ExpressionTokenKind.StringLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetString(true));
case ExpressionTokenKind.Int64Literal:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetInt64(false));
case ExpressionTokenKind.IntegerLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetInt32(false));
case ExpressionTokenKind.DoubleLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetDouble(false));
case ExpressionTokenKind.SingleLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetSingle(false));
case ExpressionTokenKind.GuidLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetGuid(false));
case ExpressionTokenKind.BinaryLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetBinary(true));
case ExpressionTokenKind.DateTimeOffsetLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetDateTimeOffset(false));
case ExpressionTokenKind.TimeLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetTemporal(EdmPrimitiveTypeKind.Time, false));
case ExpressionTokenKind.GeographyLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geography, false));
case ExpressionTokenKind.GeometryLiteral:
return this.ParseTypedLiteral(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geometry, false));
}
return null;
}
#endif
/// <summary>Validates the current character is a digit.</summary>
private void ValidateDigit()
{
if (!Char.IsDigit(this.ch))
{
throw ParseError(o.Strings.ExpressionLexer_DigitExpected(this.textPos, this.text));
}
}
#endregion Private methods
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SendReceive
{
private readonly ITestOutputHelper _log;
public SendReceive(ITestOutputHelper output)
{
_log = output;
}
private static void SendToRecvFromAsync_Datagram_UDP(IPAddress leftAddress, IPAddress rightAddress)
{
const int DatagramSize = 256;
const int DatagramsToSend = 256;
const int AckTimeout = 1000;
const int TestTimeout = 30000;
var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
var leftEventArgs = new SocketAsyncEventArgs();
left.BindToAnonymousPort(leftAddress);
var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
var rightEventArgs = new SocketAsyncEventArgs();
right.BindToAnonymousPort(rightAddress);
var leftEndpoint = (IPEndPoint)left.LocalEndPoint;
var rightEndpoint = (IPEndPoint)right.LocalEndPoint;
var receiverAck = new ManualResetEventSlim();
var senderAck = new ManualResetEventSlim();
EndPoint receiveRemote = leftEndpoint.Create(leftEndpoint.Serialize());
var receiverFinished = new TaskCompletionSource<bool>();
var receivedChecksums = new uint?[DatagramsToSend];
var receiveBuffer = new byte[DatagramSize];
int receivedDatagrams = -1;
Action<int, EndPoint> receiveHandler = null;
receiveHandler = (received, remote) =>
{
if (receivedDatagrams != -1)
{
Assert.Equal(DatagramSize, received);
Assert.Equal(rightEndpoint, remote);
int datagramId = (int)receiveBuffer[0];
Assert.Null(receivedChecksums[datagramId]);
receivedChecksums[datagramId] = Fletcher32.Checksum(receiveBuffer, 0, received);
receiverAck.Set();
Assert.True(senderAck.Wait(AckTimeout));
senderAck.Reset();
receivedDatagrams++;
if (receivedDatagrams == DatagramsToSend)
{
left.Dispose();
receiverFinished.SetResult(true);
return;
}
}
else
{
receivedDatagrams = 0;
}
left.ReceiveFromAsync(leftEventArgs, receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, receiveRemote, receiveHandler);
};
receiveHandler(0, null);
var random = new Random();
var sentChecksums = new uint[DatagramsToSend];
var sendBuffer = new byte[DatagramSize];
int sentDatagrams = -1;
Action<int> sendHandler = null;
sendHandler = sent =>
{
if (sentDatagrams != -1)
{
Assert.True(receiverAck.Wait(AckTimeout));
receiverAck.Reset();
senderAck.Set();
Assert.Equal(DatagramSize, sent);
sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent);
sentDatagrams++;
if (sentDatagrams == DatagramsToSend)
{
right.Dispose();
return;
}
}
else
{
sentDatagrams = 0;
}
random.NextBytes(sendBuffer);
sendBuffer[0] = (byte)sentDatagrams;
right.SendToAsync(rightEventArgs, sendBuffer, 0, sendBuffer.Length, SocketFlags.None, leftEndpoint, sendHandler);
};
sendHandler(0);
Assert.True(receiverFinished.Task.Wait(TestTimeout));
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]);
}
}
private static void SendRecvAsync_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int LingerTime = 60;
const int TestTimeout = 30000;
var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
server.BindToAnonymousPort(listenAt);
server.Listen(ListenBacklog);
var serverFinished = new TaskCompletionSource<bool>();
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
var serverEventArgs = new SocketAsyncEventArgs();
server.AcceptAsync(serverEventArgs, remote =>
{
Action<int> recvHandler = null;
bool first = true;
if (!useMultipleBuffers)
{
var recvBuffer = new byte[256];
recvHandler = received =>
{
if (!first)
{
if (received == 0)
{
remote.Dispose();
server.Dispose();
serverFinished.SetResult(true);
return;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
else
{
first = false;
}
remote.ReceiveAsync(serverEventArgs, recvBuffer, 0, recvBuffer.Length, SocketFlags.None, recvHandler);
};
}
else
{
var recvBuffers = new List<ArraySegment<byte>> {
new ArraySegment<byte>(new byte[123]),
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 33)
};
recvHandler = received =>
{
if (!first)
{
if (received == 0)
{
remote.Dispose();
server.Dispose();
serverFinished.SetResult(true);
return;
}
bytesReceived += received;
for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++)
{
ArraySegment<byte> buffer = recvBuffers[i];
int toAdd = Math.Min(buffer.Count, remaining);
receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd);
remaining -= toAdd;
}
}
else
{
first = false;
}
remote.ReceiveAsync(serverEventArgs, recvBuffers, SocketFlags.None, recvHandler);
};
}
recvHandler(0);
});
EndPoint clientEndpoint = server.LocalEndPoint;
var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
int bytesSent = 0;
var sentChecksum = new Fletcher32();
var clientEventArgs = new SocketAsyncEventArgs();
client.ConnectAsync(clientEventArgs, clientEndpoint, () =>
{
Action<int> sendHandler = null;
var random = new Random();
var remaining = BytesToSend;
bool first = true;
if (!useMultipleBuffers)
{
var sendBuffer = new byte[512];
sendHandler = sent =>
{
if (!first)
{
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
remaining -= sent;
Assert.True(remaining >= 0);
if (remaining == 0)
{
client.LingerState = new LingerOption(true, LingerTime);
client.Dispose();
return;
}
}
else
{
first = false;
}
random.NextBytes(sendBuffer);
client.SendAsync(clientEventArgs, sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None, sendHandler);
};
}
else
{
var sendBuffers = new List<ArraySegment<byte>> {
new ArraySegment<byte>(new byte[23]),
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 9)
};
sendHandler = sent =>
{
if (!first)
{
bytesSent += sent;
for (int i = 0, r = sent; i < sendBuffers.Count && r > 0; i++)
{
ArraySegment<byte> buffer = sendBuffers[i];
int toAdd = Math.Min(buffer.Count, r);
sentChecksum.Add(buffer.Array, buffer.Offset, toAdd);
r -= toAdd;
}
remaining -= sent;
if (remaining <= 0)
{
client.LingerState = new LingerOption(true, LingerTime);
client.Dispose();
return;
}
}
else
{
first = false;
}
for (int i = 0; i < sendBuffers.Count; i++)
{
random.NextBytes(sendBuffers[i].Array);
}
client.SendAsync(clientEventArgs, sendBuffers, SocketFlags.None, sendHandler);
};
}
sendHandler(0);
});
Assert.True(serverFinished.Task.Wait(TestTimeout), "Completed within allowed time");
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
private static void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int LingerTime = 10;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (TcpClient remote = await listener.AcceptTcpClientAsync())
using (NetworkStream stream = remote.GetStream())
{
var recvBuffer = new byte[256];
for (;;)
{
int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length);
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
});
int bytesSent = 0;
var sentChecksum = new Fletcher32();
Task clientTask = Task.Run(async () =>
{
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new TcpClient(clientEndpoint.AddressFamily))
{
await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
using (NetworkStream stream = client.GetStream())
{
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
sent = Math.Min(sendBuffer.Length, remaining);
await stream.WriteAsync(sendBuffer, 0, sent);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
client.LingerState = new LingerOption(true, LingerTime);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout));
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
[ActiveIssue(5234, PlatformID.Windows)]
[Fact]
public void SendToRecvFromAsync_Single_Datagram_UDP_IPv6()
{
SendToRecvFromAsync_Datagram_UDP(IPAddress.IPv6Loopback, IPAddress.IPv6Loopback);
}
[ActiveIssue(5234, PlatformID.Windows)]
[Fact]
public void SendToRecvFromAsync_Single_Datagram_UDP_IPv4()
{
SendToRecvFromAsync_Datagram_UDP(IPAddress.Loopback, IPAddress.Loopback);
}
[Fact]
public void SendRecvAsync_Multiple_Stream_TCP_IPv6()
{
SendRecvAsync_Stream_TCP(IPAddress.IPv6Loopback, useMultipleBuffers: true);
}
[Fact]
public void SendRecvAsync_Single_Stream_TCP_IPv6()
{
SendRecvAsync_Stream_TCP(IPAddress.IPv6Loopback, useMultipleBuffers: false);
}
[Fact]
public void SendRecvAsync_TcpListener_TcpClient_IPv6()
{
SendRecvAsync_TcpListener_TcpClient(IPAddress.IPv6Loopback);
}
[Fact]
public void SendRecvAsync_Multiple_Stream_TCP_IPv4()
{
SendRecvAsync_Stream_TCP(IPAddress.Loopback, useMultipleBuffers: true);
}
[Fact]
public void SendRecvAsync_Single_Stream_TCP_IPv4()
{
SendRecvAsync_Stream_TCP(IPAddress.Loopback, useMultipleBuffers: false);
}
[Fact]
[ActiveIssue(5234, PlatformID.Windows)]
public void SendRecvAsync_TcpListener_TcpClient_IPv4()
{
SendRecvAsync_TcpListener_TcpClient(IPAddress.Loopback);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using Xunit;
using System.Diagnostics;
using System.Threading;
using Xunit.Abstractions;
namespace Apache.Geode.Client.IntegrationTests
{
public class MyOrder : IPdxSerializable
{
private const string ORDER_ID_KEY_ = "order_id";
private const string NAME_KEY_ = "name";
private const string QUANTITY_KEY_ = "quantity";
public long OrderId { get; set; }
public string Name { get; set; }
public short Quantity { get; set; }
// A default constructor is required for deserialization
public MyOrder() { }
public MyOrder(int orderId, string name, short quantity)
{
OrderId = orderId;
Name = name;
Quantity = quantity;
}
public override string ToString()
{
return string.Format("Order: [{0}, {1}, {2}]", OrderId, Name, Quantity);
}
public void ToData(IPdxWriter output)
{
output.WriteLong(ORDER_ID_KEY_, OrderId);
output.MarkIdentityField(ORDER_ID_KEY_);
output.WriteString(NAME_KEY_, Name);
output.MarkIdentityField(NAME_KEY_);
output.WriteInt(QUANTITY_KEY_, Quantity);
output.MarkIdentityField(QUANTITY_KEY_);
}
public void FromData(IPdxReader input)
{
OrderId = input.ReadLong(ORDER_ID_KEY_);
Name = input.ReadString(NAME_KEY_);
Quantity = (short)input.ReadInt(QUANTITY_KEY_);
}
public static IPdxSerializable CreateDeserializable()
{
return new MyOrder();
}
}
public abstract class CqListener<TKey, TResult> : ICqListener<TKey, TResult>
{
public AutoResetEvent RegionClearEvent { get; private set; }
public AutoResetEvent CreatedEvent { get; private set; }
public AutoResetEvent UpdatedEvent { get; private set; }
public AutoResetEvent DestroyedNonNullEvent { get; private set; }
public AutoResetEvent DestroyedNullEvent { get; private set; }
public AutoResetEvent InvalidatedEvent { get; private set; }
public bool ReceivedUnknownEventType { get; internal set; }
public CqListener()
{
CreatedEvent = new AutoResetEvent(false);
UpdatedEvent = new AutoResetEvent(false);
DestroyedNullEvent = new AutoResetEvent(false);
DestroyedNonNullEvent = new AutoResetEvent(false);
RegionClearEvent = new AutoResetEvent(false);
InvalidatedEvent = new AutoResetEvent(false);
ReceivedUnknownEventType = false;
}
public abstract void OnEvent(CqEvent<TKey, TResult> ev);
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
}
public virtual void Close()
{
}
}
public class PdxCqListener<TKey, TResult> : CqListener<TKey, TResult>
{
public override void OnEvent(CqEvent<TKey, TResult> ev)
{
Debug.WriteLine("PdxCqListener::OnEvent called");
var val = ev.getNewValue() as MyOrder;
TKey key = ev.getKey();
switch (ev.getQueryOperation())
{
case CqOperation.OP_TYPE_REGION_CLEAR:
RegionClearEvent.Set();
break;
case CqOperation.OP_TYPE_CREATE:
CreatedEvent.Set();
break;
case CqOperation.OP_TYPE_UPDATE:
UpdatedEvent.Set();
break;
case CqOperation.OP_TYPE_INVALIDATE:
InvalidatedEvent.Set();
break;
case CqOperation.OP_TYPE_DESTROY:
if (val == null)
{
DestroyedNullEvent.Set();
}
else
{
DestroyedNonNullEvent.Set();
}
break;
default:
ReceivedUnknownEventType = true;
break;
}
}
}
public class DataCqListener<TKey, TResult> : CqListener<TKey, TResult>
{
public override void OnEvent(CqEvent<TKey, TResult> ev)
{
Debug.WriteLine("CqListener::OnEvent called");
var val = ev.getNewValue() as Position;
TKey key = ev.getKey();
switch (ev.getQueryOperation())
{
case CqOperation.OP_TYPE_REGION_CLEAR:
RegionClearEvent.Set();
break;
case CqOperation.OP_TYPE_CREATE:
CreatedEvent.Set();
break;
case CqOperation.OP_TYPE_UPDATE:
UpdatedEvent.Set();
break;
case CqOperation.OP_TYPE_INVALIDATE:
InvalidatedEvent.Set();
break;
case CqOperation.OP_TYPE_DESTROY:
if (val == null)
{
DestroyedNullEvent.Set();
}
else
{
DestroyedNonNullEvent.Set();
}
break;
default:
ReceivedUnknownEventType = true;
break;
}
}
}
[Trait("Category", "Integration")]
public class CqOperationTest : TestBase
{
private static int waitInterval_ = 1000;
public CqOperationTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
{
}
[Fact]
public void PdxSerializableNotificationsHaveCorrectValues()
{
using (var cluster = new Cluster(output, CreateTestCaseDirectoryName(), 1, 1))
{
Assert.True(cluster.Start());
Assert.Equal(0, cluster.Gfsh.create()
.region()
.withName("cqTestRegion")
.withType("REPLICATE")
.execute());
var cache = cluster.CreateCache();
cache.TypeRegistry.RegisterPdxType(MyOrder.CreateDeserializable);
var pool = cluster.ApplyLocators(cache.GetPoolFactory())
.SetSubscriptionEnabled(true)
.Create("pool");
var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY)
.SetPoolName("pool");
var region = regionFactory.Create<string, MyOrder>("cqTestRegion");
var queryService = pool.GetQueryService();
var cqAttributesFactory = new CqAttributesFactory<string, MyOrder>();
var cqListener = new PdxCqListener<string, MyOrder>();
cqAttributesFactory.AddCqListener(cqListener);
var cqAttributes = cqAttributesFactory.Create();
var query = queryService.NewCq("MyCq", "SELECT * FROM /cqTestRegion WHERE quantity > 30", cqAttributes, false);
Debug.WriteLine("Executing continuous query");
query.Execute();
Debug.WriteLine("Putting and changing Position objects in the region");
var order1 = new MyOrder(1, "product x", 23);
var order2 = new MyOrder(2, "product y", 37);
var order3 = new MyOrder(3, "product z", 101);
region.Put("order1", order1);
region.Put("order2", order2);
Assert.True(cqListener.CreatedEvent.WaitOne(waitInterval_), "Didn't receive expected CREATE event");
order1.Quantity = 60;
region.Put("order1", order1);
Assert.True(cqListener.CreatedEvent.WaitOne(waitInterval_), "Didn't receive expected CREATE event");
order2.Quantity = 45;
region.Put("order2", order2);
Assert.True(cqListener.UpdatedEvent.WaitOne(waitInterval_), "Didn't receive expected UPDATE event");
order2.Quantity = 11;
region.Put("order2", order2);
Assert.True(cqListener.DestroyedNonNullEvent.WaitOne(waitInterval_), "Didn't receive expected DESTROY event");
region.Remove("order1");
Assert.True(cqListener.DestroyedNullEvent.WaitOne(waitInterval_), "Didn't receive expected DESTROY event");
region.Put("order3", order3);
Assert.True(cqListener.CreatedEvent.WaitOne(waitInterval_), "Didn't receive expected CREATE event");
region.Clear();
Assert.True(cqListener.RegionClearEvent.WaitOne(waitInterval_), "Didn't receive expected CLEAR event");
Assert.False(cqListener.ReceivedUnknownEventType, "An unknown event was received by CQ listener");
cache.Close();
}
}
[Fact]
public void DataSerializableNotificationsHaveCorrectValues()
{
using (var cluster = new Cluster(output, CreateTestCaseDirectoryName(), 1, 1))
{
Assert.True(cluster.Start());
Assert.Equal(0, cluster.Gfsh.deploy()
.withJar(Config.JavaobjectJarPath)
.execute());
Assert.Equal(0, cluster.Gfsh.create()
.region()
.withName("cqTestRegion")
.withType("REPLICATE")
.execute());
Assert.Equal(0, cluster.Gfsh.executeFunction()
.withId("InstantiateDataSerializable")
.withMember("DataSerializableNotificationsHaveCorrectValues_server_0")
.execute());
var cache = cluster.CreateCache();
cache.TypeRegistry.RegisterType(Position.CreateDeserializable, 22);
var pool = cluster.ApplyLocators(cache.GetPoolFactory())
.SetSubscriptionEnabled(true)
.Create("pool");
var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY)
.SetPoolName("pool");
var region = regionFactory.Create<string, Position>("cqTestRegion");
var queryService = pool.GetQueryService();
var cqAttributesFactory = new CqAttributesFactory<string, Position>();
var cqListener = new DataCqListener<string, Position>();
cqAttributesFactory.AddCqListener(cqListener);
var cqAttributes = cqAttributesFactory.Create();
var query = queryService.NewCq("MyCq", "SELECT * FROM /cqTestRegion WHERE sharesOutstanding > 30", cqAttributes, false);
Debug.WriteLine("Executing continuous query");
query.Execute();
Debug.WriteLine("Putting and changing Position objects in the region");
var order1 = new Position("GOOG", 23);
var order2 = new Position("IBM", 37);
var order3 = new Position("PVTL", 101);
region.Put("order1", order1);
var Value = region["order1"];
region.Put("order2", order2);
Assert.True(cqListener.CreatedEvent.WaitOne(waitInterval_), "Didn't receive expected CREATE event");
order1.SharesOutstanding = 55;
region.Put("order1", order1);
Assert.True(cqListener.CreatedEvent.WaitOne(waitInterval_), "Didn't receive expected CREATE event");
order2.SharesOutstanding = 77;
region.Put("order2", order2);
Assert.True(cqListener.UpdatedEvent.WaitOne(waitInterval_), "Didn't receive expected UPDATE event");
order2.SharesOutstanding = 11;
region.Put("order2", order2);
Assert.True(cqListener.DestroyedNonNullEvent.WaitOne(waitInterval_), "Didn't receive expected DESTROY event");
region.Remove("order1");
Assert.True(cqListener.DestroyedNullEvent.WaitOne(waitInterval_), "Didn't receive expected DESTROY event");
region.Put("order3", order3);
Assert.True(cqListener.CreatedEvent.WaitOne(waitInterval_), "Didn't receive expected CREATE event");
region.Clear();
Assert.True(cqListener.RegionClearEvent.WaitOne(waitInterval_), "Didn't receive expected CLEAR event");
Assert.False(cqListener.ReceivedUnknownEventType, "An unknown event was received by CQ listener");
cache.Close();
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type PlannerPlanTasksCollectionRequest.
/// </summary>
public partial class PlannerPlanTasksCollectionRequest : BaseRequest, IPlannerPlanTasksCollectionRequest
{
/// <summary>
/// Constructs a new PlannerPlanTasksCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public PlannerPlanTasksCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified PlannerTask to the collection via POST.
/// </summary>
/// <param name="plannerTask">The PlannerTask to add.</param>
/// <returns>The created PlannerTask.</returns>
public System.Threading.Tasks.Task<PlannerTask> AddAsync(PlannerTask plannerTask)
{
return this.AddAsync(plannerTask, CancellationToken.None);
}
/// <summary>
/// Adds the specified PlannerTask to the collection via POST.
/// </summary>
/// <param name="plannerTask">The PlannerTask to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created PlannerTask.</returns>
public System.Threading.Tasks.Task<PlannerTask> AddAsync(PlannerTask plannerTask, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<PlannerTask>(plannerTask, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IPlannerPlanTasksCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IPlannerPlanTasksCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<PlannerPlanTasksCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Expand(Expression<Func<PlannerTask, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Select(Expression<Func<PlannerTask, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanTasksCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.ObjectModel;
using System.Net;
using System.Net.Security;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.PeerResolvers;
using System.Xml;
static class PeerTransportPolicyConstants
{
public const string PeerTransportSecurityMode = "PeerTransportSecurityMode";
public const string PeerTransportCredentialType = "PeerTransportCredentialType";
public const string PeerTransportCredentialTypePassword = "PeerTransportCredentialTypePassword";
public const string PeerTransportCredentialTypeCertificate = "PeerTransportCredentialTypeCertificate";
public const string PeerTransportSecurityModeNone = "PeerTransportSecurityModeNone";
public const string PeerTransportSecurityModeTransport = "PeerTransportSecurityModeTransport";
public const string PeerTransportSecurityModeMessage = "PeerTransportSecurityModeMessage";
public const string PeerTransportSecurityModeTransportWithMessageCredential = "PeerTransportSecurityModeTransportWithMessageCredential";
public const string PeerTransportPrefix = "pc";
}
[ObsoleteAttribute ("PeerChannel feature is obsolete and will be removed in the future.", false)]
public sealed class PeerTransportBindingElement
: TransportBindingElement, IWsdlExportExtension, ITransportPolicyImport, IPolicyExportExtension
{
IPAddress listenIPAddress;
int port;
PeerResolver resolver;
bool resolverSet;
PeerSecuritySettings peerSecurity;
public PeerTransportBindingElement()
: base()
{
this.listenIPAddress = PeerTransportDefaults.ListenIPAddress;
this.port = PeerTransportDefaults.Port;
if (PeerTransportDefaults.ResolverAvailable)
{
this.resolver = PeerTransportDefaults.CreateResolver();
}
peerSecurity = new PeerSecuritySettings();
}
PeerTransportBindingElement(PeerTransportBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
this.listenIPAddress = elementToBeCloned.listenIPAddress;
this.port = elementToBeCloned.port;
this.resolverSet = elementToBeCloned.resolverSet;
this.resolver = elementToBeCloned.resolver;
peerSecurity = new PeerSecuritySettings(elementToBeCloned.Security);
}
public IPAddress ListenIPAddress
{
get
{
return this.listenIPAddress;
}
set
{
PeerValidateHelper.ValidateListenIPAddress(value);
this.listenIPAddress = value;
}
}
public override long MaxReceivedMessageSize
{
get
{
return base.MaxReceivedMessageSize;
}
set
{
PeerValidateHelper.ValidateMaxMessageSize(value);
base.MaxReceivedMessageSize = value;
}
}
public int Port
{
get
{
return this.port;
}
set
{
PeerValidateHelper.ValidatePort(value);
this.port = value;
}
}
internal PeerResolver Resolver
{
get
{
return this.resolver;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (value.GetType() == PeerTransportDefaults.ResolverType)
{
if (!PeerTransportDefaults.ResolverInstalled)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.PeerPnrpNotInstalled));
}
else if (!PeerTransportDefaults.ResolverAvailable)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.PeerPnrpNotAvailable));
}
}
this.resolver = value;
this.resolverSet = true;
}
}
public override string Scheme { get { return PeerStrings.Scheme; } }
public PeerSecuritySettings Security
{
get { return peerSecurity; }
}
void ITransportPolicyImport.ImportPolicy(MetadataImporter importer, PolicyConversionContext context)
{
if (importer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("importer");
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
peerSecurity.OnImportPolicy(importer, context);
}
void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
{
if (exporter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
}
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
peerSecurity.OnExportPolicy(exporter, context);
bool createdNew;
MessageEncodingBindingElement encodingBindingElement = FindMessageEncodingBindingElement(context.BindingElements, out createdNew);
if (createdNew && encodingBindingElement is IPolicyExportExtension)
{
((IPolicyExportExtension)encodingBindingElement).ExportPolicy(exporter, context);
}
WsdlExporter.WSAddressingHelper.AddWSAddressingAssertion(exporter, context, encodingBindingElement.MessageVersion.Addressing);
}
void IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext context) { }
void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext endpointContext)
{
bool createdNew;
MessageEncodingBindingElement encodingBindingElement = FindMessageEncodingBindingElement(endpointContext, out createdNew);
TransportBindingElement.ExportWsdlEndpoint(
exporter, endpointContext, TransportPolicyConstants.PeerTransportUri,
encodingBindingElement.MessageVersion.Addressing);
}
internal void CreateDefaultResolver(PeerResolverSettings settings)
{
if (PeerTransportDefaults.ResolverAvailable)
{
this.resolver = new PnrpPeerResolver(settings.ReferralPolicy);
}
}
MessageEncodingBindingElement FindMessageEncodingBindingElement(BindingElementCollection bindingElements, out bool createdNew)
{
createdNew = false;
MessageEncodingBindingElement encodingBindingElement = bindingElements.Find<MessageEncodingBindingElement>();
if (encodingBindingElement == null)
{
createdNew = true;
encodingBindingElement = new BinaryMessageEncodingBindingElement();
}
return encodingBindingElement;
}
MessageEncodingBindingElement FindMessageEncodingBindingElement(WsdlEndpointConversionContext endpointContext, out bool createdNew)
{
BindingElementCollection bindingElements = endpointContext.Endpoint.Binding.CreateBindingElements();
return FindMessageEncodingBindingElement(bindingElements, out createdNew);
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("context"));
}
if (!this.CanBuildChannelFactory<TChannel>(context))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
if (this.ManualAddressing)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ManualAddressingNotSupported)));
}
PeerResolver peerResolver = GetResolver(context);
return new PeerChannelFactory<TChannel>(this, context, peerResolver);
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
PeerChannelListenerBase peerListener = null;
PeerResolver peerResolver = GetResolver(context);
if (typeof(TChannel) == typeof(IInputChannel))
{
peerListener = new PeerInputChannelListener(this, context, peerResolver);
}
else if (typeof(TChannel) == typeof(IDuplexChannel))
{
peerListener = new PeerDuplexChannelListener(this, context, peerResolver);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
return (IChannelListener<TChannel>)peerListener;
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IDuplexChannel));
}
public override bool CanBuildChannelListener<TChannel>(BindingContext context)
{
return (typeof(TChannel) == typeof(IInputChannel)
|| typeof(TChannel) == typeof(IDuplexChannel));
}
public override BindingElement Clone()
{
return new PeerTransportBindingElement(this);
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(IBindingMulticastCapabilities))
{
return (T)(object)new BindingMulticastCapabilities();
}
else if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)new SecurityCapabilities(Security.SupportsAuthentication, Security.SupportsAuthentication,
false, Security.SupportedProtectionLevel, Security.SupportedProtectionLevel);
}
else if (typeof(T) == typeof(IBindingDeliveryCapabilities))
{
return (T)(object)new BindingDeliveryCapabilitiesHelper();
}
return base.GetProperty<T>(context);
}
// Return the resolver member (if set) or create one from the resolver binding element in the context
PeerResolver GetResolver(BindingContext context)
{
if (this.resolverSet)
{
return this.resolver;
}
Collection<PeerCustomResolverBindingElement> customResolverElements
= context.BindingParameters.FindAll<PeerCustomResolverBindingElement>();
if (customResolverElements.Count > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MultiplePeerCustomResolverBindingElementsInParameters)));
}
else if (customResolverElements.Count == 1)
{
context.BindingParameters.Remove<PeerCustomResolverBindingElement>();
return customResolverElements[0].CreatePeerResolver();
}
// If resolver binding element is included in the context, use it to create the resolver. elementToBeClonedwise,
// if default resolver is available, use it.
Collection<PeerResolverBindingElement> resolverBindingElements
= context.BindingParameters.FindAll<PeerResolverBindingElement>();
if (resolverBindingElements.Count > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MultiplePeerResolverBindingElementsinParameters)));
}
else if (resolverBindingElements.Count == 0)
{
if (this.resolver != null) // default resolver available?
{
return this.resolver;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.PeerResolverBindingElementRequired, context.Binding.Name)));
}
}
else if (resolverBindingElements[0].GetType() == PeerTransportDefaults.ResolverBindingElementType)
{
if (!PeerTransportDefaults.ResolverInstalled)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.PeerPnrpNotInstalled)));
}
else if (!PeerTransportDefaults.ResolverAvailable)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.PeerPnrpNotAvailable)));
}
}
context.BindingParameters.Remove<PeerResolverBindingElement>();
return resolverBindingElements[0].CreatePeerResolver();
}
class BindingMulticastCapabilities : IBindingMulticastCapabilities
{
public bool IsMulticast { get { return true; } }
}
class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities
{
internal BindingDeliveryCapabilitiesHelper()
{
}
bool IBindingDeliveryCapabilities.AssuresOrderedDelivery
{
get { return false; }
}
bool IBindingDeliveryCapabilities.QueuedDelivery
{
get { return false; }
}
}
}
}
| |
/*
This file is licensed to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Collections.Generic;
using System.Xml;
using NUnit.Framework;
using InputBuilder = Org.XmlUnit.Builder.Input;
namespace Org.XmlUnit.Util {
[TestFixture]
public class NodesTest {
private const string FOO = "foo";
private const string BAR = "bar";
private const string SOME_URI = "urn:some:uri";
private XmlDocument doc;
[SetUp]
public void CreateDoc() {
doc = new XmlDocument();
}
[Test] public void QNameOfElementWithNoNs() {
XmlElement e = doc.CreateElement(FOO);
XmlQualifiedName q = Nodes.GetQName(e);
Assert.AreEqual(FOO, q.Name);
Assert.AreEqual(string.Empty, q.Namespace);
Assert.AreEqual(new XmlQualifiedName(FOO), q);
}
[Test] public void QNameOfXmlElementWithNsNoPrefix() {
XmlElement e = doc.CreateElement(FOO, SOME_URI);
XmlQualifiedName q = Nodes.GetQName(e);
Assert.AreEqual(FOO, q.Name);
Assert.AreEqual(SOME_URI, q.Namespace);
Assert.AreEqual(new XmlQualifiedName(FOO, SOME_URI), q);
}
[Test] public void QNameOfXmlElementWithNsAndPrefix() {
XmlElement e = doc.CreateElement(BAR, FOO, SOME_URI);
XmlQualifiedName q = Nodes.GetQName(e);
Assert.AreEqual(FOO, q.Name);
Assert.AreEqual(SOME_URI, q.Namespace);
Assert.AreEqual(new XmlQualifiedName(FOO, SOME_URI), q);
}
[Test] public void MergeNoTexts() {
XmlElement e = doc.CreateElement(FOO);
Assert.AreEqual(string.Empty, Nodes.GetMergedNestedText(e));
}
[Test] public void MergeSingleTextNode() {
XmlElement e = doc.CreateElement(FOO);
XmlText t = doc.CreateTextNode(BAR);
e.AppendChild(t);
Assert.AreEqual(BAR, Nodes.GetMergedNestedText(e));
}
[Test] public void MergeSingleCDATASection() {
XmlElement e = doc.CreateElement(FOO);
XmlCDataSection t = doc.CreateCDataSection(BAR);
e.AppendChild(t);
Assert.AreEqual(BAR, Nodes.GetMergedNestedText(e));
}
[Test] public void MergeIgnoresTextOfChildren() {
XmlElement e = doc.CreateElement(FOO);
XmlElement c = doc.CreateElement("child");
XmlText t = doc.CreateTextNode(BAR);
e.AppendChild(c);
c.AppendChild(t);
Assert.AreEqual(string.Empty, Nodes.GetMergedNestedText(e));
}
[Test] public void MergeIgnoresComments() {
XmlElement e = doc.CreateElement(FOO);
XmlComment c = doc.CreateComment(BAR);
e.AppendChild(c);
Assert.AreEqual(string.Empty, Nodes.GetMergedNestedText(e));
}
[Test] public void MergeMultipleChildren() {
XmlElement e = doc.CreateElement(FOO);
XmlCDataSection c = doc.CreateCDataSection(BAR);
e.AppendChild(c);
e.AppendChild(doc.CreateElement("child"));
XmlText t = doc.CreateTextNode(BAR);
e.AppendChild(t);
Assert.AreEqual(BAR + BAR, Nodes.GetMergedNestedText(e));
}
[Test] public void AttributeMapNoAttributes() {
XmlElement e = doc.CreateElement(FOO);
IDictionary<XmlQualifiedName, string> m = Nodes.GetAttributes(e);
Assert.AreEqual(0, m.Count);
}
[Test] public void AttributeIDictionaryNoNS() {
XmlElement e = doc.CreateElement(FOO);
e.SetAttribute(FOO, BAR);
IDictionary<XmlQualifiedName, string> m = Nodes.GetAttributes(e);
Assert.AreEqual(1, m.Count);
Assert.AreEqual(BAR, m[new XmlQualifiedName(FOO)]);
}
[Test] public void AttributeIDictionarywithNS() {
XmlElement e = doc.CreateElement(FOO);
e.SetAttribute(FOO, SOME_URI, BAR);
IDictionary<XmlQualifiedName, string> m = Nodes.GetAttributes(e);
Assert.AreEqual(1, m.Count);
Assert.AreEqual(BAR, m[new XmlQualifiedName(FOO, SOME_URI)]);
}
private XmlDocument HandleWsSetup() {
return Convert.ToDocument(InputBuilder.FromString(
"<root>\n"
+ "<!-- trim\tme -->\n"
+ "<child attr=' trim me ' attr2='not me'>\n"
+ " trim me \n"
+ "</child><![CDATA[ trim me ]]>\n"
+ "<?target trim me ?>\n"
+ "<![CDATA[ ]]>\n"
+ "</root>").Build());
}
private KeyValuePair<XmlDocument, XmlNode> StripWsSetup() {
XmlDocument toTest = HandleWsSetup();
return new KeyValuePair<XmlDocument,
XmlNode>(toTest, Nodes.StripWhitespace(toTest));
}
private KeyValuePair<XmlDocument, XmlNode> NormalizeWsSetup() {
XmlDocument toTest = HandleWsSetup();
return new KeyValuePair<XmlDocument,
XmlNode>(toTest, Nodes.NormalizeWhitespace(toTest));
}
[Test]
public void StripWhitespaceWorks() {
HandleWsWorks(StripWsSetup(), "trim\tme");
}
[Test]
public void NormalizeWhitespaceWorks() {
HandleWsWorks(NormalizeWsSetup(), "trim me");
}
private void HandleWsWorks(KeyValuePair<XmlDocument, XmlNode> s,
string commentContent) {
Assert.IsTrue(s.Value is XmlDocument);
XmlNodeList top = s.Value.ChildNodes;
Assert.AreEqual(1, top.Count);
Assert.IsTrue(top[0] is XmlElement);
Assert.AreEqual("root", top[0].Name);
XmlNodeList rootsChildren = top[0].ChildNodes;
Assert.AreEqual(4, rootsChildren.Count);
Assert.IsTrue(rootsChildren[0] is XmlComment,
"should be comment, is " + rootsChildren[0].GetType());
Assert.AreEqual(commentContent,
((XmlComment) rootsChildren[0]).Data);
Assert.IsTrue(rootsChildren[1] is XmlElement,
"should be element, is " + rootsChildren[1].GetType());
Assert.AreEqual("child", rootsChildren[1].Name);
Assert.IsTrue(rootsChildren[2] is XmlCDataSection,
"should be cdata, is " + rootsChildren[2].GetType());
Assert.AreEqual("trim me",
((XmlCDataSection) rootsChildren[2]).Data);
Assert.IsTrue(rootsChildren[3] is XmlProcessingInstruction,
"should be PI, is " + rootsChildren[3].GetType());
Assert.AreEqual("trim me",
((XmlProcessingInstruction) rootsChildren[3]).Data);
XmlNode child = rootsChildren[1];
XmlNodeList grandChildren = child.ChildNodes;
Assert.AreEqual(1, grandChildren.Count);
Assert.IsTrue(grandChildren[0] is XmlText,
"should be text, is " + grandChildren[0].GetType());
Assert.AreEqual("trim me", ((XmlText) grandChildren[0]).Data);
XmlNamedNodeMap attrs = child.Attributes;
Assert.AreEqual(2, attrs.Count);
XmlAttribute a = (XmlAttribute) attrs.GetNamedItem("attr");
Assert.AreEqual("trim me", a.Value);
XmlAttribute a2 = (XmlAttribute) attrs.GetNamedItem("attr2");
Assert.AreEqual("not me", a2.Value);
}
[Test]
public void StripWhitespaceDoesntAlterOriginal() {
HandleWsDoesntAlterOriginal(StripWsSetup());
}
[Test]
public void NormalizeWhitespaceDoesntAlterOriginal() {
HandleWsDoesntAlterOriginal(NormalizeWsSetup());
}
private void HandleWsDoesntAlterOriginal(KeyValuePair<XmlDocument,
XmlNode> s) {
XmlNodeList top = s.Key.ChildNodes;
Assert.AreEqual(1, top.Count);
Assert.IsTrue(top[0] is XmlElement);
Assert.AreEqual("root", top[0].Name);
XmlNodeList rootsChildren = top[0].ChildNodes;
Assert.AreEqual(5, rootsChildren.Count);
Assert.IsTrue(rootsChildren[0] is XmlComment,
"should be comment, is " + rootsChildren[0].GetType());
Assert.AreEqual(" trim\tme ",
((XmlComment) rootsChildren[0]).Data);
Assert.IsTrue(rootsChildren[1] is XmlElement,
"should be element, is " + rootsChildren[1].GetType());
Assert.AreEqual("child", rootsChildren[1].Name);
Assert.IsTrue(rootsChildren[2] is XmlCDataSection,
"should be cdata, is " + rootsChildren[2].GetType());
Assert.AreEqual(" trim me ",
((XmlCDataSection) rootsChildren[2]).Data);
Assert.IsTrue(rootsChildren[3] is XmlProcessingInstruction,
"should be PI, is " + rootsChildren[3].GetType());
Assert.AreEqual("trim me ",
((XmlProcessingInstruction) rootsChildren[3]).Data);
Assert.IsTrue(rootsChildren[4] is XmlCDataSection,
"should be cdata, is " + rootsChildren[4].GetType());
Assert.AreEqual(" ",
((XmlCDataSection) rootsChildren[4]).Data);
XmlNode child = rootsChildren[1];
XmlNodeList grandChildren = child.ChildNodes;
Assert.AreEqual(1, grandChildren.Count);
Assert.IsTrue(grandChildren[0] is XmlText,
"should be text, is " + grandChildren[0].GetType());
Assert.AreEqual("\n trim me \n", ((XmlText) grandChildren[0]).Data);
XmlNamedNodeMap attrs = child.Attributes;
Assert.AreEqual(2, attrs.Count);
XmlAttribute a = (XmlAttribute) attrs.GetNamedItem("attr");
Assert.AreEqual(" trim me ", a.Value);
XmlAttribute a2 = (XmlAttribute) attrs.GetNamedItem("attr2");
Assert.AreEqual("not me", a2.Value);
}
[Test]
public void Normalize() {
Assert.AreSame("foo", Nodes.Normalize("foo"));
Assert.AreSame("foo bar", Nodes.Normalize("foo bar"));
Assert.AreEqual("foo bar", Nodes.Normalize("foo\nbar"));
Assert.AreEqual("foo bar", Nodes.Normalize("foo \r\n\t bar"));
}
[Test]
public void StripECWWorks() {
XmlNode orig = HandleWsSetup();
XmlNode s = Nodes.StripElementContentWhitespace(orig);
Assert.IsTrue(s is XmlDocument);
XmlNodeList top = s.ChildNodes;
Assert.AreEqual(1, top.Count);
Assert.IsTrue(top[0] is XmlElement);
Assert.AreEqual("root", top[0].Name);
XmlNodeList rootsChildren = top[0].ChildNodes;
Assert.AreEqual(4, rootsChildren.Count);
Assert.IsTrue(rootsChildren[0] is XmlComment,
"should be comment, is " + rootsChildren[0].GetType());
Assert.AreEqual(" trim\tme ",
((XmlComment) rootsChildren[0]).Data);
Assert.IsTrue(rootsChildren[1] is XmlElement,
"should be element, is " + rootsChildren[1].GetType());
Assert.AreEqual("child", rootsChildren[1].Name);
Assert.IsTrue(rootsChildren[2] is XmlCDataSection,
"should be cdata, is " + rootsChildren[2].GetType());
Assert.AreEqual(" trim me ",
((XmlCDataSection) rootsChildren[2]).Data);
Assert.IsTrue(rootsChildren[3] is XmlProcessingInstruction,
"should be PI, is " + rootsChildren[3].GetType());
Assert.AreEqual("trim me ",
((XmlProcessingInstruction) rootsChildren[3]).Data);
XmlNode child = rootsChildren[1];
XmlNodeList grandChildren = child.ChildNodes;
Assert.AreEqual(1, grandChildren.Count);
Assert.IsTrue(grandChildren[0] is XmlText,
"should be text, is " + grandChildren[0].GetType());
Assert.AreEqual("\n trim me \n", ((XmlText) grandChildren[0]).Data);
XmlNamedNodeMap attrs = child.Attributes;
Assert.AreEqual(2, attrs.Count);
XmlAttribute a = (XmlAttribute) attrs.GetNamedItem("attr");
Assert.AreEqual(" trim me ", a.Value);
XmlAttribute a2 = (XmlAttribute) attrs.GetNamedItem("attr2");
Assert.AreEqual("not me", a2.Value);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A vet's office.
/// </summary>
public class VeterinaryCare_Core : TypeCore, IMedicalOrganization
{
public VeterinaryCare_Core()
{
this._TypeId = 283;
this._Id = "VeterinaryCare";
this._Schema_Org_Url = "http://schema.org/VeterinaryCare";
string label = "";
GetLabel(out label, "VeterinaryCare", typeof(VeterinaryCare_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,163};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{163};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
#if SILVERLIGHT
using Window = DevExpress.Xpf.Core.DXWindow;
using Microsoft.Silverlight.Testing;
#else
using NUnit.Framework;
#endif
using DevExpress.Mvvm.Tests;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using DevExpress.Mvvm.Native;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.POCO;
namespace DevExpress.Mvvm.UI.Tests {
[TestFixture]
public class WindowedDocumentUIServiceTests : BaseWpfFixture {
public class EmptyView : FrameworkElement { }
#if !SILVERLIGHT
class TestStyleSelector : StyleSelector {
public Style Style { get; set; }
public override Style SelectStyle(object item, DependencyObject container) { return Style; }
}
#endif
class ViewModelWithNullTitle : IDocumentContent {
public IDocumentOwner DocumentOwner { get; set; }
void IDocumentContent.OnClose(CancelEventArgs e) { }
object IDocumentContent.Title { get { return null; } }
void IDocumentContent.OnDestroy() { }
}
protected override void SetUpCore() {
base.SetUpCore();
ViewLocator.Default = new TestViewLocator(this);
}
protected override void TearDownCore() {
Interaction.GetBehaviors(Window).Clear();
ViewLocator.Default = null;
base.TearDownCore();
}
[Test, Asynchronous]
public void WindowStyle() {
EnqueueShowWindow();
IDocument document = null;
EnqueueCallback(() => {
WindowedDocumentUIService service = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(service);
service.WindowType = typeof(Window);
Style windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(FrameworkElement.TagProperty, "Style Tag"));
service.WindowStyle = windowStyle;
document = service.CreateDocument("EmptyView", new object());
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
var windowDocument = (WindowedDocumentUIService.WindowDocument)document;
Assert.AreEqual("Style Tag", windowDocument.Window.RealWindow.Tag);
});
EnqueueTestComplete();
}
public class UITestViewModel {
public virtual string Title { get; set; }
public virtual int Parameter { get; set; }
}
[Test, Asynchronous]
public void ActivateWhenDocumentShow() {
EnqueueShowWindow();
IDocument document = null;
WindowedDocumentUIService service = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
EnqueueCallback(() => {
document = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document);
document.Close();
});
EnqueueTestComplete();
}
[Test, Asynchronous]
public void UnActiveDocumentClose() {
EnqueueShowWindow();
IDocument document1 = null;
IDocument document2 = null;
WindowedDocumentUIService service = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
EnqueueCallback(() => {
iService.ActiveDocumentChanged += (s, e) => counter++;
document1 = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document2 = iService.CreateDocument("View2",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document1.Show();
Assert.AreEqual(1, counter);
document2.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document2);
document1.Close();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document2);
#if !SILVERLIGHT
Assert.AreEqual(3, counter);
#else
Assert.AreEqual(2, counter);
#endif
document2.Close();
});
EnqueueTestComplete();
}
[Test, Asynchronous]
public void SettingActiveDocument() {
EnqueueShowWindow();
IDocument document1 = null;
IDocument document2 = null;
WindowedDocumentUIService service = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
EnqueueCallback(() => {
iService.ActiveDocumentChanged += (s, e) => counter++;
document1 = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document2 = iService.CreateDocument("View2",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document1.Show();
document2.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
#if !SILVERLIGHT
Assert.AreEqual(3, counter);
#else
Assert.AreEqual(2, counter);
#endif
iService.ActiveDocument = document1;
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document1);
#if !SILVERLIGHT
Assert.AreEqual(4, counter);
#else
Assert.AreEqual(3, counter);
#endif
document1.Close();
document2.Close();
});
EnqueueTestComplete();
}
#if !SILVERLIGHT
[Test, Asynchronous]
public void ActivateDocumentsWhenClosed() {
EnqueueShowWindow();
List<IDocument> documents = new List<IDocument>();
WindowedDocumentUIService service = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
EnqueueCallback(() => {
service.ActiveDocumentChanged += (s, e) => counter++;
for(int i = 0; i < 4; i++) {
documents.Add(iService.CreateDocument("View" + i,
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title" + i, Parameter = i })));
documents[i].Show();
}
iService.ActiveDocument = documents[1];
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
counter = 0;
documents[1].Close();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(2, counter);
Assert.AreEqual(iService.ActiveDocument, documents[3]);
iService.ActiveDocument = documents[3];
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
counter = 0;
documents[3].Close();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, documents[2]);
Assert.AreEqual(2, counter);
documents[0].Close();
documents[2].Close();
});
EnqueueTestComplete();
}
#endif
#if !SILVERLIGHT
[Test]
public void WindowStyleSelector() {
WindowedDocumentUIService service = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(service);
service.WindowType = typeof(Window);
Style windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(System.Windows.Window.TagProperty, "Style Selector Tag"));
service.WindowStyleSelector = new TestStyleSelector() { Style = windowStyle };
IDocument document = service.CreateDocument("EmptyView", new object());
var windowDocument = (WindowedDocumentUIService.WindowDocument)document;
Assert.AreEqual("Style Selector Tag", windowDocument.Window.RealWindow.Tag);
}
#endif
}
[TestFixture]
public class WindowedDocumentUIServiceIDocumentContentCloseTests : BaseWpfFixture {
public class EmptyView : FrameworkElement { }
class TestDocumentContent : IDocumentContent {
Func<bool> close;
Action onDestroy;
public TestDocumentContent(Func<bool> close, Action onDestroy = null) {
this.close = close;
this.onDestroy = onDestroy;
}
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) { e.Cancel = !close(); }
public object Title { get { return null; } }
void IDocumentContent.OnDestroy() {
if(onDestroy != null)
onDestroy();
}
}
protected override void SetUpCore() {
base.SetUpCore();
ViewLocator.Default = new TestViewLocator(this);
}
protected override void TearDownCore() {
Interaction.GetBehaviors(Window).Clear();
ViewLocator.Default = null;
base.TearDownCore();
}
void DoCloseTest(bool allowClose, bool destroyOnClose, bool destroyed, Action<IDocument> closeMethod) {
DoCloseTest((bool?)allowClose, destroyOnClose, destroyed, (d, b) => closeMethod(d));
}
void DoCloseTest(bool? allowClose, bool destroyOnClose, bool destroyed, Action<IDocument, bool> closeMethod) {
EnqueueShowWindow();
IDocumentManagerService service = null;
bool closeChecked = false;
bool destroyCalled = false;
IDocument document = null;
EnqueueCallback(() => {
WindowedDocumentUIService windowedDocumentUIService = new WindowedDocumentUIService();
Interaction.GetBehaviors(Window).Add(windowedDocumentUIService);
service = windowedDocumentUIService;
TestDocumentContent viewModel = new TestDocumentContent(() => {
closeChecked = true;
return allowClose != null && allowClose.Value;
}, () => {
destroyCalled = true;
});
document = service.CreateDocument("EmptyView", viewModel);
document.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
document.DestroyOnClose = destroyOnClose;
closeMethod(document, allowClose == null);
Assert.AreEqual(allowClose != null, closeChecked);
Assert.AreEqual(destroyed, destroyCalled);
Assert.AreEqual(!destroyed, service.Documents.Contains(document));
});
EnqueueTestComplete();
}
void CloseDocument(IDocument document, bool force) {
document.Close(force);
}
void CloseDocumentWithDocumentOwner(IDocument document, bool force) {
IDocumentContent documentContent = (IDocumentContent)document.Content;
documentContent.DocumentOwner.Close(documentContent, force);
}
void CloseDocumentWithClosingWindow(IDocument document) {
Window window = ((WindowedDocumentUIService.WindowDocument)document).Window.RealWindow;
window.Close();
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest1() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest2() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest12() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest3() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest4() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest14() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest5() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest6() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest16() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest7() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest8() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest18() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest9() {
DoCloseTest(allowClose: null, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest10() {
DoCloseTest(allowClose: null, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest11() {
DoCloseTest(allowClose: null, destroyOnClose: true, destroyed: true, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest13() {
DoCloseTest(allowClose: null, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithDocumentOwner);
}
}
public class TestViewLocator : IViewLocator {
Dictionary<string, Type> types;
IViewLocator innerViewLocator;
public TestViewLocator(object ownerTypeInstance, IViewLocator innerViewLocator = null) : this(ownerTypeInstance.GetType(), innerViewLocator) { }
public TestViewLocator(Type ownerType, IViewLocator innerViewLocator = null) {
this.innerViewLocator = innerViewLocator;
types = ownerType.GetNestedTypes(BindingFlags.Public).ToDictionary(t => t.Name, t => t);
}
object IViewLocator.ResolveView(string name) {
Type type;
return types.TryGetValue(name, out type) ? Activator.CreateInstance(type) : innerViewLocator.With(i => i.ResolveView(name));
}
Type IViewLocator.ResolveViewType(string name) {
throw new NotImplementedException();
}
}
}
| |
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Internal.Core;
namespace ArcGIS.Desktop.Catalog.ApiTests.CodeSamples
{
class CatalogCodeSamples
{
/// <summary>
/// Sample code for ProjectItem
/// </summary>
public async Task ProjectItemExamples()
{
// not to be included in sample regions
var projectFolderConnection = (Project.Current.GetItems<FolderConnectionProjectItem>()).First();
#region GetMapProjectItems
/// Get all the maps in a project
IEnumerable<MapProjectItem> projectMaps = Project.Current.GetItems<MapProjectItem>();
#endregion //GetMapProjectItems
// cref: GetFolderConnectionProjectItems;ArcGIS.Desktop.Catalog.FolderConnectionProjectItem
#region GetFolderConnectionProjectItems
/// Get all the folder connections in a project
IEnumerable<FolderConnectionProjectItem> projectFolders = Project.Current.GetItems<FolderConnectionProjectItem>();
#endregion //GetFolderConnectiontProjectItems
// cref: GetServerConnectionProjectItems;ArcGIS.Desktop.Catalog.ServerConnectionProjectItem
#region GetServerConnectionProjectItems
/// Get all the server connections in a project
IEnumerable<ServerConnectionProjectItem> projectServers = Project.Current.GetItems<ServerConnectionProjectItem>();
#endregion //GetServerConnectionProjectItems
// cref: GetLocatorConnectionProjectItems;ArcGIS.Desktop.Catalog.LocatorsConnectionProjectItem
#region GetLocatorConnectionProjectItems
/// Get all the locator connections in a project
IEnumerable<LocatorsConnectionProjectItem> projectLocators = Project.Current.GetItems<LocatorsConnectionProjectItem>();
#endregion //GetLocatorConnectionProjectItems
#region GetProjectItemContent
/// Get all the items that can be accessed from a folder connection. The items immediately
/// contained by a folder, that is, the folder's children, are returned including folders
/// and individual items that can be used in ArcGIS Pro. This method does not return all
/// items contained by any sub-folder that can be accessed from the folder connection.
FolderConnectionProjectItem folderConnection = Project.Current.GetItems<FolderConnectionProjectItem>()
.FirstOrDefault((folder => folder.Name.Equals("Data")));
await QueuedTask.Run(() =>
{
IEnumerable<Item> folderContents = folderConnection.GetItems();
});
#endregion //GetProjectItems
#region AddFolderConnectionProjectItem
/// Add a folder connection to a project
Item folderToAdd = ItemFactory.Instance.Create(@"C:\Data\Oregon\Counties\Streets");
bool wasAdded = await QueuedTask.Run(() => Project.Current.AddItem(folderToAdd as IProjectItem));
#endregion //AddFolderConnectionProjectItem
// cref: AddGDBProjectItem;ArcGIS.Desktop.Catalog.GDBProjectItem
#region AddGDBProjectItem
/// Add a file geodatabase or a SQLite or enterprise database connection to a project
Item gdbToAdd = folderToAdd.GetItems().FirstOrDefault(folderItem => folderItem.Name.Equals("CountyData.gdb"));
var addedGeodatabase = await QueuedTask.Run(() => Project.Current.AddItem(gdbToAdd as IProjectItem));
#endregion //AddGDBProjectItem
// cref: RemoveFolderConnectionFromProject;ArcGIS.Desktop.Catalog.FolderConnectionProjectItem
#region RemoveFolderConnectionFromProject
/// Remove a folder connection from a project; the folder stored on the local disk
/// or the network is not deleted
FolderConnectionProjectItem folderToRemove = Project.Current.GetItems<FolderConnectionProjectItem>().FirstOrDefault(folder => folder.Name.Equals("PlantSpecies"));
if (folderToRemove != null)
Project.Current.RemoveItem(folderToRemove as IProjectItem);
#endregion //RemoveFolderConnectionFromProject
#region RemoveMapFromProject
/// Remove a map from a project; the map is deleted
IProjectItem mapToRemove = Project.Current.GetItems<MapProjectItem>().FirstOrDefault(map => map.Name.Equals("OldStreetRoutes"));
var removedMapProjectItem = await QueuedTask.Run(
() => Project.Current.RemoveItem(mapToRemove));
#endregion //RemoveMapFromProject
#region ImportToProject
/// Import a mxd
Item mxdToImport = ItemFactory.Instance.Create(@"C:\Projects\RegionalSurvey\LatestResults.mxd");
var addedMxd = await QueuedTask.Run(
() => Project.Current.AddItem(mxdToImport as IProjectItem));
/// Add map package
Item mapPackageToAdd = ItemFactory.Instance.Create(@"c:\Data\Map.mpkx");
var addedMapPackage = await QueuedTask.Run(
() => Project.Current.AddItem(mapPackageToAdd as IProjectItem));
/// Add an exported Pro map
Item proMapToAdd = ItemFactory.Instance.Create(@"C:\ExportedMaps\Election\Districts.mapx");
var addedMapProjectItem = await QueuedTask.Run(
() => Project.Current.AddItem(proMapToAdd as IProjectItem));
#endregion //ImportToProject
}
/// <summary>
/// Sample Code for Item.
/// </summary>
public async Task ItemExamples()
{
// not to be included in sample regions
var projectfolderConnection = (Project.Current.GetItems<FolderConnectionProjectItem>()).First();
#region CreateAnItem
Item mxdItem = ItemFactory.Instance.Create(@"C:\Projects\RegionalSurvey\LatestResults.mxd");
#endregion //CreateAnItem
#region CreateAPortalItem
// Creates an Item from an existing portal item base on its ID
string portalItemID = "9801f878ff4a22738dff3f039c43e395";
Item portalItem = ItemFactory.Instance.Create(portalItemID, ItemFactory.ItemType.PortalItem);
#endregion
#region CreateAPortalFolder
// Creates an Item from an existing portal folder base on its ID
string portalFolderID = "39c43e39f878f4a2279838dfff3f0015";
Item portalFolder = ItemFactory.Instance.Create(portalFolderID, ItemFactory.ItemType.PortalFolderItem);
#endregion
#region GetItemContent
var folderConnectionContent = projectfolderConnection.GetItems();
var folder = folderConnectionContent.FirstOrDefault(folderItem => folderItem.Name.Equals("Tourist Sites"));
var folderContents = folder.GetItems();
#endregion //GetItemContent
#region
#endregion
}
#region
#endregion
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
#endregion Namespaces
/// <summary>
/// Class with the responsibility of resolving media types (MIME types) into formats and payload kinds.
/// </summary>
internal sealed class MediaTypeResolver
{
/// <summary>application/atom+xml media type</summary>
private static readonly MediaType ApplicationAtomXmlMediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeAtomXmlSubType);
/// <summary>application/xml media type</summary>
private static readonly MediaType ApplicationXmlMediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeXmlSubType);
/// <summary>text/xml media type</summary>
private static readonly MediaType TextXmlMediaType = new MediaType(MimeConstants.MimeTextType, MimeConstants.MimeXmlSubType);
/// <summary>application/json media type</summary>
private static readonly MediaType ApplicationJsonMediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeJsonSubType);
/// <summary>application/json;odata=verbose media type</summary>
private static readonly MediaType ApplicationJsonVerboseMediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeJsonSubType, new KeyValuePair<string, string>(MimeConstants.MimeODataParameterName, MimeConstants.MimeODataParameterValueVerbose));
#region Default media types per payload kind
/// <summary>
/// An array that maps stores the supported media types for all <see cref="ODataPayloadKind"/> .
/// </summary>
/// <remarks>
/// The set of supported media types is ordered (desc) by their precedence/priority with respect to (1) format and (2) media type.
/// As a result the default media type for a given payloadKind is the first entry in the MediaTypeWithFormat array.
/// </remarks>
private static readonly MediaTypeWithFormat[][] defaultMediaTypes =
new MediaTypeWithFormat[13][]
{
// feed
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeAtomXmlSubType, new KeyValuePair<string, string>(MimeConstants.MimeTypeParameterName, MimeConstants.MimeTypeParameterValueFeed)) },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// entry
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeAtomXmlSubType, new KeyValuePair<string, string>(MimeConstants.MimeTypeParameterName, MimeConstants.MimeTypeParameterValueEntry)) },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// property
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = TextXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// entity reference link
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = TextXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// entity reference links
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = TextXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// value
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.RawValue, MediaType = new MediaType(MimeConstants.MimeTextType, MimeConstants.MimePlainSubType) },
},
// binary
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.RawValue, MediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeOctetStreamSubType) },
},
// collection
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = TextXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// service document
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeAtomSvcXmlSubType) },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// metadata document
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Metadata, MediaType = ApplicationXmlMediaType },
},
// error
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
// batch
new MediaTypeWithFormat[]
{
// Note that as per spec the multipart/mixed must have a boundary parameter which is not specified here. We will add that parameter
// when using this mime type because we need to generate a new boundary every time.
new MediaTypeWithFormat { Format = ODataFormat.Batch, MediaType = new MediaType(MimeConstants.MimeMultipartType, MimeConstants.MimeMixedSubType) },
},
// parameter
new MediaTypeWithFormat[]
{
// We will only support parameters in Json format for now.
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonVerboseMediaType }
},
};
#endregion Default media types per payload kind
#region Additional WCF DS client media types for pre-v3 payloads.
/// <summary>
/// Additional media types per payload kind for the WCF DS client on pre-v3 payloads.
/// Anything that normally accepts application/atom+xml should also accept application/xml, and vice versa.
/// </summary>
private static readonly Dictionary<ODataPayloadKind, MediaTypeWithFormat[]> additionalClientV2MediaTypes =
new Dictionary<ODataPayloadKind, MediaTypeWithFormat[]>(EqualityComparer<ODataPayloadKind>.Default)
{
{
ODataPayloadKind.Feed,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeXmlSubType, new KeyValuePair<string, string>(MimeConstants.MimeTypeParameterName, MimeConstants.MimeTypeParameterValueFeed)) },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
}
},
{
ODataPayloadKind.Entry,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = new MediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeXmlSubType, new KeyValuePair<string, string>(MimeConstants.MimeTypeParameterName, MimeConstants.MimeTypeParameterValueEntry)) },
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationXmlMediaType },
}
},
{
ODataPayloadKind.Property,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
{
ODataPayloadKind.EntityReferenceLink,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
{
ODataPayloadKind.EntityReferenceLinks,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
{
ODataPayloadKind.Collection,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
{
ODataPayloadKind.ServiceDocument,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
{
ODataPayloadKind.MetadataDocument,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
{
ODataPayloadKind.Error,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.Atom, MediaType = ApplicationAtomXmlMediaType },
}
},
};
#endregion Additional WCF DS client media types for pre-v3 payloads.
/// <summary>
/// Additional media types that create following effect:
/// Wherever we normally have json verbose, add plain application/json as well
/// </summary>
/// <remarks>
/// This is used for V1 and V2 payloads when "application/json" means "application/json;odata=verbose".
/// In V3 and beyond, "application/json" means "application/json;odata=verbose".
/// </remarks>
private static readonly Dictionary<ODataPayloadKind, MediaTypeWithFormat[]> plainAppJsonMeansVerbose =
new Dictionary<ODataPayloadKind, MediaTypeWithFormat[]>(EqualityComparer<ODataPayloadKind>.Default)
{
{
ODataPayloadKind.Feed,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.Entry,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.Property,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.EntityReferenceLink,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.EntityReferenceLinks,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.Collection,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.ServiceDocument,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.Error,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
},
{
ODataPayloadKind.Parameter,
new MediaTypeWithFormat[]
{
new MediaTypeWithFormat { Format = ODataFormat.VerboseJson, MediaType = ApplicationJsonMediaType }
}
}
};
/// <summary>
/// Backing field for the default media type resolver.
/// This gets initialized when the corresponding property is first accessed.
/// </summary>
private static MediaTypeResolver defaultMediaTypeResolver;
/// <summary>
/// Array of supported media types and formats for each payload kind.
/// The index into the array matches the order of the ODataPayloadKind enum.
/// </summary>
private MediaTypeWithFormat[][] mediaTypesForPayloadKind;
/// <summary>
/// Creates a new media type resolver with the default mappings.
/// </summary>
/// <param name="shouldPlainAppJsonImplyVerboseJson">Whether "application/json" with no "odata" parameter should be interpreted as "application/json;odata=verbose"</param>
/// <param name="shouldAppXmlAndAppAtomXmlBeInterchangeable">Whether "application/xml" and "application/atom+xml" should be interchangeable.</param>
internal MediaTypeResolver(bool shouldPlainAppJsonImplyVerboseJson, bool shouldAppXmlAndAppAtomXmlBeInterchangeable)
{
DebugUtils.CheckNoExternalCallers();
this.mediaTypesForPayloadKind = new MediaTypeWithFormat[defaultMediaTypes.Length][];
for (int i = 0; i < defaultMediaTypes.Length; i++)
{
this.mediaTypesForPayloadKind[i] = new MediaTypeWithFormat[defaultMediaTypes[i].Length];
defaultMediaTypes[i].CopyTo(this.mediaTypesForPayloadKind[i], 0);
}
if (shouldPlainAppJsonImplyVerboseJson)
{
this.AddCustomMediaTypes(plainAppJsonMeansVerbose);
}
if (shouldAppXmlAndAppAtomXmlBeInterchangeable)
{
this.AddCustomMediaTypes(additionalClientV2MediaTypes);
}
}
/// <summary>
/// Accesses the default media type resolver.
/// </summary>
public static MediaTypeResolver DefaultMediaTypeResolver
{
get
{
if (defaultMediaTypeResolver == null)
{
defaultMediaTypeResolver = new MediaTypeResolver(
false /*shouldPlainAppJsonImplyVerboseJson*/,
false /*shouldAppXmlAndAppAtomXmlBeInterchangeable*/);
}
return defaultMediaTypeResolver;
}
}
/// <summary>
/// Gets the supported media types and formats for the given payload kind.
/// </summary>
/// <param name="payloadKind">The payload kind to get media types for.</param>
/// <returns>An array of media type / format pairs, sorted by priority.</returns>
internal MediaTypeWithFormat[] GetMediaTypesForPayloadKind(ODataPayloadKind payloadKind)
{
DebugUtils.CheckNoExternalCallers();
return this.mediaTypesForPayloadKind[(int)payloadKind];
}
/// <summary>
/// Modifies the MediaTypeResolver to include additional media types.
/// </summary>
/// <param name="customMediaTypes">The payload kind mappings to add.</param>
private void AddCustomMediaTypes(Dictionary<ODataPayloadKind, MediaTypeWithFormat[]> customMediaTypes)
{
foreach (KeyValuePair<ODataPayloadKind, MediaTypeWithFormat[]> payloadKindMediaTypePair in customMediaTypes)
{
MediaTypeWithFormat[] newMappings = payloadKindMediaTypePair.Value;
MediaTypeWithFormat[] existingMappings = this.mediaTypesForPayloadKind[(int)payloadKindMediaTypePair.Key];
MediaTypeWithFormat[] combinedMappings = new MediaTypeWithFormat[existingMappings.Length + newMappings.Length];
// Copy the existing and new mappings into the combinedMappings array.
existingMappings.CopyTo(combinedMappings, 0);
newMappings.CopyTo(combinedMappings, existingMappings.Length);
this.mediaTypesForPayloadKind[(int)payloadKindMediaTypePair.Key] = combinedMappings;
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// DisplayAppliancePage
/// </summary>
[DataContract]
public partial class DisplayAppliancePage : IEquatable<DisplayAppliancePage>, IValidatableObject
{
public DisplayAppliancePage()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="DisplayAppliancePage" /> class.
/// </summary>
/// <param name="DocumentId">Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute..</param>
/// <param name="DocumentName">.</param>
/// <param name="ExternalDocumentId">.</param>
/// <param name="Height">Height of the tab in pixels..</param>
/// <param name="IsFirstPage">.</param>
/// <param name="PageId">.</param>
/// <param name="PageNo">.</param>
/// <param name="PageStatus">.</param>
/// <param name="PageType">.</param>
/// <param name="Width">Width of the tab in pixels..</param>
public DisplayAppliancePage(string DocumentId = default(string), string DocumentName = default(string), string ExternalDocumentId = default(string), int? Height = default(int?), bool? IsFirstPage = default(bool?), string PageId = default(string), int? PageNo = default(int?), string PageStatus = default(string), string PageType = default(string), int? Width = default(int?))
{
this.DocumentId = DocumentId;
this.DocumentName = DocumentName;
this.ExternalDocumentId = ExternalDocumentId;
this.Height = Height;
this.IsFirstPage = IsFirstPage;
this.PageId = PageId;
this.PageNo = PageNo;
this.PageStatus = PageStatus;
this.PageType = PageType;
this.Width = Width;
}
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="documentName", EmitDefaultValue=false)]
public string DocumentName { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="externalDocumentId", EmitDefaultValue=false)]
public string ExternalDocumentId { get; set; }
/// <summary>
/// Height of the tab in pixels.
/// </summary>
/// <value>Height of the tab in pixels.</value>
[DataMember(Name="height", EmitDefaultValue=false)]
public int? Height { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="isFirstPage", EmitDefaultValue=false)]
public bool? IsFirstPage { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="pageId", EmitDefaultValue=false)]
public string PageId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="pageNo", EmitDefaultValue=false)]
public int? PageNo { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="pageStatus", EmitDefaultValue=false)]
public string PageStatus { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="pageType", EmitDefaultValue=false)]
public string PageType { get; set; }
/// <summary>
/// Width of the tab in pixels.
/// </summary>
/// <value>Width of the tab in pixels.</value>
[DataMember(Name="width", EmitDefaultValue=false)]
public int? Width { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DisplayAppliancePage {\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" DocumentName: ").Append(DocumentName).Append("\n");
sb.Append(" ExternalDocumentId: ").Append(ExternalDocumentId).Append("\n");
sb.Append(" Height: ").Append(Height).Append("\n");
sb.Append(" IsFirstPage: ").Append(IsFirstPage).Append("\n");
sb.Append(" PageId: ").Append(PageId).Append("\n");
sb.Append(" PageNo: ").Append(PageNo).Append("\n");
sb.Append(" PageStatus: ").Append(PageStatus).Append("\n");
sb.Append(" PageType: ").Append(PageType).Append("\n");
sb.Append(" Width: ").Append(Width).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DisplayAppliancePage);
}
/// <summary>
/// Returns true if DisplayAppliancePage instances are equal
/// </summary>
/// <param name="other">Instance of DisplayAppliancePage to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DisplayAppliancePage other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.DocumentName == other.DocumentName ||
this.DocumentName != null &&
this.DocumentName.Equals(other.DocumentName)
) &&
(
this.ExternalDocumentId == other.ExternalDocumentId ||
this.ExternalDocumentId != null &&
this.ExternalDocumentId.Equals(other.ExternalDocumentId)
) &&
(
this.Height == other.Height ||
this.Height != null &&
this.Height.Equals(other.Height)
) &&
(
this.IsFirstPage == other.IsFirstPage ||
this.IsFirstPage != null &&
this.IsFirstPage.Equals(other.IsFirstPage)
) &&
(
this.PageId == other.PageId ||
this.PageId != null &&
this.PageId.Equals(other.PageId)
) &&
(
this.PageNo == other.PageNo ||
this.PageNo != null &&
this.PageNo.Equals(other.PageNo)
) &&
(
this.PageStatus == other.PageStatus ||
this.PageStatus != null &&
this.PageStatus.Equals(other.PageStatus)
) &&
(
this.PageType == other.PageType ||
this.PageType != null &&
this.PageType.Equals(other.PageType)
) &&
(
this.Width == other.Width ||
this.Width != null &&
this.Width.Equals(other.Width)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.DocumentId != null)
hash = hash * 59 + this.DocumentId.GetHashCode();
if (this.DocumentName != null)
hash = hash * 59 + this.DocumentName.GetHashCode();
if (this.ExternalDocumentId != null)
hash = hash * 59 + this.ExternalDocumentId.GetHashCode();
if (this.Height != null)
hash = hash * 59 + this.Height.GetHashCode();
if (this.IsFirstPage != null)
hash = hash * 59 + this.IsFirstPage.GetHashCode();
if (this.PageId != null)
hash = hash * 59 + this.PageId.GetHashCode();
if (this.PageNo != null)
hash = hash * 59 + this.PageNo.GetHashCode();
if (this.PageStatus != null)
hash = hash * 59 + this.PageStatus.GetHashCode();
if (this.PageType != null)
hash = hash * 59 + this.PageType.GetHashCode();
if (this.Width != null)
hash = hash * 59 + this.Width.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ApiProxy.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
#if !PORTABLE && !NETSTANDARD1_6
using System.Collections.Generic;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Api;
using NUnit.Framework.Interfaces;
using NUnit.TestUtilities;
namespace NUnit.Framework.Internal
{
[TestFixture]
public class SetUpFixtureTests
{
private static readonly string testAssembly = AssemblyHelper.GetAssemblyPath(typeof(NUnit.TestData.SetupFixture.Namespace1.SomeFixture).GetTypeInfo().Assembly);
ITestAssemblyBuilder builder;
ITestAssemblyRunner runner;
#region SetUp
[SetUp]
public void SetUp()
{
TestUtilities.SimpleEventRecorder.Clear();
builder = new DefaultTestAssemblyBuilder();
runner = new NUnitTestAssemblyRunner(builder);
}
#endregion SetUp
private ITestResult runTests(string nameSpace)
{
return runTests(nameSpace, TestFilter.Empty);
}
private ITestResult runTests(string nameSpace, TestFilter filter)
{
IDictionary<string, object> options = new Dictionary<string, object>();
if (nameSpace != null)
options["LOAD"] = new string[] { nameSpace };
// No need for the overhead of parallel execution here
options["NumberOfTestWorkers"] = 0;
if (runner.Load(testAssembly, options) != null)
return runner.Run(TestListener.NULL, filter);
return null;
}
#region Builder Tests
/// <summary>
/// Tests that the TestSuiteBuilder correctly interprets a SetupFixture class as a 'virtual namespace' into which
/// all it's sibling classes are inserted.
/// </summary>
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureReplacesNamespaceNodeInTree()
{
string nameSpace = "NUnit.TestData.SetupFixture.Namespace1";
IDictionary<string, object> options = new Dictionary<string, object>();
options["LOAD"] = new string[] { nameSpace };
ITest suite = builder.Build(testAssembly, options);
Assert.IsNotNull(suite);
Assert.AreEqual(testAssembly, suite.FullName);
Assert.AreEqual(1, suite.Tests.Count, "Error in top level test count");
string[] nameSpaceBits = nameSpace.Split('.');
for (int i = 0; i < nameSpaceBits.Length; i++)
{
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual(nameSpaceBits[i], suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
}
Assert.That(suite, Is.InstanceOf<SetUpFixture>());
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual("SomeFixture", suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite.Tests[0].RunState, Is.EqualTo(RunState.Runnable));
}
/// <summary>
/// Tests that the TestSuiteBuilder correctly interprets a SetupFixture class with no parent namespace
/// as a 'virtual assembly' into which all it's sibling fixtures are inserted.
/// </summary>
[NUnit.Framework.Test]
public void AssemblySetUpFixtureReplacesAssemblyNodeInTree()
{
IDictionary<string, object> options = new Dictionary<string, object>();
var setupFixture = builder.Build(testAssembly, options) as SetUpFixture;
Assert.IsNotNull(setupFixture);
var testFixture = TestFinder.Find("SomeFixture", setupFixture, false);
Assert.AreEqual(1, testFixture.Tests.Count);
}
[Test]
public void InvalidAssemblySetUpFixtureIsLoadedCorrectly()
{
string nameSpace = "NUnit.TestData.SetupFixture.Namespace6";
IDictionary<string, object> options = new Dictionary<string, object>();
options["LOAD"] = new string[] { nameSpace };
ITest suite = builder.Build(testAssembly, options);
Assert.IsNotNull(suite);
Assert.AreEqual(testAssembly, suite.FullName);
Assert.AreEqual(1, suite.Tests.Count, "Error in top level test count");
Assert.AreEqual(RunState.Runnable, suite.RunState);
string[] nameSpaceBits = nameSpace.Split('.');
for (int i = 0; i < nameSpaceBits.Length; i++)
{
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual(nameSpaceBits[i], suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(i < nameSpaceBits.Length - 1 ? RunState.Runnable : RunState.NotRunnable));
}
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual("SomeFixture", suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite.Tests[0].RunState, Is.EqualTo(RunState.Runnable));
}
#endregion
#region Simple
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureWrapsExecutionOfSingleTest()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace1").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("NS1.OneTimeSetup",
"NS1.Fixture.SetUp",
"NS1.Test.SetUp",
"NS1.Test",
"NS1.Test.TearDown",
"NS1.Fixture.TearDown",
"NS1.OneTimeTearDown");
}
#endregion Simple
#region Static
[Test]
public void NamespaceSetUpMethodsMayBeStatic()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace5").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("NS5.OneTimeSetUp",
"NS5.Fixture.SetUp",
"NS5.Test.SetUp",
"NS5.Test",
"NS5.Test.TearDown",
"NS5.Fixture.TearDown",
"NS5.OneTimeTearDown");
}
#endregion
#region TwoTestFixtures
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureWrapsExecutionOfTwoTests()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace2").ResultState.Status, Is.EqualTo(TestStatus.Passed));
// There are two fixtures but we can't be sure of the order of execution so they use the same events
TestUtilities.SimpleEventRecorder.Verify("NS2.OneTimeSetUp",
"NS2.Fixture.SetUp",
"NS2.Test.SetUp",
"NS2.Test",
"NS2.Test.TearDown",
"NS2.Fixture.TearDown",
"NS2.Fixture.SetUp",
"NS2.Test.SetUp",
"NS2.Test",
"NS2.Test.TearDown",
"NS2.Fixture.TearDown",
"NS2.OneTimeTearDown");
}
#endregion TwoTestFixtures
#region SubNamespace
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureWrapsNestedNamespaceSetUpFixture()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace3").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("NS3.OneTimeSetUp",
"NS3.Fixture.SetUp",
"NS3.Test.SetUp",
"NS3.Test",
"NS3.Test.TearDown",
"NS3.Fixture.TearDown",
"NS3.SubNamespace.OneTimeSetUp",
"NS3.SubNamespace.Fixture.SetUp",
"NS3.SubNamespace.Test.SetUp",
"NS3.SubNamespace.Test",
"NS3.SubNamespace.Test.TearDown",
"NS3.SubNamespace.Fixture.TearDown",
"NS3.SubNamespace.OneTimeTearDown",
"NS3.OneTimeTearDown");
}
#endregion SubNamespace
#region TwoSetUpFixtures
[NUnit.Framework.Test]
public void WithTwoSetUpFixturesBothAreUsed()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace4").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.ExpectEvents("NS4.OneTimeSetUp1", "NS4.OneTimeSetUp2")
.AndThen("NS4.Fixture.SetUp")
.AndThen("NS4.Test.SetUp")
.AndThen("NS4.Test")
.AndThen("NS4.Test.TearDown")
.AndThen("NS4.Fixture.TearDown")
.AndThen("NS4.OneTimeTearDown1", "NS4.OneTimeTearDown2")
.Verify();
}
#endregion TwoSetUpFixtures
#region InvalidSetUpFixture
[Test]
public void InvalidSetUpFixtureTest()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace6").ResultState.Status, Is.EqualTo(TestStatus.Failed));
TestUtilities.SimpleEventRecorder.Verify(new string[0]);
}
#endregion
#region NoNamespaceSetupFixture
[NUnit.Framework.Test]
public void AssemblySetupFixtureWrapsExecutionOfTest()
{
ITestResult result = runTests(null, new Filters.FullNameFilter("SomeFixture"));
Assert.AreEqual(1, result.PassCount);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("Assembly.OneTimeSetUp",
"NoNamespaceTest",
"Assembly.OneTimeTearDown");
}
#endregion NoNamespaceSetupFixture
}
}
#endif
| |
using System;
using System.Linq;
using System.Data;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
using bv.common;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.model.Model.Validators;
using eidss.model.Core;
using eidss.model.Resources;
using eidss.model.Schema;
namespace Eidss.Web
{
public class HumanCaseInfo
{
//[XmlIgnore]
//[FieldName("idfHuman")]
//public long idfHuman { get; set; }
//[XmlIgnore]
//[FieldName("idfEpiObservation")]
//public long idfEpiObservation { get; set; }
//[XmlIgnore]
//[FieldName("idfCSObservation")]
//public long idfCSObservation { get; set; }
//[XmlIgnore]
//[FieldName("idfPointGeoLocation")]
//public long idfPointGeoLocation { get; set; }
[FieldName("uidOfflineCaseID")]
public string OfflineCaseID { get; set; }
[FieldName("idfCase")]
public long Id { get; set; }
[FieldName("strCaseID")]
public string CaseID { get; set; }
[FieldName("strLocalIdentifier")]
public string LocalID { get; set; }
//[FieldName("strLocalIdentifier")]
//public string LocalIdentifier { get; set; }
[FieldName("datCompletionPaperFormDate")]
public DateTime? CompletionPaperFormDate { get; set; }
//[XmlIgnore]
//[FieldName("datEnteredDate")]
//public DateTime EnteredDate { get; set; }
//[XmlIgnore]
//[FieldName("datModificationDate")]
//public DateTime? ModificationDate { get; set; }
[FieldName("datFacilityLastVisit")]
public DateTime? FacilityLastVisitDate { get; set; }
[FieldName("datOnSetDate")]
public DateTime? OnsetDate { get; set; }
[FieldName("datNotificationDate")]
public DateTime? NotificationDate { get; set; }
[FieldName("idfsTentativeDiagnosis")]
public BaseReferenceItem TentativeDiagnosis { get; set; }
[FieldName("datTentativeDiagnosisDate")]
public DateTime? TentativeDiagnosisDate { get; set; }
[FieldName("idfsFinalDiagnosis")]
public BaseReferenceItem FinalDiagnosis { get; set; }
[FieldName("datFinalDiagnosisDate")]
public DateTime? FinalDiagnosisDate { get; set; }
[FieldName("intPatientAge")]
public int? PatientAge { get; set; }
[FieldName("strFirstName")]
public string FirstName { get; set; }
[FieldName("strSecondName")]
public string MiddleName { get; set; }
[FieldName("strLastName")]
public string LastName { get; set; }
[FieldName("idfsHumanAgeType")]
public BaseReferenceItem PatientAgeType { get; set; }
[FieldName("idfsHumanGender")]
public BaseReferenceItem PatientGender { get; set; }
[FieldName("idfsCaseProgressStatus")]
public BaseReferenceItem CaseStatus { get; set; }
[FieldName("idfsYNRelatedToOutbreak")]
public BaseReferenceItem RelatedToOutbreak { get; set; }
[FieldName("idfsHospitalizationStatus")]
public BaseReferenceItem CurrentLocation { get; set; }
[FieldName("idfsYNHospitalization")]
public BaseReferenceItem Hospitalization { get; set; }
[FieldName("idfsInitialCaseStatus")]
public BaseReferenceItem CaseClassification { get; set; }
[FieldName("idfsFinalCaseStatus")]
public BaseReferenceItem FinalCaseStatus { get; set; }
[FieldName("idfsFinalState")]
public BaseReferenceItem PatientState { get; set; }
[FieldName("datDateOfBirth")]
public DateTime? DateOfBirth { get; set; }
[FieldName("idfsNationality")]
public BaseReferenceItem Citizenship { get; set; }
[FieldName("strNote")]
public string AdditionalComment { get; set; }
[FieldName("idfsOutcome")]
public BaseReferenceItem Outcome { get; set; }
[FieldName("CurrentResidence")]
public AddressInfo CurrentResidence { get; set; }
[FieldName("EmployerAddress")]
public AddressInfo EmployerAddress { get; set; }
[FieldName("strEmployerName")]
public string EmployerName { get; set; }
[FieldName("strCurrentLocation")]
public string CurrentLocationName { get; set; }
[FieldName("idfSentByOffice")]
public BaseReferenceItem NotificationSentBy { get; set; }
[FieldName("idfSentByPerson")]
public BaseReferenceItem NotificationSentByPerson { get; set; }
[FieldName("strSentByFirstName")]
public string NotificationSentByFirstName { get; set; }
[FieldName("strSentByPatronymicName")]
public string NotificationSentByPatronymicName { get; set; }
[FieldName("strSentByLastName")]
public string NotificationSentByLastName { get; set; }
[FieldName("idfReceivedByOffice")]
public BaseReferenceItem NotificationReceivedBy { get; set; }
[FieldName("strReceivedByFirstName")]
public string NotificationReceivedByFirstName { get; set; }
[FieldName("strReceivedByPatronymicName")]
public string NotificationReceivedByPatronymicName { get; set; }
[FieldName("strReceivedByLastName")]
public string NotificationReceivedByLastName { get; set; }
[FieldName("strHomePhone")]
public string PhoneNumber { get; set; }
public string LastErrorDescription { get; set; }
public bool MarkedToDelete { get; set; }
public static HumanCaseInfo GetById(string id)
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
var hc = HumanCase.Accessor.Instance(null).SelectByKey(manager, long.Parse(id));
if (hc == null)
throw new SoapException(string.Format("Case with id='{0}' is not found", id), new XmlQualifiedName("id"));
return new HumanCaseInfo()
{
Id = hc.idfCase,
CaseID = hc.strCaseID,
LocalID = hc.strLocalIdentifier,
//LocalIdentifier = hc.strLocalIdentifier,
CompletionPaperFormDate = hc.datCompletionPaperFormDate,
FacilityLastVisitDate = hc.datFacilityLastVisit,
OnsetDate = hc.datOnSetDate,
NotificationDate = hc.datNotificationDate,
TentativeDiagnosis = new BaseReferenceItem() { Id = hc.idfsTentativeDiagnosis, Name = hc.TentativeDiagnosis != null ? hc.TentativeDiagnosis.name : "" },
TentativeDiagnosisDate = hc.datTentativeDiagnosisDate,
FinalDiagnosis = new BaseReferenceItem() { Id = hc.idfsFinalDiagnosis, Name = hc.FinalDiagnosis != null ? hc.FinalDiagnosis.name : "" },
FinalDiagnosisDate = hc.datFinalDiagnosisDate,
PatientAge = hc.intPatientAge,
FirstName = hc.Patient.strFirstName,
MiddleName = hc.Patient.strSecondName,
LastName = hc.Patient.strLastName,
PatientAgeType = new BaseReferenceItem() { Id = hc.idfsHumanAgeType, Name = hc.Patient.HumanAgeType != null ? hc.Patient.HumanAgeType.name : "" },
PatientGender = new BaseReferenceItem() { Id = hc.Patient.idfsHumanGender, Name = hc.Patient.Gender != null ? hc.Patient.Gender.name : "" },
CaseStatus = new BaseReferenceItem() { Id = hc.idfsCaseProgressStatus, Name = hc.CaseProgressStatus != null ? hc.CaseProgressStatus.name : "" },
RelatedToOutbreak = new BaseReferenceItem() { Id = hc.idfsYNRelatedToOutbreak, Name = hc.RelatedToOutbreak != null ? hc.RelatedToOutbreak.name : "" },
CurrentLocation = new BaseReferenceItem() { Id = hc.idfsHospitalizationStatus, Name = hc.PatientLocationType != null ? hc.PatientLocationType.name : "" },
Hospitalization = new BaseReferenceItem() { Id = hc.idfsYNHospitalization, Name = hc.Hospitalization != null ? hc.Hospitalization.name : "" },
CaseClassification = new BaseReferenceItem() { Id = hc.idfsInitialCaseStatus, Name = hc.InitialCaseClassification != null ? hc.InitialCaseClassification.name : "" },
FinalCaseStatus = new BaseReferenceItem() { Id = hc.idfsFinalCaseStatus, Name = hc.FinalCaseClassification != null ? hc.FinalCaseClassification.name : "" },
PatientState = new BaseReferenceItem() { Id = hc.idfsFinalState, Name = hc.PatientState != null ? hc.PatientState.name : "" },
DateOfBirth = hc.Patient.datDateofBirth,
Citizenship = new BaseReferenceItem() { Id = hc.Patient.idfsNationality, Name = hc.Patient.Nationality != null ? hc.Patient.Nationality.name : "" },
AdditionalComment = hc.strNote,
Outcome = new BaseReferenceItem() { Id = hc.idfsOutcome, Name = hc.Outcome != null ? hc.Outcome.name : "" },
CurrentResidence = new AddressInfo()
{
idfGeoLocation = hc.Patient.CurrentResidenceAddress.idfGeoLocation,
Country = new BaseReferenceItem() { Id = hc.Patient.CurrentResidenceAddress.idfsCountry, Name = hc.Patient.CurrentResidenceAddress.Country != null ? hc.Patient.CurrentResidenceAddress.Country.strCountryName : "" },
Region = new BaseReferenceItem() { Id = hc.Patient.CurrentResidenceAddress.idfsRegion, Name = hc.Patient.CurrentResidenceAddress.Region != null ? hc.Patient.CurrentResidenceAddress.Region.strRegionName : "" },
Rayon = new BaseReferenceItem() { Id = hc.Patient.CurrentResidenceAddress.idfsRayon, Name = hc.Patient.CurrentResidenceAddress.Rayon != null ? hc.Patient.CurrentResidenceAddress.Rayon.strRayonName : "" },
Settlement = new BaseReferenceItem() { Id = hc.Patient.CurrentResidenceAddress.idfsSettlement, Name = hc.Patient.CurrentResidenceAddress.Settlement != null ? hc.Patient.CurrentResidenceAddress.Settlement.strSettlementName : "" },
Street = hc.Patient.CurrentResidenceAddress.strStreetName,
ZipCode = hc.Patient.CurrentResidenceAddress.strPostCode
},
EmployerAddress = new AddressInfo()
{
idfGeoLocation = hc.Patient.EmployerAddress.idfGeoLocation,
Country = new BaseReferenceItem() { Id = hc.Patient.EmployerAddress.idfsCountry, Name = hc.Patient.EmployerAddress.Country != null ? hc.Patient.EmployerAddress.Country.strCountryName : "" },
Region = new BaseReferenceItem() { Id = hc.Patient.EmployerAddress.idfsRegion, Name = hc.Patient.EmployerAddress.Region != null ? hc.Patient.EmployerAddress.Region.strRegionName : "" },
Rayon = new BaseReferenceItem() { Id = hc.Patient.EmployerAddress.idfsRayon, Name = hc.Patient.EmployerAddress.Rayon != null ? hc.Patient.EmployerAddress.Rayon.strRayonName : "" },
Settlement = new BaseReferenceItem() { Id = hc.Patient.EmployerAddress.idfsSettlement, Name = hc.Patient.EmployerAddress.Settlement != null ? hc.Patient.EmployerAddress.Settlement.strSettlementName : "" },
Street = hc.Patient.EmployerAddress.strStreetName,
ZipCode = hc.Patient.EmployerAddress.strPostCode
},
EmployerName = hc.Patient.strEmployerName,
CurrentLocationName = hc.strCurrentLocation,
NotificationSentBy = new BaseReferenceItem() { Id = hc.idfSentByOffice, Name = hc.strSentByOffice },
NotificationSentByPerson = new BaseReferenceItem() { Id = hc.idfSentByPerson, Name = hc.strSentByPerson },
NotificationSentByFirstName = hc.strSentByFirstName,
NotificationSentByPatronymicName = hc.strSentByPatronymicName,
NotificationSentByLastName = hc.strSentByLastName,
NotificationReceivedBy = new BaseReferenceItem() { Id = hc.idfReceivedByOffice, Name = hc.strReceivedByOffice },
NotificationReceivedByFirstName = hc.strReceivedByFirstName,
NotificationReceivedByPatronymicName = hc.strReceivedByPatronymicName,
NotificationReceivedByLastName = hc.strReceivedByLastName,
PhoneNumber = hc.Patient.strHomePhone
};
}
}
private long find_by_offline_id(DbManagerProxy manager)
{
long ret = HumanCaseListItem.Accessor.Instance(null)
.SelectListT(manager, new FilterParams().Add("uidOfflineCaseID", "=", OfflineCaseID))
.Select(c => c.idfCase).FirstOrDefault();
return ret;
}
public bool Save(bool bSaveNotification)
{
bool ret = false;
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
var acc = HumanCase.Accessor.Instance(null);
HumanCase hc = null;
if (string.IsNullOrEmpty(OfflineCaseID))
{
hc = (Id != 0) ? acc.SelectByKey(manager, Id) : acc.CreateNewT(manager, null);
}
else
{
var find = find_by_offline_id(manager);
if (find != 0)
hc = acc.SelectByKey(manager, find);
else
{
hc = acc.CreateNewT(manager, null);
if (Id != 0)
{
MarkedToDelete = true;
return true;
}
}
}
if (hc == null)
throw new SoapException(string.Format("Case with id='{0}' is not found", Id != 0 ? Id.ToString() : OfflineCaseID), new XmlQualifiedName("id"));
hc.strCaseID = CaseID ?? "";
try { hc.uidOfflineCaseID = new Guid(OfflineCaseID); } catch {}
hc.strLocalIdentifier = LocalID;
//hc.strLocalIdentifier = LocalIdentifier;
hc.datCompletionPaperFormDate = CompletionPaperFormDate;
hc.datFacilityLastVisit = FacilityLastVisitDate;
hc.datOnSetDate = OnsetDate;
if (bSaveNotification)
hc.datNotificationDate = NotificationDate;
hc.TentativeDiagnosis = TentativeDiagnosis == null ? null
: hc.TentativeDiagnosisLookup.SingleOrDefault(c => c.idfsDiagnosis == TentativeDiagnosis.Id);
hc.datTentativeDiagnosisDate = TentativeDiagnosisDate;
hc.FinalDiagnosis = FinalDiagnosis == null ? null :
hc.FinalDiagnosisLookup.SingleOrDefault(c => c.idfsDiagnosis == FinalDiagnosis.Id);
hc.datFinalDiagnosisDate = FinalDiagnosisDate;
hc.intPatientAge = PatientAge.HasValue && PatientAge.Value > 0 ? PatientAge : null;
hc.Patient.intPatientAgeFromCase = hc.intPatientAge;
hc.Patient.strFirstName = FirstName;
hc.Patient.strSecondName = MiddleName;
hc.Patient.strLastName = LastName;
hc.Patient.HumanAgeType = PatientAgeType == null ? null :
hc.Patient.HumanAgeTypeLookup.SingleOrDefault(c => c.idfsBaseReference == PatientAgeType.Id);
hc.Patient.Gender = PatientGender == null ? null :
hc.Patient.GenderLookup.SingleOrDefault(c => c.idfsBaseReference == PatientGender.Id);
hc.CaseProgressStatus = CaseStatus == null ? null :
hc.CaseProgressStatusLookup.SingleOrDefault(c => c.idfsBaseReference == CaseStatus.Id);
hc.RelatedToOutbreak = RelatedToOutbreak == null ? null :
hc.RelatedToOutbreakLookup.SingleOrDefault(c => c.idfsBaseReference == RelatedToOutbreak.Id);
hc.PatientLocationType = CurrentLocation == null ? null :
hc.PatientLocationTypeLookup.SingleOrDefault(c => c.idfsBaseReference == CurrentLocation.Id);
hc.Hospitalization = Hospitalization == null ? null :
hc.HospitalizationLookup.SingleOrDefault(c => c.idfsBaseReference == Hospitalization.Id);
hc.InitialCaseClassification = CaseClassification == null ? null :
hc.InitialCaseClassificationLookup.SingleOrDefault(c => c.idfsReference == CaseClassification.Id);
hc.FinalCaseClassification = FinalCaseStatus == null ? null :
hc.FinalCaseClassificationLookup.SingleOrDefault(c => c.idfsReference == FinalCaseStatus.Id);
hc.PatientState = PatientState == null ? null :
hc.PatientStateLookup.SingleOrDefault(c => c.idfsBaseReference == PatientState.Id);
hc.Patient.datDateofBirth = DateOfBirth;
hc.Patient.Nationality = Citizenship == null ? null :
hc.Patient.NationalityLookup.SingleOrDefault(c => c.idfsBaseReference == Citizenship.Id);
hc.strNote = AdditionalComment;
hc.Outcome = Outcome == null ? null :
hc.OutcomeLookup.SingleOrDefault(c => c.idfsBaseReference == Outcome.Id);
hc.Patient.CurrentResidenceAddress.Country = CurrentResidence == null || CurrentResidence.Country == null ? null :
hc.Patient.CurrentResidenceAddress.CountryLookup.SingleOrDefault(c => c.idfsCountry == CurrentResidence.Country.Id);
hc.Patient.CurrentResidenceAddress.Region = CurrentResidence == null || CurrentResidence.Region == null ? null :
hc.Patient.CurrentResidenceAddress.RegionLookup.SingleOrDefault(c => c.idfsRegion == CurrentResidence.Region.Id);
hc.Patient.CurrentResidenceAddress.Rayon = CurrentResidence == null || CurrentResidence.Rayon == null ? null :
hc.Patient.CurrentResidenceAddress.RayonLookup.SingleOrDefault(c => c.idfsRayon == CurrentResidence.Rayon.Id);
hc.Patient.CurrentResidenceAddress.Settlement = CurrentResidence == null || CurrentResidence.Settlement == null ? null :
hc.Patient.CurrentResidenceAddress.SettlementLookup.SingleOrDefault(c => c.idfsSettlement == CurrentResidence.Settlement.Id);
hc.Patient.CurrentResidenceAddress.strStreetName = CurrentResidence == null ? null : CurrentResidence.Street;
hc.Patient.CurrentResidenceAddress.strPostCode = CurrentResidence == null ? null : CurrentResidence.ZipCode;
hc.Patient.EmployerAddress.Country = EmployerAddress == null || EmployerAddress.Country == null ? null :
hc.Patient.EmployerAddress.CountryLookup.SingleOrDefault(c => c.idfsCountry == EmployerAddress.Country.Id);
hc.Patient.EmployerAddress.Region = EmployerAddress == null || EmployerAddress.Region == null ? null :
hc.Patient.EmployerAddress.RegionLookup.SingleOrDefault(c => c.idfsRegion == EmployerAddress.Region.Id);
hc.Patient.EmployerAddress.Rayon = EmployerAddress == null || EmployerAddress.Rayon == null ? null :
hc.Patient.EmployerAddress.RayonLookup.SingleOrDefault(c => c.idfsRayon == EmployerAddress.Rayon.Id);
hc.Patient.EmployerAddress.Settlement = EmployerAddress == null || EmployerAddress.Settlement == null ? null :
hc.Patient.EmployerAddress.SettlementLookup.SingleOrDefault(c => c.idfsSettlement == EmployerAddress.Settlement.Id);
hc.Patient.EmployerAddress.strStreetName = EmployerAddress == null ? null : EmployerAddress.Street;
hc.Patient.EmployerAddress.strPostCode = EmployerAddress == null ? null : EmployerAddress.ZipCode;
hc.Patient.strEmployerName = EmployerName;
hc.strCurrentLocation = CurrentLocationName;
if (bSaveNotification)
{
hc.idfSentByOffice = NotificationSentBy.Id;
//hc.SentByOffice = NotificationSentBy == null ? null :
// hc.SentByOfficeLookup.SingleOrDefault(c => c.idfInstitution == NotificationSentBy.Id);
hc.idfSentByPerson = NotificationSentByPerson.Id;
//hc.SentByPerson = NotificationSentByPerson == null ? null :
// hc.SentByPersonLookup.SingleOrDefault(c => c.idfPerson == NotificationSentByPerson.Id);
hc.strSentByFirstName = NotificationSentByFirstName;
hc.strSentByPatronymicName = NotificationSentByPatronymicName;
hc.strSentByLastName = NotificationSentByLastName;
hc.idfReceivedByOffice = NotificationReceivedBy.Id;
//hc.ReceivedByOffice = NotificationReceivedBy == null ? null :
// hc.ReceivedByOfficeLookup.SingleOrDefault(c => c.idfInstitution == NotificationReceivedBy.Id);
hc.strReceivedByFirstName = NotificationReceivedByFirstName;
hc.strReceivedByPatronymicName = NotificationReceivedByPatronymicName;
hc.strReceivedByLastName = NotificationReceivedByLastName;
}
hc.Patient.strHomePhone = PhoneNumber;
hc.Validation += (sender, args) =>
{
LastErrorDescription = GetErrorMessage(args);
throw new SoapException(EidssMessages.GetValidationErrorMessage(args, "en"), new XmlQualifiedName(args.FieldName));
};
ret = acc.Post(manager, hc);
if (!ret)
{
LastErrorDescription = "Unknown error is occured during posting case";
throw new SoapException("Unknown error is occured during posting case", new XmlQualifiedName("post"));
}
Id = hc.idfCase;
CaseID = hc.strCaseID;
}
return ret;
}
private static string GetString(string key)
{
var value = EidssFields.Instance.GetString(key);
if (string.IsNullOrWhiteSpace(value))
{
return key;
}
return value;
}
private static string GetErrorMessage(ValidationEventArgs args)
{
if (args.Type == typeof(RequiredValidator))
{
return string.Format(EidssMessages.Get(args.MessageId), GetString(args.Pars[0].ToString()));
}
return EidssMessages.Get(args.MessageId);
}
/*
protected override string SavingProcedureName
{
get
{
return "spHumanCase_Post";
}
}
protected override void OnSaving(IDbConnection connection, IDbTransaction transaction)
{
//ValidationResult res = Validate();
//if (res.IsValid == false)
//throw new ModelValidationException(res);
if ( Id==null )
{
Id = BaseDbService.NewIntID(transaction);
bv.common.ErrorMessage err = new bv.common.ErrorMessage();
CaseID = NumberingService.GetNextNumber(NumberingObject.HumanCase, null, connection, ref err, transaction);
EnteredDate = DateTime.Now;
}
idfGeoLocation=BaseDbService.NewIntID(transaction);
idfCSObservation = BaseDbService.NewIntID(transaction);
idfEpiObservation = BaseDbService.NewIntID(transaction);
ModificationDate = DateTime.Now;
Address residence = new Address();
if (CurrentResidence != null)
{
if (CurrentResidence.Country.Id != null) residence.CountryId = CurrentResidence.Country.Id.Value;
if (CurrentResidence.Region.Id != null) residence.RegionId = CurrentResidence.Region.Id.Value;
if (CurrentResidence.Rayon.Id != null) residence.RayonId = CurrentResidence.Rayon.Id.Value;
residence.Save(connection, transaction);
}
Patient p = new Patient();
p.CaseId = Id.Value;
p.CurrentResidenceId = residence.Id.Value;
if(PatientGender!=null)p.HumanGenderId = PatientGender.Id;
p.FirstName = FirstName;
p.LastName = LastName;
p.Save(connection, transaction);
idfHuman = p.Id.Value;
//Patient.CurrentResidence.Save(connection, transaction);
//Patient.CurrentResidenceId = Patient.CurrentResidence.Id;
//Patient.Save(connection, transaction);
//PatientId = Patient.Id;
}
*/
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public abstract class DockPaneStripBase : Control
{
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected internal class Tab : IDisposable
{
private IDockContent m_content;
public Tab(IDockContent content)
{
m_content = content;
}
~Tab()
{
Dispose(false);
}
public IDockContent Content
{
get { return m_content; }
}
public Form ContentForm
{
get { return m_content as Form; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected sealed class TabCollection : IEnumerable<Tab>
{
#region IEnumerable Members
IEnumerator<Tab> IEnumerable<Tab>.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
#endregion
internal TabCollection(DockPane pane)
{
m_dockPane = pane;
}
private DockPane m_dockPane;
public DockPane DockPane
{
get { return m_dockPane; }
}
public int Count
{
get { return DockPane.DisplayingContents.Count; }
}
public Tab this[int index]
{
get
{
IDockContent content = DockPane.DisplayingContents[index];
if (content == null)
throw (new ArgumentOutOfRangeException("index"));
return content.DockHandler.GetTab(DockPane.TabStripControl);
}
}
public bool Contains(Tab tab)
{
return (IndexOf(tab) != -1);
}
public bool Contains(IDockContent content)
{
return (IndexOf(content) != -1);
}
public int IndexOf(Tab tab)
{
if (tab == null)
return -1;
return DockPane.DisplayingContents.IndexOf(tab.Content);
}
public int IndexOf(IDockContent content)
{
return DockPane.DisplayingContents.IndexOf(content);
}
}
protected DockPaneStripBase(DockPane pane)
{
m_dockPane = pane;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.Selectable, false);
AllowDrop = true;
}
private DockPane m_dockPane;
protected DockPane DockPane
{
get { return m_dockPane; }
}
protected DockPane.AppearanceStyle Appearance
{
get { return DockPane.Appearance; }
}
private TabCollection m_tabs = null;
protected TabCollection Tabs
{
get
{
if (m_tabs == null)
m_tabs = new TabCollection(DockPane);
return m_tabs;
}
}
internal void RefreshChanges()
{
if (IsDisposed)
return;
OnRefreshChanges();
}
protected virtual void OnRefreshChanges()
{
}
protected internal abstract int MeasureHeight();
protected internal abstract void EnsureTabVisible(IDockContent content);
protected int HitTest()
{
return HitTest(PointToClient(Control.MousePosition));
}
protected internal abstract int HitTest(Point point);
public abstract GraphicsPath GetOutline(int index);
protected internal virtual Tab CreateTab(IDockContent content)
{
return new Tab(content);
}
private Rectangle _dragBox = Rectangle.Empty;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
int index = HitTest();
if (index != -1)
{
if (e.Button == MouseButtons.Middle)
{
// Close the specified content.
IDockContent content = Tabs[index].Content;
DockPane.CloseContent(content);
}
else
{
IDockContent content = Tabs[index].Content;
if (DockPane.ActiveContent != content)
DockPane.ActiveContent = content;
}
}
if (e.Button == MouseButtons.Left)
{
var dragSize = SystemInformation.DragSize;
_dragBox = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)), dragSize);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button != MouseButtons.Left || _dragBox.Contains(e.Location))
return;
if (DockPane.ActiveContent == null)
return;
if (DockPane.DockPanel.AllowEndUserDocking && DockPane.AllowDockDragAndDrop && DockPane.ActiveContent.DockHandler.AllowEndUserDocking)
DockPane.DockPanel.BeginDrag(DockPane.ActiveContent.DockHandler);
}
protected bool HasTabPageContextMenu
{
get { return DockPane.HasTabPageContextMenu; }
}
protected void ShowTabPageContextMenu(Point position)
{
DockPane.ShowTabPageContextMenu(this, position);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Right)
ShowTabPageContextMenu(new Point(e.X, e.Y));
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_LBUTTONDBLCLK)
{
base.WndProc(ref m);
int index = HitTest();
if (DockPane.DockPanel.AllowEndUserDocking && index != -1)
{
IDockContent content = Tabs[index].Content;
if (content.DockHandler.CheckDockState(!content.DockHandler.IsFloat) != DockState.Unknown)
content.DockHandler.IsFloat = !content.DockHandler.IsFloat;
}
return;
}
base.WndProc(ref m);
return;
}
protected override void OnDragOver(DragEventArgs drgevent)
{
base.OnDragOver(drgevent);
int index = HitTest();
if (index != -1)
{
IDockContent content = Tabs[index].Content;
if (DockPane.ActiveContent != content)
DockPane.ActiveContent = content;
}
}
protected abstract Rectangle GetTabBounds(Tab tab);
internal static Rectangle ToScreen(Rectangle rectangle, Control parent)
{
if (parent == null)
return rectangle;
return new Rectangle(parent.PointToScreen(new Point(rectangle.Left, rectangle.Top)), new Size(rectangle.Width, rectangle.Height));
}
protected override AccessibleObject CreateAccessibilityInstance()
{
return new DockPaneStripAccessibleObject(this);
}
public class DockPaneStripAccessibleObject : Control.ControlAccessibleObject
{
private DockPaneStripBase _strip;
private DockState _state;
public DockPaneStripAccessibleObject(DockPaneStripBase strip)
: base(strip)
{
_strip = strip;
}
public override AccessibleRole Role
{
get
{
return AccessibleRole.PageTabList;
}
}
public override int GetChildCount()
{
return _strip.Tabs.Count;
}
public override AccessibleObject GetChild(int index)
{
return new DockPaneStripTabAccessibleObject(_strip, _strip.Tabs[index], this);
}
public override AccessibleObject HitTest(int x, int y)
{
Point point = new Point(x, y);
foreach (Tab tab in _strip.Tabs)
{
Rectangle rectangle = _strip.GetTabBounds(tab);
if (ToScreen(rectangle, _strip).Contains(point))
return new DockPaneStripTabAccessibleObject(_strip, tab, this);
}
return null;
}
}
protected class DockPaneStripTabAccessibleObject : AccessibleObject
{
private DockPaneStripBase _strip;
private Tab _tab;
private AccessibleObject _parent;
internal DockPaneStripTabAccessibleObject(DockPaneStripBase strip, Tab tab, AccessibleObject parent)
{
_strip = strip;
_tab = tab;
_parent = parent;
}
public override AccessibleObject Parent
{
get
{
return _parent;
}
}
public override AccessibleRole Role
{
get
{
return AccessibleRole.PageTab;
}
}
public override Rectangle Bounds
{
get
{
Rectangle rectangle = _strip.GetTabBounds(_tab);
return ToScreen(rectangle, _strip);
}
}
public override string Name
{
get
{
return _tab.Content.DockHandler.TabText;
}
set
{
//base.Name = value;
}
}
}
}
}
| |
--- /dev/null 2016-03-07 14:47:24.000000000 -0500
+++ src/System.ObjectModel/src/SR.cs 2016-03-07 14:47:39.218804000 -0500
@@ -0,0 +1,222 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.ObjectModel
+{
+ internal static class SR
+ {
+
+ }
+}
+
+namespace System
+{
+ internal static class SR
+ {
+ private static ResourceManager s_resourceManager;
+
+ private const String s_resourcesName = "FxResources.System.ObjectModel.SR";
+
+ internal static String Arg_ArrayPlusOffTooSmall
+ {
+ get
+ {
+ return SR.GetResourceString("Arg_ArrayPlusOffTooSmall", null);
+ }
+ }
+
+ internal static String Arg_NonZeroLowerBound
+ {
+ get
+ {
+ return SR.GetResourceString("Arg_NonZeroLowerBound", null);
+ }
+ }
+
+ internal static String Arg_RankMultiDimNotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("Arg_RankMultiDimNotSupported", null);
+ }
+ }
+
+ internal static String Argument_AddingDuplicate
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_AddingDuplicate", null);
+ }
+ }
+
+ internal static String Argument_InvalidArrayType
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidArrayType", null);
+ }
+ }
+
+ internal static String Argument_ItemNotExist
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_ItemNotExist", null);
+ }
+ }
+
+ internal static String ArgumentOutOfRange_InvalidThreshold
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_InvalidThreshold", null);
+ }
+ }
+
+ internal static String ArgumentOutOfRange_NeedNonNegNum
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null);
+ }
+ }
+
+ internal static String IndexCannotBeNegative
+ {
+ get
+ {
+ return SR.GetResourceString("IndexCannotBeNegative", null);
+ }
+ }
+
+ internal static String MustBeResetAddOrRemoveActionForCtor
+ {
+ get
+ {
+ return SR.GetResourceString("MustBeResetAddOrRemoveActionForCtor", null);
+ }
+ }
+
+ internal static String NotSupported_ReadOnlyCollection
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_ReadOnlyCollection", null);
+ }
+ }
+
+ internal static String ObservableCollectionReentrancyNotAllowed
+ {
+ get
+ {
+ return SR.GetResourceString("ObservableCollectionReentrancyNotAllowed", null);
+ }
+ }
+
+ internal static String ResetActionRequiresIndexMinus1
+ {
+ get
+ {
+ return SR.GetResourceString("ResetActionRequiresIndexMinus1", null);
+ }
+ }
+
+ internal static String ResetActionRequiresNullItem
+ {
+ get
+ {
+ return SR.GetResourceString("ResetActionRequiresNullItem", null);
+ }
+ }
+
+ private static ResourceManager ResourceManager
+ {
+ get
+ {
+ if (SR.s_resourceManager == null)
+ {
+ SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+ }
+ return SR.s_resourceManager;
+ }
+ }
+
+ internal static Type ResourceType
+ {
+ get
+ {
+ return typeof(FxResources.System.ObjectModel.SR);
+ }
+ }
+
+ internal static String WrongActionForCtor
+ {
+ get
+ {
+ return SR.GetResourceString("WrongActionForCtor", null);
+ }
+ }
+
+ internal static String Format(String resourceFormat, params Object[] args)
+ {
+ if (args == null)
+ {
+ return resourceFormat;
+ }
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, args);
+ }
+ return String.Concat(resourceFormat, String.Join(", ", args));
+ }
+
+ internal static String Format(String resourceFormat, Object p1)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2, Object p3)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2, p3);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 });
+ }
+
+ internal static String GetResourceString(String resourceKey, String defaultString)
+ {
+ String str = null;
+ try
+ {
+ str = SR.ResourceManager.GetString(resourceKey);
+ }
+ catch (MissingManifestResourceException missingManifestResourceException)
+ {
+ }
+ if (defaultString != null && resourceKey.Equals(str))
+ {
+ return defaultString;
+ }
+ return str;
+ }
+
+ private static Boolean UsingResourceKeys()
+ {
+ return false;
+ }
+ }
+}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ErrorReporting.V1Beta1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedErrorStatsServiceClientSnippets
{
/// <summary>Snippet for ListGroupStats</summary>
public void ListGroupStatsRequestObject()
{
// Snippet: ListGroupStats(ListGroupStatsRequest, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ListGroupStatsRequest request = new ListGroupStatsRequest
{
ProjectNameAsProjectName = ProjectName.FromProject("[PROJECT]"),
GroupId = { "", },
ServiceFilter = new ServiceContextFilter(),
TimeRange = new QueryTimeRange(),
TimedCountDuration = new Duration(),
Alignment = TimedCountAlignment.ErrorCountAlignmentUnspecified,
AlignmentTime = new Timestamp(),
Order = ErrorGroupOrder.GroupOrderUnspecified,
};
// Make the request
PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> response = errorStatsServiceClient.ListGroupStats(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorGroupStats item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGroupStatsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStatsAsync</summary>
public async Task ListGroupStatsRequestObjectAsync()
{
// Snippet: ListGroupStatsAsync(ListGroupStatsRequest, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ListGroupStatsRequest request = new ListGroupStatsRequest
{
ProjectNameAsProjectName = ProjectName.FromProject("[PROJECT]"),
GroupId = { "", },
ServiceFilter = new ServiceContextFilter(),
TimeRange = new QueryTimeRange(),
TimedCountDuration = new Duration(),
Alignment = TimedCountAlignment.ErrorCountAlignmentUnspecified,
AlignmentTime = new Timestamp(),
Order = ErrorGroupOrder.GroupOrderUnspecified,
};
// Make the request
PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> response = errorStatsServiceClient.ListGroupStatsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorGroupStats item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGroupStatsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStats</summary>
public void ListGroupStats()
{
// Snippet: ListGroupStats(string, QueryTimeRange, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
string projectName = "projects/[PROJECT]";
QueryTimeRange timeRange = new QueryTimeRange();
// Make the request
PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> response = errorStatsServiceClient.ListGroupStats(projectName, timeRange);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorGroupStats item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGroupStatsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStatsAsync</summary>
public async Task ListGroupStatsAsync()
{
// Snippet: ListGroupStatsAsync(string, QueryTimeRange, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
string projectName = "projects/[PROJECT]";
QueryTimeRange timeRange = new QueryTimeRange();
// Make the request
PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> response = errorStatsServiceClient.ListGroupStatsAsync(projectName, timeRange);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorGroupStats item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGroupStatsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStats</summary>
public void ListGroupStatsResourceNames()
{
// Snippet: ListGroupStats(ProjectName, QueryTimeRange, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ProjectName projectName = ProjectName.FromProject("[PROJECT]");
QueryTimeRange timeRange = new QueryTimeRange();
// Make the request
PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> response = errorStatsServiceClient.ListGroupStats(projectName, timeRange);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorGroupStats item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGroupStatsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStatsAsync</summary>
public async Task ListGroupStatsResourceNamesAsync()
{
// Snippet: ListGroupStatsAsync(ProjectName, QueryTimeRange, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName projectName = ProjectName.FromProject("[PROJECT]");
QueryTimeRange timeRange = new QueryTimeRange();
// Make the request
PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> response = errorStatsServiceClient.ListGroupStatsAsync(projectName, timeRange);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorGroupStats item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGroupStatsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEvents</summary>
public void ListEventsRequestObject()
{
// Snippet: ListEvents(ListEventsRequest, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ListEventsRequest request = new ListEventsRequest
{
ProjectNameAsProjectName = ProjectName.FromProject("[PROJECT]"),
GroupId = "",
ServiceFilter = new ServiceContextFilter(),
TimeRange = new QueryTimeRange(),
};
// Make the request
PagedEnumerable<ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEvents(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEventsAsync</summary>
public async Task ListEventsRequestObjectAsync()
{
// Snippet: ListEventsAsync(ListEventsRequest, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ListEventsRequest request = new ListEventsRequest
{
ProjectNameAsProjectName = ProjectName.FromProject("[PROJECT]"),
GroupId = "",
ServiceFilter = new ServiceContextFilter(),
TimeRange = new QueryTimeRange(),
};
// Make the request
PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEventsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEvents</summary>
public void ListEvents()
{
// Snippet: ListEvents(string, string, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
string projectName = "projects/[PROJECT]";
string groupId = "";
// Make the request
PagedEnumerable<ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEvents(projectName, groupId);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEventsAsync</summary>
public async Task ListEventsAsync()
{
// Snippet: ListEventsAsync(string, string, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
string projectName = "projects/[PROJECT]";
string groupId = "";
// Make the request
PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEventsAsync(projectName, groupId);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEvents</summary>
public void ListEventsResourceNames()
{
// Snippet: ListEvents(ProjectName, string, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ProjectName projectName = ProjectName.FromProject("[PROJECT]");
string groupId = "";
// Make the request
PagedEnumerable<ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEvents(projectName, groupId);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEventsAsync</summary>
public async Task ListEventsResourceNamesAsync()
{
// Snippet: ListEventsAsync(ProjectName, string, string, int?, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName projectName = ProjectName.FromProject("[PROJECT]");
string groupId = "";
// Make the request
PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEventsAsync(projectName, groupId);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteEvents</summary>
public void DeleteEventsRequestObject()
{
// Snippet: DeleteEvents(DeleteEventsRequest, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
DeleteEventsRequest request = new DeleteEventsRequest
{
ProjectNameAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
DeleteEventsResponse response = errorStatsServiceClient.DeleteEvents(request);
// End snippet
}
/// <summary>Snippet for DeleteEventsAsync</summary>
public async Task DeleteEventsRequestObjectAsync()
{
// Snippet: DeleteEventsAsync(DeleteEventsRequest, CallSettings)
// Additional: DeleteEventsAsync(DeleteEventsRequest, CancellationToken)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteEventsRequest request = new DeleteEventsRequest
{
ProjectNameAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
DeleteEventsResponse response = await errorStatsServiceClient.DeleteEventsAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteEvents</summary>
public void DeleteEvents()
{
// Snippet: DeleteEvents(string, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
string projectName = "projects/[PROJECT]";
// Make the request
DeleteEventsResponse response = errorStatsServiceClient.DeleteEvents(projectName);
// End snippet
}
/// <summary>Snippet for DeleteEventsAsync</summary>
public async Task DeleteEventsAsync()
{
// Snippet: DeleteEventsAsync(string, CallSettings)
// Additional: DeleteEventsAsync(string, CancellationToken)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
string projectName = "projects/[PROJECT]";
// Make the request
DeleteEventsResponse response = await errorStatsServiceClient.DeleteEventsAsync(projectName);
// End snippet
}
/// <summary>Snippet for DeleteEvents</summary>
public void DeleteEventsResourceNames()
{
// Snippet: DeleteEvents(ProjectName, CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ProjectName projectName = ProjectName.FromProject("[PROJECT]");
// Make the request
DeleteEventsResponse response = errorStatsServiceClient.DeleteEvents(projectName);
// End snippet
}
/// <summary>Snippet for DeleteEventsAsync</summary>
public async Task DeleteEventsResourceNamesAsync()
{
// Snippet: DeleteEventsAsync(ProjectName, CallSettings)
// Additional: DeleteEventsAsync(ProjectName, CancellationToken)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName projectName = ProjectName.FromProject("[PROJECT]");
// Make the request
DeleteEventsResponse response = await errorStatsServiceClient.DeleteEventsAsync(projectName);
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml;
using System.Xml.Serialization;
namespace System.ServiceModel.Description
{
public class XmlSerializerOperationBehavior : IOperationBehavior
{
private readonly Reflector.OperationReflector _reflector;
private readonly bool _builtInOperationBehavior;
public XmlSerializerOperationBehavior(OperationDescription operation)
: this(operation, null)
{
}
public XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute)
{
if (operation == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation");
Reflector parentReflector = new Reflector(operation.DeclaringContract.Namespace, operation.DeclaringContract.ContractType);
_reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute());
}
internal XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute, Reflector parentReflector)
: this(operation, attribute)
{
// used by System.ServiceModel.Web
_reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute());
}
private XmlSerializerOperationBehavior(Reflector.OperationReflector reflector, bool builtInOperationBehavior)
{
Fx.Assert(reflector != null, "");
_reflector = reflector;
_builtInOperationBehavior = builtInOperationBehavior;
}
internal Reflector.OperationReflector OperationReflector
{
get { return _reflector; }
}
internal bool IsBuiltInOperationBehavior
{
get { return _builtInOperationBehavior; }
}
public XmlSerializerFormatAttribute XmlSerializerFormatAttribute
{
get
{
return _reflector.Attribute;
}
}
internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation)
{
return new XmlSerializerOperationBehavior(operation).CreateFormatter();
}
internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation, XmlSerializerFormatAttribute attr)
{
return new XmlSerializerOperationBehavior(operation, attr).CreateFormatter();
}
internal static void AddBehaviors(ContractDescription contract)
{
AddBehaviors(contract, false);
}
internal static void AddBuiltInBehaviors(ContractDescription contract)
{
AddBehaviors(contract, true);
}
private static void AddBehaviors(ContractDescription contract, bool builtInOperationBehavior)
{
Reflector reflector = new Reflector(contract.Namespace, contract.ContractType);
foreach (OperationDescription operation in contract.Operations)
{
Reflector.OperationReflector operationReflector = reflector.ReflectOperation(operation);
if (operationReflector != null)
{
bool isInherited = operation.DeclaringContract != contract;
if (!isInherited)
{
operation.Behaviors.Add(new XmlSerializerOperationBehavior(operationReflector, builtInOperationBehavior));
}
}
}
}
internal XmlSerializerOperationFormatter CreateFormatter()
{
return new XmlSerializerOperationFormatter(_reflector.Operation, _reflector.Attribute, _reflector.Request, _reflector.Reply);
}
private XmlSerializerFaultFormatter CreateFaultFormatter(SynchronizedCollection<FaultContractInfo> faultContractInfos)
{
return new XmlSerializerFaultFormatter(faultContractInfos, _reflector.XmlSerializerFaultContractInfos);
}
void IOperationBehavior.Validate(OperationDescription description)
{
}
void IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
{
}
void IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
if (dispatch == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatch");
if (dispatch.Formatter == null)
{
dispatch.Formatter = (IDispatchMessageFormatter)CreateFormatter();
dispatch.DeserializeRequest = _reflector.RequestRequiresSerialization;
dispatch.SerializeReply = _reflector.ReplyRequiresSerialization;
}
if (_reflector.Attribute.SupportFaults && !dispatch.IsFaultFormatterSetExplicit)
{
dispatch.FaultFormatter = (IDispatchFaultFormatter)CreateFaultFormatter(dispatch.FaultContractInfos);
}
}
void IOperationBehavior.ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
if (proxy == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("proxy");
if (proxy.Formatter == null)
{
proxy.Formatter = (IClientMessageFormatter)CreateFormatter();
proxy.SerializeRequest = _reflector.RequestRequiresSerialization;
proxy.DeserializeReply = _reflector.ReplyRequiresSerialization;
}
if (_reflector.Attribute.SupportFaults && !proxy.IsFaultFormatterSetExplicit)
proxy.FaultFormatter = (IClientFaultFormatter)CreateFaultFormatter(proxy.FaultContractInfos);
}
// helper for reflecting operations
internal class Reflector
{
private readonly XmlSerializerImporter _importer;
private readonly SerializerGenerationContext _generation;
private Collection<OperationReflector> _operationReflectors = new Collection<OperationReflector>();
private object _thisLock = new object();
internal Reflector(string defaultNs, Type type)
{
_importer = new XmlSerializerImporter(defaultNs);
_generation = new SerializerGenerationContext(type);
}
internal void EnsureMessageInfos()
{
lock (_thisLock)
{
foreach (OperationReflector operationReflector in _operationReflectors)
{
operationReflector.EnsureMessageInfos();
}
}
}
private static XmlSerializerFormatAttribute FindAttribute(OperationDescription operation)
{
Type contractType = operation.DeclaringContract != null ? operation.DeclaringContract.ContractType : null;
XmlSerializerFormatAttribute contractFormatAttribute = contractType != null ? TypeLoader.GetFormattingAttribute(contractType, null) as XmlSerializerFormatAttribute : null;
return TypeLoader.GetFormattingAttribute(operation.OperationMethod, contractFormatAttribute) as XmlSerializerFormatAttribute;
}
// auto-reflects the operation, returning null if no attribute was found or inherited
internal OperationReflector ReflectOperation(OperationDescription operation)
{
XmlSerializerFormatAttribute attr = FindAttribute(operation);
if (attr == null)
return null;
return ReflectOperation(operation, attr);
}
// overrides the auto-reflection with an attribute
internal OperationReflector ReflectOperation(OperationDescription operation, XmlSerializerFormatAttribute attrOverride)
{
OperationReflector operationReflector = new OperationReflector(this, operation, attrOverride, true/*reflectOnDemand*/);
_operationReflectors.Add(operationReflector);
return operationReflector;
}
internal class OperationReflector
{
private readonly Reflector _parent;
internal readonly OperationDescription Operation;
internal readonly XmlSerializerFormatAttribute Attribute;
internal readonly bool IsRpc;
internal readonly bool IsOneWay;
internal readonly bool RequestRequiresSerialization;
internal readonly bool ReplyRequiresSerialization;
private readonly string _keyBase;
private MessageInfo _request;
private MessageInfo _reply;
private SynchronizedCollection<XmlSerializerFaultContractInfo> _xmlSerializerFaultContractInfos;
internal OperationReflector(Reflector parent, OperationDescription operation, XmlSerializerFormatAttribute attr, bool reflectOnDemand)
{
Fx.Assert(parent != null, "");
Fx.Assert(operation != null, "");
Fx.Assert(attr != null, "");
OperationFormatter.Validate(operation, attr.Style == OperationFormatStyle.Rpc, false/*IsEncoded*/);
_parent = parent;
this.Operation = operation;
this.Attribute = attr;
this.IsRpc = (attr.Style == OperationFormatStyle.Rpc);
this.IsOneWay = operation.Messages.Count == 1;
this.RequestRequiresSerialization = !operation.Messages[0].IsUntypedMessage;
this.ReplyRequiresSerialization = !this.IsOneWay && !operation.Messages[1].IsUntypedMessage;
MethodInfo methodInfo = operation.OperationMethod;
if (methodInfo == null)
{
// keyBase needs to be unique within the scope of the parent reflector
_keyBase = string.Empty;
if (operation.DeclaringContract != null)
{
_keyBase = operation.DeclaringContract.Name + "," + operation.DeclaringContract.Namespace + ":";
}
_keyBase = _keyBase + operation.Name;
}
else
_keyBase = methodInfo.DeclaringType.FullName + ":" + methodInfo.ToString();
foreach (MessageDescription message in operation.Messages)
foreach (MessageHeaderDescription header in message.Headers)
SetUnknownHeaderInDescription(header);
if (!reflectOnDemand)
{
this.EnsureMessageInfos();
}
}
private void SetUnknownHeaderInDescription(MessageHeaderDescription header)
{
if (header.AdditionalAttributesProvider != null)
{
object[] attrs = header.AdditionalAttributesProvider.GetCustomAttributes(false);
foreach (var attr in attrs)
{
if (attr is XmlAnyElementAttribute)
{
if (String.IsNullOrEmpty(((XmlAnyElementAttribute)attr).Name))
{
header.IsUnknownHeaderCollection = true;
}
}
}
}
}
private string ContractName
{
get { return this.Operation.DeclaringContract.Name; }
}
private string ContractNamespace
{
get { return this.Operation.DeclaringContract.Namespace; }
}
internal MessageInfo Request
{
get
{
_parent.EnsureMessageInfos();
return _request;
}
}
internal MessageInfo Reply
{
get
{
_parent.EnsureMessageInfos();
return _reply;
}
}
internal SynchronizedCollection<XmlSerializerFaultContractInfo> XmlSerializerFaultContractInfos
{
get
{
_parent.EnsureMessageInfos();
return _xmlSerializerFaultContractInfos;
}
}
internal void EnsureMessageInfos()
{
if (_request == null)
{
foreach (Type knownType in Operation.KnownTypes)
{
if (knownType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxKnownTypeNull, Operation.Name)));
_parent._importer.IncludeType(knownType);
}
_request = CreateMessageInfo(this.Operation.Messages[0], ":Request");
// We don't do the following check at Net Native runtime because XmlMapping.XsdElementName
// is not available at that time.
bool skipVerifyXsdElementName = false;
#if FEATURE_NETNATIVE
skipVerifyXsdElementName = GeneratedXmlSerializers.IsInitialized;
#endif
if (_request != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _request.BodyMapping.XsdElementName != this.Operation.Name)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[0].MessageName, _request.BodyMapping.XsdElementName, this.Operation.Name)));
if (!this.IsOneWay)
{
_reply = CreateMessageInfo(this.Operation.Messages[1], ":Response");
XmlName responseName = TypeLoader.GetBodyWrapperResponseName(this.Operation.Name);
if (_reply != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _reply.BodyMapping.XsdElementName != responseName.EncodedName)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[1].MessageName, _reply.BodyMapping.XsdElementName, responseName.EncodedName)));
}
if (this.Attribute.SupportFaults)
{
GenerateXmlSerializerFaultContractInfos();
}
}
}
private void GenerateXmlSerializerFaultContractInfos()
{
SynchronizedCollection<XmlSerializerFaultContractInfo> faultInfos = new SynchronizedCollection<XmlSerializerFaultContractInfo>();
for (int i = 0; i < this.Operation.Faults.Count; i++)
{
FaultDescription fault = this.Operation.Faults[i];
FaultContractInfo faultContractInfo = new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, this.Operation.KnownTypes);
XmlQualifiedName elementName;
XmlMembersMapping xmlMembersMapping = this.ImportFaultElement(fault, out elementName);
SerializerStub serializerStub = _parent._generation.AddSerializer(xmlMembersMapping);
faultInfos.Add(new XmlSerializerFaultContractInfo(faultContractInfo, serializerStub, elementName));
}
_xmlSerializerFaultContractInfos = faultInfos;
}
private MessageInfo CreateMessageInfo(MessageDescription message, string key)
{
if (message.IsUntypedMessage)
return null;
MessageInfo info = new MessageInfo();
bool isEncoded = false;
if (message.IsTypedMessage)
key = message.MessageType.FullName + ":" + isEncoded + ":" + IsRpc;
XmlMembersMapping headersMapping = LoadHeadersMapping(message, key + ":Headers");
info.SetHeaders(_parent._generation.AddSerializer(headersMapping));
MessagePartDescriptionCollection rpcEncodedTypedMessgeBodyParts;
info.SetBody(_parent._generation.AddSerializer(LoadBodyMapping(message, key, out rpcEncodedTypedMessgeBodyParts)), rpcEncodedTypedMessgeBodyParts);
CreateHeaderDescriptionTable(message, info, headersMapping);
return info;
}
private void CreateHeaderDescriptionTable(MessageDescription message, MessageInfo info, XmlMembersMapping headersMapping)
{
int headerNameIndex = 0;
OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable = new OperationFormatter.MessageHeaderDescriptionTable();
info.SetHeaderDescriptionTable(headerDescriptionTable);
foreach (MessageHeaderDescription header in message.Headers)
{
if (header.IsUnknownHeaderCollection)
info.SetUnknownHeaderDescription(header);
else if (headersMapping != null)
{
XmlMemberMapping memberMapping = headersMapping[headerNameIndex++];
if (GeneratedXmlSerializers.IsInitialized)
{
// If GeneratedXmlSerializers has been initialized, we would use the
// mappings generated by .Net Native tools. In that case, the mappings
// we genrated at Runtime are just fake mapping instance which have
// no valid name/namespace. Therefore we cannot do the checks in the
// else block. Those checks should have been done during NET Native
// precompilation.
headerDescriptionTable.Add(header.Name, header.Namespace, header);
}
else
{
string headerName, headerNs;
headerName = memberMapping.XsdElementName;
headerNs = memberMapping.Namespace;
if (headerName != header.Name)
{
if (message.MessageType != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Name, headerName)));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Name, headerName)));
}
if (headerNs != header.Namespace)
{
if (message.MessageType != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Namespace, headerNs)));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Namespace, headerNs)));
}
headerDescriptionTable.Add(headerName, headerNs, header);
}
}
}
}
private XmlMembersMapping LoadBodyMapping(MessageDescription message, string mappingKey, out MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts)
{
MessagePartDescription returnPart;
string wrapperName, wrapperNs;
MessagePartDescriptionCollection bodyParts;
rpcEncodedTypedMessageBodyParts = null;
returnPart = OperationFormatter.IsValidReturnValue(message.Body.ReturnValue) ? message.Body.ReturnValue : null;
bodyParts = message.Body.Parts;
wrapperName = message.Body.WrapperName;
wrapperNs = message.Body.WrapperNamespace;
bool isWrapped = (wrapperName != null);
bool hasReturnValue = returnPart != null;
int paramCount = bodyParts.Count + (hasReturnValue ? 1 : 0);
if (paramCount == 0 && !isWrapped) // no need to create serializer
{
return null;
}
XmlReflectionMember[] members = new XmlReflectionMember[paramCount];
int paramIndex = 0;
if (hasReturnValue)
members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(returnPart, IsRpc, isWrapped);
for (int i = 0; i < bodyParts.Count; i++)
members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(bodyParts[i], IsRpc, isWrapped);
if (!isWrapped)
wrapperNs = ContractNamespace;
return ImportMembersMapping(wrapperName, wrapperNs, members, isWrapped, IsRpc, mappingKey);
}
private XmlMembersMapping LoadHeadersMapping(MessageDescription message, string mappingKey)
{
int headerCount = message.Headers.Count;
if (headerCount == 0)
return null;
int unknownHeaderCount = 0, headerIndex = 0;
XmlReflectionMember[] members = new XmlReflectionMember[headerCount];
for (int i = 0; i < headerCount; i++)
{
MessageHeaderDescription header = message.Headers[i];
if (!header.IsUnknownHeaderCollection)
{
members[headerIndex++] = XmlSerializerHelper.GetXmlReflectionMember(header, false/*isRpc*/, false/*isWrapped*/);
}
else
{
unknownHeaderCount++;
}
}
if (unknownHeaderCount == headerCount)
{
return null;
}
if (unknownHeaderCount > 0)
{
XmlReflectionMember[] newMembers = new XmlReflectionMember[headerCount - unknownHeaderCount];
Array.Copy(members, newMembers, newMembers.Length);
members = newMembers;
}
return ImportMembersMapping(ContractName, ContractNamespace, members, false /*isWrapped*/, false /*isRpc*/, mappingKey);
}
internal XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey)
{
string key = mappingKey.StartsWith(":", StringComparison.Ordinal) ? _keyBase + mappingKey : mappingKey;
return _parent._importer.ImportMembersMapping(new XmlName(elementName, true /*isEncoded*/), ns, members, hasWrapperElement, rpc, key);
}
internal XmlMembersMapping ImportFaultElement(FaultDescription fault, out XmlQualifiedName elementName)
{
// the number of reflection members is always 1 because there is only one fault detail type
XmlReflectionMember[] members = new XmlReflectionMember[1];
XmlName faultElementName = fault.ElementName;
string faultNamespace = fault.Namespace;
if (faultElementName == null)
{
XmlTypeMapping mapping = _parent._importer.ImportTypeMapping(fault.DetailType);
faultElementName = new XmlName(mapping.ElementName, false /*isEncoded*/);
faultNamespace = mapping.Namespace;
if (faultElementName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxFaultTypeAnonymous, this.Operation.Name, fault.DetailType.FullName)));
}
elementName = new XmlQualifiedName(faultElementName.DecodedName, faultNamespace);
members[0] = XmlSerializerHelper.GetXmlReflectionMember(null /*memberName*/, faultElementName, faultNamespace, fault.DetailType,
null /*additionalAttributesProvider*/, false /*isMultiple*/, false /*isWrapped*/);
string mappingKey = "fault:" + faultElementName.DecodedName + ":" + faultNamespace;
return ImportMembersMapping(faultElementName.EncodedName, faultNamespace, members, false /*hasWrapperElement*/, this.IsRpc, mappingKey);
}
}
private class XmlSerializerImporter
{
private readonly string _defaultNs;
private XmlReflectionImporter _xmlImporter;
private Dictionary<string, XmlMembersMapping> _xmlMappings;
private HashSet<Type> _includedTypes;
internal XmlSerializerImporter(string defaultNs)
{
_defaultNs = defaultNs;
_xmlImporter = null;
}
private XmlReflectionImporter XmlImporter
{
get
{
if (_xmlImporter == null)
{
_xmlImporter = new XmlReflectionImporter(_defaultNs);
}
return _xmlImporter;
}
}
private Dictionary<string, XmlMembersMapping> XmlMappings
{
get
{
if (_xmlMappings == null)
{
_xmlMappings = new Dictionary<string, XmlMembersMapping>();
}
return _xmlMappings;
}
}
private HashSet<Type> IncludedTypes
{
get
{
if (_includedTypes == null)
{
_includedTypes = new HashSet<Type>();
}
return _includedTypes;
}
}
internal XmlMembersMapping ImportMembersMapping(XmlName elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey)
{
XmlMembersMapping mapping;
string mappingName = elementName.DecodedName;
if (XmlMappings.TryGetValue(mappingKey, out mapping))
{
return mapping;
}
mapping = this.XmlImporter.ImportMembersMapping(mappingName, ns, members, hasWrapperElement, rpc);
mapping.SetKey(mappingKey);
XmlMappings.Add(mappingKey, mapping);
return mapping;
}
internal XmlTypeMapping ImportTypeMapping(Type type)
{
return this.XmlImporter.ImportTypeMapping(type);
}
internal void IncludeType(Type knownType)
{
// XmlReflectionImporter.IncludeTypes calls XmlReflectionImporter.ImportTypeMapping to generate mappings
// for types and store those mappings.
// XmlReflectionImporter.ImportTypeMapping internally uses HashTables for caching imported mappings.
// But it's still very costly to call XmlReflectionImporter.ImportTypeMapping because XmlReflectionImporter.ImportTypeMapping
// method takes many params and the generated mapping can vary on all those params. XmlReflectionImporter
// needs to do some work before it can use its caches.
//
// In this case, the mapping should only vary on the value of the knownType.
// Including a type twice doesn't make any difference than including the type once. Therefore we use
// IncludedTypes to store the types that have been included and skip them later.
if (IncludedTypes.Contains(knownType))
return;
this.XmlImporter.IncludeType(knownType);
IncludedTypes.Add(knownType);
}
}
internal class SerializerGenerationContext
{
private List<XmlMembersMapping> _mappings = new List<XmlMembersMapping>();
private XmlSerializer[] _serializers = null;
private Type _type;
private object _thisLock = new object();
internal SerializerGenerationContext(Type type)
{
_type = type;
}
// returns a stub to a serializer
internal SerializerStub AddSerializer(XmlMembersMapping mapping)
{
int handle = -1;
if (mapping != null)
{
handle = ((IList)_mappings).Add(mapping);
}
return new SerializerStub(this, mapping, handle);
}
internal XmlSerializer GetSerializer(int handle)
{
if (handle < 0)
{
return null;
}
if (_serializers == null)
{
lock (_thisLock)
{
if (_serializers == null)
{
_serializers = GenerateSerializers();
}
}
}
return _serializers[handle];
}
private XmlSerializer[] GenerateSerializers()
{
//this.Mappings may have duplicate mappings (for e.g. same message contract is used by more than one operation)
//XmlSerializer.FromMappings require unique mappings. The following code uniquifies, calls FromMappings and deuniquifies
List<XmlMembersMapping> uniqueMappings = new List<XmlMembersMapping>();
int[] uniqueIndexes = new int[_mappings.Count];
for (int srcIndex = 0; srcIndex < _mappings.Count; srcIndex++)
{
XmlMembersMapping mapping = _mappings[srcIndex];
int uniqueIndex = uniqueMappings.IndexOf(mapping);
if (uniqueIndex < 0)
{
uniqueMappings.Add(mapping);
uniqueIndex = uniqueMappings.Count - 1;
}
uniqueIndexes[srcIndex] = uniqueIndex;
}
XmlSerializer[] uniqueSerializers = CreateSerializersFromMappings(uniqueMappings.ToArray(), _type);
if (uniqueMappings.Count == _mappings.Count)
return uniqueSerializers;
XmlSerializer[] serializers = new XmlSerializer[_mappings.Count];
for (int i = 0; i < _mappings.Count; i++)
{
serializers[i] = uniqueSerializers[uniqueIndexes[i]];
}
return serializers;
}
[Fx.Tag.SecurityNote(Critical = "XmlSerializer.FromMappings has a LinkDemand.",
Safe = "LinkDemand is spurious, not protecting anything in particular.")]
[SecuritySafeCritical]
private XmlSerializer[] CreateSerializersFromMappings(XmlMapping[] mappings, Type type)
{
return XmlSerializerHelper.FromMappings(mappings, type);
}
}
internal struct SerializerStub
{
private readonly SerializerGenerationContext _context;
internal readonly XmlMembersMapping Mapping;
internal readonly int Handle;
internal SerializerStub(SerializerGenerationContext context, XmlMembersMapping mapping, int handle)
{
_context = context;
this.Mapping = mapping;
this.Handle = handle;
}
internal XmlSerializer GetSerializer()
{
return _context.GetSerializer(Handle);
}
}
internal class XmlSerializerFaultContractInfo
{
private FaultContractInfo _faultContractInfo;
private SerializerStub _serializerStub;
private XmlQualifiedName _faultContractElementName;
private XmlSerializerObjectSerializer _serializer;
internal XmlSerializerFaultContractInfo(FaultContractInfo faultContractInfo, SerializerStub serializerStub,
XmlQualifiedName faultContractElementName)
{
if (faultContractInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractInfo");
}
if (faultContractElementName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractElementName");
}
_faultContractInfo = faultContractInfo;
_serializerStub = serializerStub;
_faultContractElementName = faultContractElementName;
}
internal FaultContractInfo FaultContractInfo
{
get { return _faultContractInfo; }
}
internal XmlQualifiedName FaultContractElementName
{
get { return _faultContractElementName; }
}
internal XmlSerializerObjectSerializer Serializer
{
get
{
if (_serializer == null)
_serializer = new XmlSerializerObjectSerializer(_faultContractInfo.Detail, _faultContractElementName, _serializerStub.GetSerializer());
return _serializer;
}
}
}
internal class MessageInfo : XmlSerializerOperationFormatter.MessageInfo
{
private SerializerStub _headers;
private SerializerStub _body;
private OperationFormatter.MessageHeaderDescriptionTable _headerDescriptionTable;
private MessageHeaderDescription _unknownHeaderDescription;
private MessagePartDescriptionCollection _rpcEncodedTypedMessageBodyParts;
internal XmlMembersMapping BodyMapping
{
get { return _body.Mapping; }
}
internal override XmlSerializer BodySerializer
{
get { return _body.GetSerializer(); }
}
internal XmlMembersMapping HeadersMapping
{
get { return _headers.Mapping; }
}
internal override XmlSerializer HeaderSerializer
{
get { return _headers.GetSerializer(); }
}
internal override OperationFormatter.MessageHeaderDescriptionTable HeaderDescriptionTable
{
get { return _headerDescriptionTable; }
}
internal override MessageHeaderDescription UnknownHeaderDescription
{
get { return _unknownHeaderDescription; }
}
internal override MessagePartDescriptionCollection RpcEncodedTypedMessageBodyParts
{
get { return _rpcEncodedTypedMessageBodyParts; }
}
internal void SetBody(SerializerStub body, MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts)
{
_body = body;
_rpcEncodedTypedMessageBodyParts = rpcEncodedTypedMessageBodyParts;
}
internal void SetHeaders(SerializerStub headers)
{
_headers = headers;
}
internal void SetHeaderDescriptionTable(OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable)
{
_headerDescriptionTable = headerDescriptionTable;
}
internal void SetUnknownHeaderDescription(MessageHeaderDescription unknownHeaderDescription)
{
_unknownHeaderDescription = unknownHeaderDescription;
}
}
}
}
internal static class XmlSerializerHelper
{
static internal XmlReflectionMember GetXmlReflectionMember(MessagePartDescription part, bool isRpc, bool isWrapped)
{
string ns = isRpc ? null : part.Namespace;
MemberInfo additionalAttributesProvider = null;
if (part.AdditionalAttributesProvider.MemberInfo != null)
additionalAttributesProvider = part.AdditionalAttributesProvider.MemberInfo;
XmlName memberName = string.IsNullOrEmpty(part.UniquePartName) ? null : new XmlName(part.UniquePartName, true /*isEncoded*/);
XmlName elementName = part.XmlName;
return GetXmlReflectionMember(memberName, elementName, ns, part.Type, additionalAttributesProvider, part.Multiple, isWrapped);
}
static internal XmlReflectionMember GetXmlReflectionMember(XmlName memberName, XmlName elementName, string ns, Type type, MemberInfo additionalAttributesProvider, bool isMultiple, bool isWrapped)
{
XmlReflectionMember member = new XmlReflectionMember();
member.MemberName = (memberName ?? elementName).DecodedName;
member.MemberType = type;
if (member.MemberType.IsByRef)
member.MemberType = member.MemberType.GetElementType();
if (isMultiple)
member.MemberType = member.MemberType.MakeArrayType();
if (additionalAttributesProvider != null)
{
#if NETStandard13
member.XmlAttributes = XmlAttributesHelper.CreateXmlAttributes(additionalAttributesProvider);
#else
member.XmlAttributes = new XmlAttributes(additionalAttributesProvider);
#endif
}
if (member.XmlAttributes == null)
member.XmlAttributes = new XmlAttributes();
else
{
Type invalidAttributeType = null;
if (member.XmlAttributes.XmlAttribute != null)
invalidAttributeType = typeof(XmlAttributeAttribute);
else if (member.XmlAttributes.XmlAnyAttribute != null && !isWrapped)
invalidAttributeType = typeof(XmlAnyAttributeAttribute);
else if (member.XmlAttributes.XmlChoiceIdentifier != null)
invalidAttributeType = typeof(XmlChoiceIdentifierAttribute);
else if (member.XmlAttributes.XmlIgnore)
invalidAttributeType = typeof(XmlIgnoreAttribute);
else if (member.XmlAttributes.Xmlns)
invalidAttributeType = typeof(XmlNamespaceDeclarationsAttribute);
else if (member.XmlAttributes.XmlText != null)
invalidAttributeType = typeof(XmlTextAttribute);
else if (member.XmlAttributes.XmlEnum != null)
invalidAttributeType = typeof(XmlEnumAttribute);
if (invalidAttributeType != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(isWrapped ? SR.SFxInvalidXmlAttributeInWrapped : SR.SFxInvalidXmlAttributeInBare, invalidAttributeType, elementName.DecodedName)));
if (member.XmlAttributes.XmlArray != null && isMultiple)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxXmlArrayNotAllowedForMultiple, elementName.DecodedName, ns)));
}
bool isArray = member.MemberType.IsArray;
if ((isArray && !isMultiple && member.MemberType != typeof(byte[])) ||
(!isArray && typeof(IEnumerable).IsAssignableFrom(member.MemberType) && member.MemberType != typeof(string) && !typeof(XmlNode).IsAssignableFrom(member.MemberType) && !typeof(IXmlSerializable).IsAssignableFrom(member.MemberType)))
{
if (member.XmlAttributes.XmlArray != null)
{
if (member.XmlAttributes.XmlArray.ElementName == String.Empty)
member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName;
if (member.XmlAttributes.XmlArray.Namespace == null)
member.XmlAttributes.XmlArray.Namespace = ns;
}
else if (HasNoXmlParameterAttributes(member.XmlAttributes))
{
member.XmlAttributes.XmlArray = new XmlArrayAttribute();
member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName;
member.XmlAttributes.XmlArray.Namespace = ns;
}
}
else
{
if (member.XmlAttributes.XmlElements == null || member.XmlAttributes.XmlElements.Count == 0)
{
if (HasNoXmlParameterAttributes(member.XmlAttributes))
{
XmlElementAttribute elementAttribute = new XmlElementAttribute();
elementAttribute.ElementName = elementName.DecodedName;
elementAttribute.Namespace = ns;
member.XmlAttributes.XmlElements.Add(elementAttribute);
}
}
else
{
foreach (XmlElementAttribute elementAttribute in member.XmlAttributes.XmlElements)
{
if (elementAttribute.ElementName == String.Empty)
elementAttribute.ElementName = elementName.DecodedName;
if (elementAttribute.Namespace == null)
elementAttribute.Namespace = ns;
}
}
}
return member;
}
private static bool HasNoXmlParameterAttributes(XmlAttributes xmlAttributes)
{
return xmlAttributes.XmlAnyAttribute == null &&
(xmlAttributes.XmlAnyElements == null || xmlAttributes.XmlAnyElements.Count == 0) &&
xmlAttributes.XmlArray == null &&
xmlAttributes.XmlAttribute == null &&
!xmlAttributes.XmlIgnore &&
xmlAttributes.XmlText == null &&
xmlAttributes.XmlChoiceIdentifier == null &&
(xmlAttributes.XmlElements == null || xmlAttributes.XmlElements.Count == 0) &&
!xmlAttributes.Xmlns;
}
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
#if FEATURE_NETNATIVE
if (GeneratedXmlSerializers.IsInitialized)
{
return FromMappingsViaInjection(mappings, type);
}
#endif
return FromMappingsViaReflection(mappings, type);
}
private static XmlSerializer[] FromMappingsViaReflection(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0)
{
return new XmlSerializer[0];
}
#if NETStandard13
Array mappingArray = XmlMappingTypesHelper.InitializeArray(XmlMappingTypesHelper.XmlMappingType, mappings);
MethodInfo method = typeof(XmlSerializer).GetMethod("FromMappings", new Type[] { XmlMappingTypesHelper.XmlMappingType.MakeArrayType(), typeof(Type) });
object result = method.Invoke(null, new object[] { mappingArray, type });
return (XmlSerializer[])result;
#else
return XmlSerializer.FromMappings(mappings, type);
#endif
}
#if FEATURE_NETNATIVE
private static XmlSerializer[] FromMappingsViaInjection(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
for (int i = 0; i < serializers.Length; i++)
{
Type t;
GeneratedXmlSerializers.GetGeneratedSerializers().TryGetValue(mappings[i].Key, out t);
if (t == null)
{
throw new InvalidOperationException(SR.Format(SR.SFxXmlSerializerIsNotFound, type));
}
serializers[i] = new XmlSerializer(t);
}
return serializers;
}
#endif
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkyLightComponent.h:96
namespace UnrealEngine
{
public partial class USkyLightComponent : ULightComponentBase
{
public USkyLightComponent(IntPtr adress)
: base(adress)
{
}
public USkyLightComponent(UObject Parent = null, string Name = "SkyLightComponent")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_USkyLightComponent(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_PROP_USkyLightComponent_bCaptureEmissiveOnly_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_bCaptureEmissiveOnly_SET(IntPtr Ptr, bool Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_PROP_USkyLightComponent_bLowerHemisphereIsBlack_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_bLowerHemisphereIsBlack_SET(IntPtr Ptr, bool Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_USkyLightComponent_Contrast_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_Contrast_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_USkyLightComponent_CubemapResolution_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_CubemapResolution_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_USkyLightComponent_LowerHemisphereColor_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_LowerHemisphereColor_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_USkyLightComponent_MinOcclusion_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_MinOcclusion_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_USkyLightComponent_OcclusionExponent_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_OcclusionExponent_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_USkyLightComponent_OcclusionMaxDistance_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_OcclusionMaxDistance_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_USkyLightComponent_SkyDistanceThreshold_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_SkyDistanceThreshold_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_USkyLightComponent_SourceCubemapAngle_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_USkyLightComponent_SourceCubemapAngle_SET(IntPtr Ptr, float Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_USkyLightComponent(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_USkyLightComponent_IsOcclusionSupported(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_RecaptureSky(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SanitizeCubemapSize(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetBlendDestinationCaptureIsDirty(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetCaptureIsDirty(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetIndirectLightingIntensity(IntPtr self, float newIntensity);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetIntensity(IntPtr self, float newIntensity);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetLightColor(IntPtr self, IntPtr newLightColor);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetLowerHemisphereColor(IntPtr self, IntPtr inLowerHemisphereColor);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetMinOcclusion(IntPtr self, float inMinOcclusion);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetOcclusionContrast(IntPtr self, float inOcclusionContrast);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetOcclusionExponent(IntPtr self, float inOcclusionExponent);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_SetVolumetricScatteringIntensity(IntPtr self, float newIntensity);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_UpdateLimitedRenderingStateFast(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_UpdateOcclusionRenderingStateFast(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_USkyLightComponent_UpdateSkyCaptureContents(IntPtr self, IntPtr worldToUpdate);
#endregion
#region Property
/// <summary>
/// Only capture emissive materials. Skips all lighting making the capture cheaper. Recomended when using CaptureEveryFrame
/// </summary>
public bool bCaptureEmissiveOnly
{
get => E_PROP_USkyLightComponent_bCaptureEmissiveOnly_GET(NativePointer);
set => E_PROP_USkyLightComponent_bCaptureEmissiveOnly_SET(NativePointer, value);
}
/// <summary>
/// Whether all distant lighting from the lower hemisphere should be set to LowerHemisphereColor.
/// <para>Enabling this is accurate when lighting a scene on a planet where the ground blocks the sky, </para>
/// However disabling it can be useful to approximate skylight bounce lighting (eg Movable light).
/// </summary>
public bool LowerHemisphereIsSolidColor
{
get => E_PROP_USkyLightComponent_bLowerHemisphereIsBlack_GET(NativePointer);
set => E_PROP_USkyLightComponent_bLowerHemisphereIsBlack_SET(NativePointer, value);
}
/// <summary>
/// Contrast S-curve applied to the computed AO. A value of 0 means no contrast increase, 1 is a significant contrast increase.
/// </summary>
public float OcclusionContrast
{
get => E_PROP_USkyLightComponent_Contrast_GET(NativePointer);
set => E_PROP_USkyLightComponent_Contrast_SET(NativePointer, value);
}
/// <summary>
/// Maximum resolution for the very top processed cubemap mip. Must be a power of 2.
/// </summary>
public int CubemapResolution
{
get => E_PROP_USkyLightComponent_CubemapResolution_GET(NativePointer);
set => E_PROP_USkyLightComponent_CubemapResolution_SET(NativePointer, value);
}
public FLinearColor LowerHemisphereColor
{
get => E_PROP_USkyLightComponent_LowerHemisphereColor_GET(NativePointer);
set => E_PROP_USkyLightComponent_LowerHemisphereColor_SET(NativePointer, value);
}
/// <summary>
/// Controls the darkest that a fully occluded area can get. This tends to destroy contact shadows, use Contrast or OcclusionExponent instead.
/// </summary>
public float MinOcclusion
{
get => E_PROP_USkyLightComponent_MinOcclusion_GET(NativePointer);
set => E_PROP_USkyLightComponent_MinOcclusion_SET(NativePointer, value);
}
/// <summary>
/// Exponent applied to the computed AO. Values lower than 1 brighten occlusion overall without losing contact shadows.
/// </summary>
public float OcclusionExponent
{
get => E_PROP_USkyLightComponent_OcclusionExponent_GET(NativePointer);
set => E_PROP_USkyLightComponent_OcclusionExponent_SET(NativePointer, value);
}
/// <summary>
/// Max distance that the occlusion of one point will affect another.
/// <para>Higher values increase the cost of Distance Field AO exponentially. </para>
/// </summary>
public float OcclusionMaxDistance
{
get => E_PROP_USkyLightComponent_OcclusionMaxDistance_GET(NativePointer);
set => E_PROP_USkyLightComponent_OcclusionMaxDistance_SET(NativePointer, value);
}
/// <summary>
/// Distance from the sky light at which any geometry should be treated as part of the sky.
/// <para>This is also used by reflection captures, so update reflection captures to see the impact. </para>
/// </summary>
public float SkyDistanceThreshold
{
get => E_PROP_USkyLightComponent_SkyDistanceThreshold_GET(NativePointer);
set => E_PROP_USkyLightComponent_SkyDistanceThreshold_SET(NativePointer, value);
}
/// <summary>
/// Angle to rotate the source cubemap when SourceType is set to SLS_SpecifiedCubemap.
/// </summary>
public float SourceCubemapAngle
{
get => E_PROP_USkyLightComponent_SourceCubemapAngle_GET(NativePointer);
set => E_PROP_USkyLightComponent_SourceCubemapAngle_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// Whether sky occlusion is supported by current feature level
/// </summary>
public bool IsOcclusionSupported()
=> E_USkyLightComponent_IsOcclusionSupported(this);
/// <summary>
/// Recaptures the scene for the skylight.
/// <para>This is useful for making sure the sky light is up to date after changing something in the world that it would capture. </para>
/// Warning: this is very costly and will definitely cause a hitch.
/// </summary>
public void RecaptureSky()
=> E_USkyLightComponent_RecaptureSky(this);
public void SanitizeCubemapSize()
=> E_USkyLightComponent_SanitizeCubemapSize(this);
public void SetBlendDestinationCaptureIsDirty()
=> E_USkyLightComponent_SetBlendDestinationCaptureIsDirty(this);
/// <summary>
/// Indicates that the capture needs to recapture the scene, adds it to the recapture queue.
/// </summary>
public void SetCaptureIsDirty()
=> E_USkyLightComponent_SetCaptureIsDirty(this);
public void SetIndirectLightingIntensity(float newIntensity)
=> E_USkyLightComponent_SetIndirectLightingIntensity(this, newIntensity);
public void SetIntensity(float newIntensity)
=> E_USkyLightComponent_SetIntensity(this, newIntensity);
/// <summary>
/// Set color of the light
/// </summary>
public void SetLightColor(FLinearColor newLightColor)
=> E_USkyLightComponent_SetLightColor(this, newLightColor);
public void SetLowerHemisphereColor(FLinearColor inLowerHemisphereColor)
=> E_USkyLightComponent_SetLowerHemisphereColor(this, inLowerHemisphereColor);
public void SetMinOcclusion(float inMinOcclusion)
=> E_USkyLightComponent_SetMinOcclusion(this, inMinOcclusion);
public void SetOcclusionContrast(float inOcclusionContrast)
=> E_USkyLightComponent_SetOcclusionContrast(this, inOcclusionContrast);
public void SetOcclusionExponent(float inOcclusionExponent)
=> E_USkyLightComponent_SetOcclusionExponent(this, inOcclusionExponent);
public void SetVolumetricScatteringIntensity(float newIntensity)
=> E_USkyLightComponent_SetVolumetricScatteringIntensity(this, newIntensity);
protected void UpdateLimitedRenderingStateFast()
=> E_USkyLightComponent_UpdateLimitedRenderingStateFast(this);
protected void UpdateOcclusionRenderingStateFast()
=> E_USkyLightComponent_UpdateOcclusionRenderingStateFast(this);
/// <summary>
/// Called each tick to recapture and queued sky captures.
/// </summary>
public void UpdateSkyCaptureContents(UWorld worldToUpdate)
=> E_USkyLightComponent_UpdateSkyCaptureContents(this, worldToUpdate);
#endregion
public static implicit operator IntPtr(USkyLightComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator USkyLightComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<USkyLightComponent>(PtrDesc);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit;
public static unsafe class EnumTests
{
[Fact]
public static void TestParse()
{
{
Type t = typeof(SimpleEnum);
bool b;
SimpleEnum e;
b = Enum.TryParse<SimpleEnum>("Red", out e);
Assert.True(b);
Assert.Equal(e, SimpleEnum.Red);
b = Enum.TryParse<SimpleEnum>(" Red ", out e);
Assert.True(b);
Assert.Equal(e, SimpleEnum.Red);
b = Enum.TryParse<SimpleEnum>(" red ", out e);
Assert.True(!b);
b = Enum.TryParse<SimpleEnum>(" red ", false, out e);
Assert.True(!b);
b = Enum.TryParse<SimpleEnum>(" red ", true, out e);
Assert.True(b);
Assert.Equal(e, SimpleEnum.Red);
b = Enum.TryParse<SimpleEnum>(" Red , Blue ", out e);
Assert.True(b);
Assert.Equal(e, (SimpleEnum)3);
b = Enum.TryParse<SimpleEnum>("Purple", out e);
Assert.True(!b);
b = Enum.TryParse<SimpleEnum>("1", out e);
Assert.True(b);
Assert.Equal(e, SimpleEnum.Red);
b = Enum.TryParse<SimpleEnum>(" 1 ", out e);
Assert.True(b);
Assert.Equal(e, SimpleEnum.Red);
b = Enum.TryParse<SimpleEnum>("2", out e);
Assert.True(b);
Assert.Equal(e, SimpleEnum.Blue);
b = Enum.TryParse<SimpleEnum>("99", out e);
Assert.True(b);
Assert.Equal(e, (SimpleEnum)99);
return;
}
}
[Fact]
public static void TestGetName()
{
String s;
{
Type t = typeof(SimpleEnum);
s = Enum.GetName(t, 99);
Assert.Equal(s, null);
s = Enum.GetName(t, 1);
Assert.Equal(s, "Red");
s = Enum.GetName(t, SimpleEnum.Red);
Assert.Equal(s, "Red");
// In the case of multiple matches, GetName returns one of them (which one is an implementation detail.)
s = Enum.GetName(t, 3);
Assert.True(s == "Green" || s == "Green_a" || s == "Green_b");
}
// Negative tests
{
Type t = typeof(SimpleEnum);
Assert.Throws<ArgumentNullException>(() => Enum.GetName(null, 1));
Assert.Throws<ArgumentNullException>(() => Enum.GetName(t, null));
Assert.Throws<ArgumentNullException>(() => Enum.GetName(typeof(Object), null));
Assert.Throws<ArgumentException>(() => Enum.GetName(t, "Red"));
Assert.Throws<ArgumentException>(() => Enum.GetName(t, (IntPtr)0));
}
{
/*
* Despite what MSDN says, GetName() does not require passing in the exact integral type.
*
* For the purposes of comparison:
*
* - The enum member value are normalized as follows:
* - unsigned ints zero-extended to 64-bits
* - signed ints sign-extended to 64-bits
*
* - The value passed in as an argument to GetNames() is normalized as follows:
* - unsigned ints zero-extended to 64-bits
* - signed ints sign-extended to 64-bits
*
* Then comparison is done on all 64 bits.
*/
Type t = typeof(SByteEnum);
s = Enum.GetName(t, 0xffffffffffffff80LU);
Assert.Equal(s, "Min");
s = Enum.GetName(t, 0xffffff80u);
Assert.Equal(s, null);
s = Enum.GetName(t, unchecked((int)(0xffffff80u)));
Assert.Equal(s, "Min");
s = Enum.GetName(t, true);
Assert.Equal(s, "One");
s = Enum.GetName(t, (char)1);
Assert.Equal(s, "One");
// The api doesn't even care if you pass in a completely different enum!
s = Enum.GetName(t, SimpleEnum.Red);
Assert.Equal(s, "One");
}
return;
}
[Fact]
public static void TestIsDefined()
{
Type t = typeof(SimpleEnum);
bool b;
// Value can be a string...
b = Enum.IsDefined(t, "Red");
Assert.True(b);
b = Enum.IsDefined(t, "Green");
Assert.True(b);
b = Enum.IsDefined(t, "Blue");
Assert.True(b);
b = Enum.IsDefined(t, " Blue");
Assert.True(!b);
b = Enum.IsDefined(t, "blue");
Assert.True(!b);
// or an Enum value
b = Enum.IsDefined(t, SimpleEnum.Red);
Assert.True(b);
b = Enum.IsDefined(t, (SimpleEnum)(99));
Assert.True(!b);
// but not a different enum.
Assert.Throws<ArgumentException>(() => Enum.IsDefined(t, Int32Enum.One));
// or the underlying integer
b = Enum.IsDefined(t, 1);
Assert.True(b);
b = Enum.IsDefined(t, 99);
Assert.True(!b);
// but not just any integer type.
Assert.Throws<ArgumentException>(() => Enum.IsDefined(t, (short)1));
Assert.Throws<ArgumentException>(() => Enum.IsDefined(t, (uint)1));
// "Combos" do not pass.
b = Enum.IsDefined(typeof(Int32Enum), 0x1 | 0x2);
Assert.True(!b);
// Other negative tests
Assert.Throws<ArgumentNullException>(() => Enum.IsDefined(null, 1));
Assert.Throws<ArgumentNullException>(() => Enum.IsDefined(t, null));
// These throws ArgumentException (though MSDN claims it should throw InvalidOperationException)
Assert.Throws<ArgumentException>(() => Enum.IsDefined(t, true));
Assert.Throws<ArgumentException>(() => Enum.IsDefined(t, 'a'));
// Non-integers throw InvalidOperationException prior to Win8P.
Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(t, (IntPtr)0));
Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(t, 5.5));
Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(t, 5.5f));
return;
}
[Fact]
public static void TestHasFlag()
{
EI32 e = (EI32)0x3f06;
try
{
e.HasFlag(null);
Assert.True(false, "HasFlag should have thrown.");
}
catch (ArgumentNullException)
{
}
try
{
e.HasFlag((EI32a)0x2);
Assert.True(false, "HasFlag should have thrown.");
}
catch (ArgumentException)
{
}
bool b;
b = e.HasFlag((EI32)(0x3000));
Assert.True(b);
b = e.HasFlag((EI32)(0x1000));
Assert.True(b);
b = e.HasFlag((EI32)(0x0000));
Assert.True(b);
b = e.HasFlag((EI32)(0x0010));
Assert.False(b);
b = e.HasFlag((EI32)(0x3f06));
Assert.True(b);
b = e.HasFlag((EI32)(0x3f16));
Assert.False(b);
}
[Fact]
public static void TestToObject()
{
Object o;
o = 3;
try
{
Enum.ToObject(null, o);
Assert.True(false, "ToObject() should have thrown.");
}
catch (ArgumentNullException)
{
}
o = null;
try
{
Enum.ToObject(typeof(EI8), o);
Assert.True(false, "ToObject() should have thrown.");
}
catch (ArgumentNullException)
{
}
o = 1;
try
{
Enum.ToObject(typeof(Enum), o);
Assert.True(false, "ToObject() should have thrown.");
}
catch (ArgumentException)
{
}
try
{
o = "Hello";
Enum.ToObject(typeof(EI8), o);
Assert.True(false, "ToObject() should have thrown.");
}
catch (ArgumentException)
{
}
TestToObjectVerifySuccess<EI8, sbyte>(42);
TestToObjectVerifySuccess<EI8, EI8>((EI8)0x42);
TestToObjectVerifySuccess<EU64, ulong>(0x0123456789abcdefL);
ulong l = 0x0ccccccccccccc2aL;
EI8 e = (EI8)(Enum.ToObject(typeof(EI8), l));
Assert.True((sbyte)e == 0x2a);
}
private static void TestToObjectVerifySuccess<E, T>(T value)
{
Object oValue = value;
Object e = Enum.ToObject(typeof(E), oValue);
Assert.Equal(e.GetType(), typeof(E));
E expected = (E)(Object)(value);
Object oExpected = (Object)expected; // Workaround for Bartok codegen bug: Calling Object methods on enum through type variable fails (due to missing box)
Assert.True(oExpected.Equals(e));
}
[Fact]
public static void TestHashCode()
{
EI64 e = (EI64)42;
int h = e.GetHashCode();
int h2 = e.GetHashCode();
Assert.Equal(h, h2);
}
[Fact]
public static void TestEquals()
{
EI64 e = (EI64)42;
bool b;
b = e.Equals(null);
Assert.False(b);
b = e.Equals((long)42);
Assert.False(b);
b = e.Equals((EI32)42);
Assert.False(b);
b = e.Equals((EI64)43);
Assert.False(b);
long l = 0x700000000000002aL;
b = e.Equals((EI64)l);
Assert.False(b);
b = e.Equals((EI64)42);
Assert.True(b);
}
[Fact]
public static void TestCompareTo()
{
EI8 e = EI8.One;
int result;
// Special case: All values are "greater than" null.
Object other = null;
result = e.CompareTo(other);
Assert.Equal(result, 1);
try
{
sbyte b = 1;
result = e.CompareTo(b);
Assert.True(false, "CompareTo should have failed.");
}
catch (ArgumentException)
{
}
other = EI8.One;
result = e.CompareTo(other);
Assert.Equal(result, 0);
other = (EI8)(0);
result = e.CompareTo(other);
Assert.True(result > 0);
other = (EI8)(2);
result = e.CompareTo(other);
Assert.True(result < 0);
}
[Fact]
public static void TestGetUnderlyingType()
{
Type t;
try
{
Enum.GetUnderlyingType(null);
Assert.True(false, "GetUnderlyingType should have thrown.");
}
catch (ArgumentNullException)
{
}
try
{
Enum.GetUnderlyingType(typeof(Enum));
Assert.True(false, "GetUnderlyingType should have thrown.");
}
catch (ArgumentException)
{
}
t = Enum.GetUnderlyingType(typeof(EI8));
Assert.Equal(t, typeof(SByte));
t = Enum.GetUnderlyingType(typeof(EU8));
Assert.Equal(t, typeof(Byte));
t = Enum.GetUnderlyingType(typeof(EI16));
Assert.Equal(t, typeof(Int16));
t = Enum.GetUnderlyingType(typeof(EU16));
Assert.Equal(t, typeof(UInt16));
t = Enum.GetUnderlyingType(typeof(EI32));
Assert.Equal(t, typeof(Int32));
t = Enum.GetUnderlyingType(typeof(EU32));
Assert.Equal(t, typeof(UInt32));
t = Enum.GetUnderlyingType(typeof(EI64));
Assert.Equal(t, typeof(Int64));
t = Enum.GetUnderlyingType(typeof(EU64));
Assert.Equal(t, typeof(UInt64));
}
private enum EI8 : sbyte
{
One = 1,
}
private enum EU8 : byte
{
}
private enum EI16 : short
{
}
private enum EU16 : ushort
{
}
private enum EI32 : int
{
}
private enum EI32a : int
{
}
private enum EU32 : uint
{
}
private enum EI64 : long
{
}
private enum EU64 : ulong
{
}
[Fact]
public static void TestGetNamesAndValues()
{
{
String[] names = Enum.GetNames(typeof(SimpleEnum));
SimpleEnum[] values = (SimpleEnum[])(Enum.GetValues(typeof(SimpleEnum)));
int i = 0;
Assert.Equal(names[i], "Red");
Assert.Equal(values[i], SimpleEnum.Red);
i++;
Assert.Equal(names[i], "Blue");
Assert.Equal(values[i], SimpleEnum.Blue);
i++;
Assert.Equal(names[i], "Green");
Assert.Equal(values[i], SimpleEnum.Green);
i++;
Assert.Equal(names[i], "Green_a");
Assert.Equal(values[i], SimpleEnum.Green_a);
i++;
Assert.Equal(names[i], "Green_b");
Assert.Equal(values[i], SimpleEnum.Green_a);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(ByteEnum));
ByteEnum[] values = (ByteEnum[])(Enum.GetValues(typeof(ByteEnum)));
int i = 0;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], ByteEnum.Min);
i++;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], ByteEnum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], ByteEnum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], ByteEnum.Max);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(SByteEnum));
SByteEnum[] values = (SByteEnum[])(Enum.GetValues(typeof(SByteEnum)));
int i = 0;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], SByteEnum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], SByteEnum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], SByteEnum.Max);
i++;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], SByteEnum.Min);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(UInt16Enum));
UInt16Enum[] values = (UInt16Enum[])(Enum.GetValues(typeof(UInt16Enum)));
int i = 0;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], UInt16Enum.Min);
i++;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], UInt16Enum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], UInt16Enum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], UInt16Enum.Max);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(Int16Enum));
Int16Enum[] values = (Int16Enum[])(Enum.GetValues(typeof(Int16Enum)));
int i = 0;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], Int16Enum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], Int16Enum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], Int16Enum.Max);
i++;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], Int16Enum.Min);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(UInt32Enum));
UInt32Enum[] values = (UInt32Enum[])(Enum.GetValues(typeof(UInt32Enum)));
int i = 0;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], UInt32Enum.Min);
i++;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], UInt32Enum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], UInt32Enum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], UInt32Enum.Max);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(Int32Enum));
Int32Enum[] values = (Int32Enum[])(Enum.GetValues(typeof(Int32Enum)));
int i = 0;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], Int32Enum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], Int32Enum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], Int32Enum.Max);
i++;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], Int32Enum.Min);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(UInt64Enum));
UInt64Enum[] values = (UInt64Enum[])(Enum.GetValues(typeof(UInt64Enum)));
int i = 0;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], UInt64Enum.Min);
i++;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], UInt64Enum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], UInt64Enum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], UInt64Enum.Max);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
{
String[] names = Enum.GetNames(typeof(Int64Enum));
Int64Enum[] values = (Int64Enum[])(Enum.GetValues(typeof(Int64Enum)));
int i = 0;
Assert.Equal(names[i], "One");
Assert.Equal(values[i], Int64Enum.One);
i++;
Assert.Equal(names[i], "Two");
Assert.Equal(values[i], Int64Enum.Two);
i++;
Assert.Equal(names[i], "Max");
Assert.Equal(values[i], Int64Enum.Max);
i++;
Assert.Equal(names[i], "Min");
Assert.Equal(values[i], Int64Enum.Min);
i++;
Assert.Equal(names.Length, i);
Assert.Equal(values.Length, i);
}
}
[Fact]
public static void TestFormatD()
{
String s;
s = ByteEnum.Min.ToString("D");
Assert.Equal(s, "0");
s = ByteEnum.One.ToString("D");
Assert.Equal(s, "1");
s = ByteEnum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((ByteEnum)99).ToString("D");
Assert.Equal(s, "99");
s = ByteEnum.Max.ToString("D");
Assert.Equal(s, "255");
s = SByteEnum.Min.ToString("D");
Assert.Equal(s, "-128");
s = SByteEnum.One.ToString("D");
Assert.Equal(s, "1");
s = SByteEnum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((SByteEnum)99).ToString("D");
Assert.Equal(s, "99");
s = SByteEnum.Max.ToString("D");
Assert.Equal(s, "127");
s = UInt16Enum.Min.ToString("D");
Assert.Equal(s, "0");
s = UInt16Enum.One.ToString("D");
Assert.Equal(s, "1");
s = UInt16Enum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((UInt16Enum)99).ToString("D");
Assert.Equal(s, "99");
s = UInt16Enum.Max.ToString("D");
Assert.Equal(s, "65535");
s = Int16Enum.Min.ToString("D");
Assert.Equal(s, "-32768");
s = Int16Enum.One.ToString("D");
Assert.Equal(s, "1");
s = Int16Enum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((Int16Enum)99).ToString("D");
Assert.Equal(s, "99");
s = Int16Enum.Max.ToString("D");
Assert.Equal(s, "32767");
s = UInt32Enum.Min.ToString("D");
Assert.Equal(s, "0");
s = UInt32Enum.One.ToString("D");
Assert.Equal(s, "1");
s = UInt32Enum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((UInt32Enum)99).ToString("D");
Assert.Equal(s, "99");
s = UInt32Enum.Max.ToString("D");
Assert.Equal(s, "4294967295");
s = Int32Enum.Min.ToString("D");
Assert.Equal(s, "-2147483648");
s = Int32Enum.One.ToString("D");
Assert.Equal(s, "1");
s = Int32Enum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((Int32Enum)99).ToString("D");
Assert.Equal(s, "99");
s = Int32Enum.Max.ToString("D");
Assert.Equal(s, "2147483647");
s = UInt64Enum.Min.ToString("D");
Assert.Equal(s, "0");
s = UInt64Enum.One.ToString("D");
Assert.Equal(s, "1");
s = UInt64Enum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((UInt64Enum)99).ToString("D");
Assert.Equal(s, "99");
s = UInt64Enum.Max.ToString("D");
Assert.Equal(s, "18446744073709551615");
s = Int64Enum.Min.ToString("D");
Assert.Equal(s, "-9223372036854775808");
s = Int64Enum.One.ToString("D");
Assert.Equal(s, "1");
s = Int64Enum.Two.ToString("D");
Assert.Equal(s, "2");
s = ((Int64Enum)99).ToString("D");
Assert.Equal(s, "99");
s = Int64Enum.Max.ToString("D");
Assert.Equal(s, "9223372036854775807");
}
[Fact]
public static void TestFormatX()
{
// Format "X": Represents value in hex form without a leading "0x"
String s;
s = ByteEnum.Min.ToString("X");
Assert.Equal(s, "00");
s = ByteEnum.One.ToString("X");
Assert.Equal(s, "01");
s = ByteEnum.Two.ToString("X");
Assert.Equal(s, "02");
s = ((ByteEnum)99).ToString("X");
Assert.Equal(s, "63");
s = ByteEnum.Max.ToString("X");
Assert.Equal(s, "FF");
s = SByteEnum.Min.ToString("X");
Assert.Equal(s, "80");
s = SByteEnum.One.ToString("X");
Assert.Equal(s, "01");
s = SByteEnum.Two.ToString("X");
Assert.Equal(s, "02");
s = ((SByteEnum)99).ToString("X");
Assert.Equal(s, "63");
s = SByteEnum.Max.ToString("X");
Assert.Equal(s, "7F");
s = UInt16Enum.Min.ToString("X");
Assert.Equal(s, "0000");
s = UInt16Enum.One.ToString("X");
Assert.Equal(s, "0001");
s = UInt16Enum.Two.ToString("X");
Assert.Equal(s, "0002");
s = ((UInt16Enum)99).ToString("X");
Assert.Equal(s, "0063");
s = UInt16Enum.Max.ToString("X");
Assert.Equal(s, "FFFF");
s = Int16Enum.Min.ToString("X");
Assert.Equal(s, "8000");
s = Int16Enum.One.ToString("X");
Assert.Equal(s, "0001");
s = Int16Enum.Two.ToString("X");
Assert.Equal(s, "0002");
s = ((Int16Enum)99).ToString("X");
Assert.Equal(s, "0063");
s = Int16Enum.Max.ToString("X");
Assert.Equal(s, "7FFF");
s = UInt32Enum.Min.ToString("X");
Assert.Equal(s, "00000000");
s = UInt32Enum.One.ToString("X");
Assert.Equal(s, "00000001");
s = UInt32Enum.Two.ToString("X");
Assert.Equal(s, "00000002");
s = ((UInt32Enum)99).ToString("X");
Assert.Equal(s, "00000063");
s = UInt32Enum.Max.ToString("X");
Assert.Equal(s, "FFFFFFFF");
s = Int32Enum.Min.ToString("X");
Assert.Equal(s, "80000000");
s = Int32Enum.One.ToString("X");
Assert.Equal(s, "00000001");
s = Int32Enum.Two.ToString("X");
Assert.Equal(s, "00000002");
s = ((Int32Enum)99).ToString("X");
Assert.Equal(s, "00000063");
s = Int32Enum.Max.ToString("X");
Assert.Equal(s, "7FFFFFFF");
s = UInt64Enum.Min.ToString("X");
Assert.Equal(s, "0000000000000000");
s = UInt64Enum.One.ToString("X");
Assert.Equal(s, "0000000000000001");
s = UInt64Enum.Two.ToString("X");
Assert.Equal(s, "0000000000000002");
s = ((UInt64Enum)99).ToString("X");
Assert.Equal(s, "0000000000000063");
s = UInt64Enum.Max.ToString("X");
Assert.Equal(s, "FFFFFFFFFFFFFFFF");
s = Int64Enum.Min.ToString("X");
Assert.Equal(s, "8000000000000000");
s = Int64Enum.One.ToString("X");
Assert.Equal(s, "0000000000000001");
s = Int64Enum.Two.ToString("X");
Assert.Equal(s, "0000000000000002");
s = ((Int64Enum)99).ToString("X");
Assert.Equal(s, "0000000000000063");
s = Int64Enum.Max.ToString("X");
Assert.Equal(s, "7FFFFFFFFFFFFFFF");
}
[Fact]
public static void TestFormatF()
{
// Format "F". value is treated as a bit field that contains one or more flags that consist of one or more bits.
// If value is equal to a combination of named enumerated constants, a delimiter-separated list of the names
// of those constants is returned. value is searched for flags, going from the flag with the largest value
// to the smallest value. For each flag that corresponds to a bit field in value, the name of the constant
// is concatenated to the delimiter-separated list. The value of that flag is then excluded from further
// consideration, and the search continues for the next flag.
//
//If value is not equal to a combination of named enumerated constants, the decimal equivalent of value is returned.
String s;
s = SimpleEnum.Red.ToString("F");
Assert.Equal(s, "Red");
s = SimpleEnum.Blue.ToString("F");
Assert.Equal(s, "Blue");
s = ((SimpleEnum)3).ToString("F");
Assert.True(s == "Green" || s == "Green_a" || s == "Green_b");
s = ((SimpleEnum)99).ToString("F");
Assert.Equal(s, "99");
s = ((SimpleEnum)0).ToString("F");
Assert.Equal(s, "0"); // Not found.
s = ((ByteEnum)0).ToString("F");
Assert.Equal(s, "Min"); // Found
s = ((ByteEnum)3).ToString("F");
Assert.Equal(s, "One, Two"); // Found
// Larger values take precedence (and remove the bits from consideration.)
s = ((ByteEnum)0xff).ToString("F");
Assert.Equal(s, "Max"); // Found
}
[Fact]
public static void TestFormatG()
{
// Format "G": If value is equal to a named enumerated constant, the name of that constant is returned.
// Otherwise, if "[Flags]" present, do as Format "F" - else return the decimal value of "value".
String s;
s = SimpleEnum.Red.ToString("G");
Assert.Equal(s, "Red");
s = SimpleEnum.Blue.ToString("G");
Assert.Equal(s, "Blue");
s = ((SimpleEnum)3).ToString("G");
Assert.True(s == "Green" || s == "Green_a" || s == "Green_b");
s = ((SimpleEnum)99).ToString("G");
Assert.Equal(s, "99");
s = ((SimpleEnum)0).ToString("G");
Assert.Equal(s, "0"); // Not found.
s = ((ByteEnum)0).ToString("G");
Assert.Equal(s, "Min"); // Found
s = ((ByteEnum)3).ToString("G");
Assert.Equal(s, "3"); // No [Flags] attribute
// Larger values take precedence (and remove the bits from consideration.)
s = ((ByteEnum)0xff).ToString("G");
Assert.Equal(s, "Max"); // Found
// An enum with [Flags]
s = (AttributeTargets.Class | AttributeTargets.Delegate).ToString("G");
Assert.Equal(s, "Class, Delegate");
}
[Fact]
public static void TestFormat()
{
String s;
s = Enum.Format(typeof(SimpleEnum), SimpleEnum.Red, "F");
Assert.Equal(s, "Red");
// Can pass enum or exact underlying integral.
s = Enum.Format(typeof(SimpleEnum), 1, "F");
Assert.Equal(s, "Red");
Assert.Throws<ArgumentNullException>(() => Enum.Format(null, (Int32Enum)1, "F"));
Assert.Throws<ArgumentNullException>(() => Enum.Format(typeof(SimpleEnum), null, "F"));
// Not an enum type.
Assert.Throws<ArgumentException>(() => Enum.Format(typeof(Object), 1, "F"));
// Wrong enumType.
Assert.Throws<ArgumentException>(() => Enum.Format(typeof(SimpleEnum), (Int32Enum)1, "F"));
// Wrong integral.
Assert.Throws<ArgumentException>(() => Enum.Format(typeof(SimpleEnum), (short)1, "F"));
// Not an integral.
Assert.Throws<ArgumentException>(() => Enum.Format(typeof(SimpleEnum), "Red", "F"));
}
private enum SimpleEnum
{
Red = 1,
Blue = 2,
Green = 3,
Green_a = 3,
Green_b = 3,
}
private enum ByteEnum : byte
{
Min = 0,
One = 1,
Two = 2,
Max = 0xff,
}
private enum SByteEnum : sbyte
{
Min = -128,
One = 1,
Two = 2,
Max = 127,
}
private enum UInt16Enum : ushort
{
Min = 0,
One = 1,
Two = 2,
Max = 0xffff,
}
private enum Int16Enum : short
{
Min = Int16.MinValue,
One = 1,
Two = 2,
Max = 0x7fff,
}
private enum UInt32Enum : uint
{
Min = 0,
One = 1,
Two = 2,
Max = 0xffffffff,
}
private enum Int32Enum : int
{
Min = Int32.MinValue,
One = 1,
Two = 2,
Max = 0x7fffffff,
}
private enum UInt64Enum : ulong
{
Min = 0,
One = 1,
Two = 2,
Max = 0xffffffffffffffff,
}
private enum Int64Enum : long
{
Min = Int64.MinValue,
One = 1,
Two = 2,
Max = 0x7fffffffffffffff,
}
}
| |
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Squirrel
{
using SQInteger = Int32;
using HSQUIRRELVM = IntPtr;
using SQRESULT = Int32;
using SQBool = UInt32;
using SQUnsignedInteger = UInt32;
using SQUserPointer = IntPtr;
using SQFloat = Single;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate SQInteger SQFUNCTION(HSQUIRRELVM v);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate SQInteger SQRELEASEHOOK(SQUserPointer ptr, SQInteger size);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SQCOMPILERERROR(HSQUIRRELVM v, string desc, string source, SQInteger line, SQInteger column);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SQPRINTFUNCTION(HSQUIRRELVM v, string str);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SQDEBUGHOOK(HSQUIRRELVM v, SQInteger type, string sourcename, SQInteger line, string funcname);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate SQInteger SQWRITEFUNC(SQUserPointer up, SQUserPointer tag, SQInteger idx);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate SQInteger SQREADFUNC(SQUserPointer up, SQUserPointer tag, SQInteger idx);
#else
public delegate SQInteger SQFUNCTION(HSQUIRRELVM v);
public delegate SQInteger SQRELEASEHOOK(SQUserPointer ptr, SQInteger size);
public delegate void SQCOMPILERERROR(HSQUIRRELVM v, string desc, string source, SQInteger line, SQInteger column);
public delegate void SQPRINTFUNCTION(HSQUIRRELVM v, string str);
public delegate void SQDEBUGHOOK(HSQUIRRELVM v, SQInteger type, string sourcename, SQInteger line, string funcname);
public delegate SQInteger SQWRITEFUNC(SQUserPointer up, SQUserPointer tag, SQInteger idx);
public delegate SQInteger SQREADFUNC(SQUserPointer up, SQUserPointer tag, SQInteger idx);
#endif
public class SquirrelDLL
{
public const SQBool SQFalse = 0;
public const SQBool SQTrue = 1;
#if UNITY_IPHONE && !UNITY_EDITOR
const string LUADLL = "__Internal";
#else
const string LUADLL = "squirrel";
#endif
public static bool SQ_FAILED(SQRESULT res) { return res < 0; }
public static bool SQ_SUCCEEDED(SQRESULT res) { return res >= 0; }
[Flags]
enum MaskValue
{
_RT_NULL = 0x00000001,
_RT_INTEGER = 0x00000002,
_RT_FLOAT = 0x00000004,
_RT_BOOL = 0x00000008,
_RT_STRING = 0x00000010,
_RT_TABLE = 0x00000020,
_RT_ARRAY = 0x00000040,
_RT_USERDATA = 0x00000080,
_RT_CLOSURE = 0x00000100,
_RT_NATIVECLOSURE = 0x00000200,
_RT_GENERATOR = 0x00000400,
_RT_USERPOINTER = 0x00000800,
_RT_THREAD = 0x00001000,
_RT_FUNCPROTO = 0x00002000,
_RT_CLASS = 0x00004000,
_RT_INSTANCE = 0x00008000,
_RT_WEAKREF = 0x00010000,
_RT_OUTER = 0x00020000,
SQOBJECT_REF_COUNTED = 0x08000000,
SQOBJECT_NUMERIC = 0x04000000,
SQOBJECT_DELEGABLE = 0x02000000,
SQOBJECT_CANBEFALSE = 0x01000000,
}
enum SQObjectType
{
OT_NULL = (MaskValue._RT_NULL | MaskValue.SQOBJECT_CANBEFALSE),
OT_INTEGER = (MaskValue._RT_INTEGER | MaskValue.SQOBJECT_NUMERIC | MaskValue.SQOBJECT_CANBEFALSE),
OT_FLOAT = (MaskValue._RT_FLOAT | MaskValue.SQOBJECT_NUMERIC | MaskValue.SQOBJECT_CANBEFALSE),
OT_BOOL = (MaskValue._RT_BOOL | MaskValue.SQOBJECT_CANBEFALSE),
OT_STRING = (MaskValue._RT_STRING | MaskValue.SQOBJECT_REF_COUNTED),
OT_TABLE = (MaskValue._RT_TABLE | MaskValue.SQOBJECT_REF_COUNTED | MaskValue.SQOBJECT_DELEGABLE),
OT_ARRAY = (MaskValue._RT_ARRAY | MaskValue.SQOBJECT_REF_COUNTED),
OT_USERDATA = (MaskValue._RT_USERDATA | MaskValue.SQOBJECT_REF_COUNTED | MaskValue.SQOBJECT_DELEGABLE),
OT_CLOSURE = (MaskValue._RT_CLOSURE | MaskValue.SQOBJECT_REF_COUNTED),
OT_NATIVECLOSURE = (MaskValue._RT_NATIVECLOSURE | MaskValue.SQOBJECT_REF_COUNTED),
OT_GENERATOR = (MaskValue._RT_GENERATOR | MaskValue.SQOBJECT_REF_COUNTED),
OT_USERPOINTER = MaskValue._RT_USERPOINTER,
OT_THREAD = (MaskValue._RT_THREAD | MaskValue.SQOBJECT_REF_COUNTED),
OT_FUNCPROTO = (MaskValue._RT_FUNCPROTO | MaskValue.SQOBJECT_REF_COUNTED), //internal usage only
OT_CLASS = (MaskValue._RT_CLASS | MaskValue.SQOBJECT_REF_COUNTED),
OT_INSTANCE = (MaskValue._RT_INSTANCE | MaskValue.SQOBJECT_REF_COUNTED | MaskValue.SQOBJECT_DELEGABLE),
OT_WEAKREF = (MaskValue._RT_WEAKREF | MaskValue.SQOBJECT_REF_COUNTED),
OT_OUTER = (MaskValue._RT_OUTER | MaskValue.SQOBJECT_REF_COUNTED) //internal usage only
}
// /*standard library*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sqstd_register_bloblib(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sqstd_register_iolib(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sqstd_register_systemlib(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sqstd_register_mathlib(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sqstd_register_stringlib(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sqstd_seterrorhandlers(HSQUIRRELVM v);
// /*vm*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern HSQUIRRELVM sq_open(SQInteger initialstacksize);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern HSQUIRRELVM sq_newthread(HSQUIRRELVM friendvm, SQInteger initialstacksize);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_seterrorhandler(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_close(HSQUIRRELVM v);
// SQUIRREL_API void sq_setforeignptr(HSQUIRRELVM v,SQUserPointer p);
// SQUIRREL_API SQUserPointer sq_getforeignptr(HSQUIRRELVM v);
// SQUIRREL_API void sq_setsharedforeignptr(HSQUIRRELVM v,SQUserPointer p);
// SQUIRREL_API SQUserPointer sq_getsharedforeignptr(HSQUIRRELVM v);
// SQUIRREL_API void sq_setvmreleasehook(HSQUIRRELVM v,SQRELEASEHOOK hook);
// SQUIRREL_API SQRELEASEHOOK sq_getvmreleasehook(HSQUIRRELVM v);
// SQUIRREL_API void sq_setsharedreleasehook(HSQUIRRELVM v,SQRELEASEHOOK hook);
// SQUIRREL_API SQRELEASEHOOK sq_getsharedreleasehook(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_setprintfunc(HSQUIRRELVM v, SQPRINTFUNCTION printfunc, SQPRINTFUNCTION errorfunc);
// SQUIRREL_API SQPRINTFUNCTION sq_getprintfunc(HSQUIRRELVM v);
// SQUIRREL_API SQPRINTFUNCTION sq_geterrorfunc(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_suspendvm(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_wakeupvm(HSQUIRRELVM v, SQBool resumedret, SQBool retval, SQBool raiseerror, SQBool throwerror);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQInteger sq_getvmstate(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQInteger sq_getversion();
// /*compiler*/
// SQUIRREL_API SQRESULT sq_compile(HSQUIRRELVM v,SQLEXREADFUNC read,SQUserPointer p,const SQChar *sourcename,SQBool raiseerror);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_compilebuffer(HSQUIRRELVM v, byte[] s, SQInteger size, string sourcename, SQBool raiseerror);
public static SQRESULT sq_compilebuffer(HSQUIRRELVM v, string s, string sourcename, SQBool raiseerror)
{
var bytes = Encoding.UTF8.GetBytes(s);
return sq_compilebuffer(v, bytes, bytes.Length, sourcename, raiseerror);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_enabledebuginfo(HSQUIRRELVM v, SQBool enable);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_notifyallexceptions(HSQUIRRELVM v, SQBool enable);
// SQUIRREL_API void sq_setcompilererrorhandler(HSQUIRRELVM v,SQCOMPILERERROR f);
// /*stack operations*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_push(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pop(HSQUIRRELVM v, SQInteger nelemstopop);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_poptop(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_remove(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQInteger sq_gettop(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_settop(HSQUIRRELVM v, SQInteger newtop);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_reservestack(HSQUIRRELVM v, SQInteger nsize);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQInteger sq_cmp(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_move(HSQUIRRELVM dest, HSQUIRRELVM src, SQInteger idx);
/*object creation handling*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQUserPointer sq_newuserdata(HSQUIRRELVM v, SQUnsignedInteger size);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_newtable(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_newtableex(HSQUIRRELVM v, SQInteger initialcapacity);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_newarray(HSQUIRRELVM v, SQInteger size);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_newclosure(HSQUIRRELVM v, IntPtr func, SQUnsignedInteger nfreevars);
public static void sq_newclosure(HSQUIRRELVM v, SQFUNCTION function, SQUnsignedInteger nfreevars)
{
IntPtr fn = Marshal.GetFunctionPointerForDelegate(function);
sq_newclosure(v, fn, nfreevars);
}
// SQUIRREL_API SQRESULT sq_setparamscheck(HSQUIRRELVM v,SQInteger nparamscheck,const SQChar *typemask);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_bindenv(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_setclosureroot(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getclosureroot(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushstring(HSQUIRRELVM v, byte[] s, SQInteger len);
public static void sq_pushstring(HSQUIRRELVM v, string s)
{
var bytes = Encoding.UTF8.GetBytes(s);
sq_pushstring(v, bytes, bytes.Length);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushfloat(HSQUIRRELVM v, SQFloat f);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushinteger(HSQUIRRELVM v, SQInteger n);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushbool(HSQUIRRELVM v, SQBool b);
// SQUIRREL_API void sq_pushuserpointer(HSQUIRRELVM v,SQUserPointer p);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushnull(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushthread(HSQUIRRELVM v, HSQUIRRELVM thread);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int sq_gettype(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_typeof(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQInteger sq_getsize(HSQUIRRELVM v, SQInteger idx);
// SQUIRREL_API SQHash sq_gethash(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getbase(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQBool sq_instanceof(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_tostring(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_tobool(HSQUIRRELVM v, SQInteger idx, out SQBool b);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getstring(HSQUIRRELVM v, SQInteger idx, out IntPtr c);
public static SQRESULT sq_getstring(HSQUIRRELVM v, SQInteger idx, out string c)
{
IntPtr ptr;
SQRESULT result;
if (SQ_SUCCEEDED(result = sq_getstring(v, idx, out ptr)))
{
c = Marshal.PtrToStringAnsi(ptr);
}
else
{
c = null;
}
return result;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getinteger(HSQUIRRELVM v, SQInteger idx, out SQInteger i);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getfloat(HSQUIRRELVM v, SQInteger idx, out SQFloat f);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getbool(HSQUIRRELVM v, SQInteger idx, out SQBool b);
// SQUIRREL_API SQRESULT sq_getthread(HSQUIRRELVM v,SQInteger idx,HSQUIRRELVM *thread);
// SQUIRREL_API SQRESULT sq_getuserpointer(HSQUIRRELVM v,SQInteger idx,SQUserPointer *p);
// SQUIRREL_API SQRESULT sq_getuserdata(HSQUIRRELVM v,SQInteger idx,SQUserPointer *p,SQUserPointer *typetag);
// SQUIRREL_API SQRESULT sq_settypetag(HSQUIRRELVM v,SQInteger idx,SQUserPointer typetag);
// SQUIRREL_API SQRESULT sq_gettypetag(HSQUIRRELVM v,SQInteger idx,SQUserPointer *typetag);
// SQUIRREL_API void sq_setreleasehook(HSQUIRRELVM v,SQInteger idx,SQRELEASEHOOK hook);
// SQUIRREL_API SQRELEASEHOOK sq_getreleasehook(HSQUIRRELVM v,SQInteger idx);
// SQUIRREL_API SQChar *sq_getscratchpad(HSQUIRRELVM v,SQInteger minsize);
// SQUIRREL_API SQRESULT sq_getfunctioninfo(HSQUIRRELVM v,SQInteger level,SQFunctionInfo *fi);
// SQUIRREL_API SQRESULT sq_getclosureinfo(HSQUIRRELVM v,SQInteger idx,SQUnsignedInteger *nparams,SQUnsignedInteger *nfreevars);
// SQUIRREL_API SQRESULT sq_getclosurename(HSQUIRRELVM v,SQInteger idx);
// SQUIRREL_API SQRESULT sq_setnativeclosurename(HSQUIRRELVM v,SQInteger idx,const SQChar *name);
// SQUIRREL_API SQRESULT sq_setinstanceup(HSQUIRRELVM v, SQInteger idx, SQUserPointer p);
// SQUIRREL_API SQRESULT sq_getinstanceup(HSQUIRRELVM v, SQInteger idx, SQUserPointer *p,SQUserPointer typetag);
// SQUIRREL_API SQRESULT sq_setclassudsize(HSQUIRRELVM v, SQInteger idx, SQInteger udsize);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_newclass(HSQUIRRELVM v, SQBool hasbase);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_createinstance(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_setattributes(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getattributes(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getclass(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_weakref(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getdefaultdelegate(HSQUIRRELVM v, int /*SQObjectType*/ t);
// SQUIRREL_API SQRESULT sq_getmemberhandle(HSQUIRRELVM v,SQInteger idx,HSQMEMBERHANDLE *handle);
// SQUIRREL_API SQRESULT sq_getbyhandle(HSQUIRRELVM v,SQInteger idx,const HSQMEMBERHANDLE *handle);
// SQUIRREL_API SQRESULT sq_setbyhandle(HSQUIRRELVM v,SQInteger idx,const HSQMEMBERHANDLE *handle);
// /*object manipulation*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushroottable(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushregistrytable(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_pushconsttable(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_setroottable(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_setconsttable(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_newslot(HSQUIRRELVM v, SQInteger idx, SQBool bstatic);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_deleteslot(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_set(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_get(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_rawget(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_rawset(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_rawdeleteslot(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_newmember(HSQUIRRELVM v, SQInteger idx, SQBool bstatic);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_rawnewmember(HSQUIRRELVM v, SQInteger idx, SQBool bstatic);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_arrayappend(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_arraypop(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_arrayresize(HSQUIRRELVM v, SQInteger idx, SQInteger newsize);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_arrayreverse(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_arrayremove(HSQUIRRELVM v, SQInteger idx, SQInteger itemidx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_arrayinsert(HSQUIRRELVM v, SQInteger idx, SQInteger destpos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_setdelegate(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getdelegate(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_clone(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_setfreevariable(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger nval);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_next(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getweakrefval(HSQUIRRELVM v, SQInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_clear(HSQUIRRELVM v, SQInteger idx);
// /*calls*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_call(HSQUIRRELVM v, SQInteger args, SQBool retval, SQBool raiseerror);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_resume(HSQUIRRELVM v, SQBool retval, SQBool raiseerror);
// SQUIRREL_API const SQChar *sq_getlocal(HSQUIRRELVM v,SQUnsignedInteger level,SQUnsignedInteger idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_getcallee(HSQUIRRELVM v);
// SQUIRREL_API const SQChar *sq_getfreevariable(HSQUIRRELVM v,SQInteger idx,SQUnsignedInteger nval);
// SQUIRREL_API SQRESULT sq_throwerror(HSQUIRRELVM v,const SQChar *err);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_throwobject(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_reseterror(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_getlasterror(HSQUIRRELVM v);
// /*raw object handling*/
// SQUIRREL_API SQRESULT sq_getstackobj(HSQUIRRELVM v,SQInteger idx,HSQOBJECT *po);
// SQUIRREL_API void sq_pushobject(HSQUIRRELVM v,HSQOBJECT obj);
// SQUIRREL_API void sq_addref(HSQUIRRELVM v,HSQOBJECT *po);
// SQUIRREL_API SQBool sq_release(HSQUIRRELVM v,HSQOBJECT *po);
// SQUIRREL_API SQUnsignedInteger sq_getrefcount(HSQUIRRELVM v,HSQOBJECT *po);
// SQUIRREL_API void sq_resetobject(HSQOBJECT *po);
// SQUIRREL_API const SQChar *sq_objtostring(const HSQOBJECT *o);
// SQUIRREL_API SQBool sq_objtobool(const HSQOBJECT *o);
// SQUIRREL_API SQInteger sq_objtointeger(const HSQOBJECT *o);
// SQUIRREL_API SQFloat sq_objtofloat(const HSQOBJECT *o);
// SQUIRREL_API SQUserPointer sq_objtouserpointer(const HSQOBJECT *o);
// SQUIRREL_API SQRESULT sq_getobjtypetag(const HSQOBJECT *o,SQUserPointer * typetag);
// SQUIRREL_API SQUnsignedInteger sq_getvmrefcount(HSQUIRRELVM v, const HSQOBJECT *po);
// /*GC*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQInteger sq_collectgarbage(HSQUIRRELVM v);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern SQRESULT sq_resurrectunreachable(HSQUIRRELVM v);
// /*serialization*/
// SQUIRREL_API SQRESULT sq_writeclosure(HSQUIRRELVM vm,SQWRITEFUNC writef,SQUserPointer up);
// SQUIRREL_API SQRESULT sq_readclosure(HSQUIRRELVM vm,SQREADFUNC readf,SQUserPointer up);
// /*mem allocation*/
// SQUIRREL_API void *sq_malloc(SQUnsignedInteger size);
// SQUIRREL_API void *sq_realloc(void* p,SQUnsignedInteger oldsize,SQUnsignedInteger newsize);
// SQUIRREL_API void sq_free(void *p,SQUnsignedInteger size);
// /*debug*/
// SQUIRREL_API SQRESULT sq_stackinfos(HSQUIRRELVM v,SQInteger level,SQStackInfos *si);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void sq_setdebughook(HSQUIRRELVM v);
// SQUIRREL_API void sq_setnativedebughook(HSQUIRRELVM v,SQDEBUGHOOK hook);
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/8/2008 7:36:02 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
namespace DotSpatial.Data
{
/// <summary>
/// A list that also includes several events during its existing activities.
/// List is fussy about inheritance, unfortunately, so this wraps a list
/// and then makes this class much more inheritable
/// </summary>
public class ChangeEventList<T> : CopyList<T>, IChangeEventList<T> where T : class, IChangeItem
{
#region Events
/// <summary>
/// This event is for when it is necessary to do something if any of the internal
/// members changes. It will also forward the original item calling the message.
/// </summary>
public event EventHandler ItemChanged;
/// <summary>
/// Occurs when this list should be removed from its container
/// </summary>
public event EventHandler RemoveItem;
#endregion
#region variables
private bool _hasChanged;
private int _suspension;
#endregion
#region Constructors
#endregion
#region Methods
#region Add
/// <summary>
/// Adds the elements of the specified collection to the end of the System.Collections.Generic.List<T>
/// </summary>
/// <param name="collection">collection: The collection whose elements should be added to the end of the
/// System.Collections.Generic.List<T>. The collection itself cannot be null, but it can contain elements that are null,
/// if type T is a reference type.</param>
/// <exception cref="System.ApplicationException">Unable to add while the ReadOnly property is set to true.</exception>
public virtual void AddRange(IEnumerable<T> collection)
{
SuspendEvents();
foreach (T item in collection)
{
Add(item);
}
ResumeEvents();
}
#endregion
/// <summary>
/// Resumes event sending and fires a ListChanged event if any changes have taken place.
/// This will not track all the individual changes that may have fired in the meantime.
/// </summary>
public void ResumeEvents()
{
_suspension--;
if (_suspension == 0)
{
OnResumeEvents();
if (_hasChanged)
{
OnListChanged();
}
}
if (_suspension < 0) _suspension = 0;
}
/// <summary>
/// Temporarilly suspends notice events, allowing a large number of changes.
/// </summary>
public void SuspendEvents()
{
if (_suspension == 0) _hasChanged = false;
_suspension++;
}
/// <summary>
/// An overriding event handler so that we can signfiy the list has changed
/// when the inner list has been set to a new list.
/// </summary>
protected override void OnInnerListSet()
{
OnItemChanged(this);
}
/// <summary>
/// Overrides the normal clear situation so that we only update after all the members are cleared.
/// </summary>
protected override void OnClear()
{
SuspendEvents();
base.OnClear();
ResumeEvents();
}
/// <summary>
/// Occurs during the copy process and overrides the base behavior so that events are suspended.
/// </summary>
/// <param name="copy"></param>
protected override void OnCopy(CopyList<T> copy)
{
ChangeEventList<T> myCopy = copy as ChangeEventList<T>;
if (myCopy != null)
{
RemoveHandlers(myCopy);
myCopy.SuspendEvents();
}
base.OnCopy(copy);
if (myCopy != null) myCopy.ResumeEvents();
}
private static void RemoveHandlers(ChangeEventList<T> myCopy)
{
if (myCopy.ItemChanged != null)
{
foreach (var handler in myCopy.ItemChanged.GetInvocationList())
{
myCopy.ItemChanged -= (EventHandler)handler;
}
}
if (myCopy.RemoveItem != null)
{
foreach (var handler in myCopy.RemoveItem.GetInvocationList())
{
myCopy.RemoveItem -= (EventHandler)handler;
}
}
}
/// <summary>
/// Occurs when ResumeEvents has been called enough times so that events are re-enabled.
/// </summary>
protected virtual void OnResumeEvents()
{
}
#region Reverse
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
/// <exception cref="System.ArgumentException">index and count do not denote a valid range of elements in the EventList<T>.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-count is less than 0.</exception>
/// <exception cref="System.ApplicationException">Unable to reverse while the ReadOnly property is set to true.</exception>
public virtual void Reverse(int index, int count)
{
InnerList.Reverse(index, count);
OnListChanged();
}
/// <summary>
/// Reverses the order of the elements in the entire EventList<T>.
/// </summary>
/// <exception cref="System.ApplicationException">Unable to reverse while the ReadOnly property is set to true.</exception>
public virtual void Reverse()
{
InnerList.Reverse();
OnListChanged();
}
#endregion
#region Insert
/// <summary>
/// Inserts the elements of a collection into the EventList<T> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which the new elements should be inserted.</param>
/// <param name="collection">The collection whose elements should be inserted into the EventList<T>. The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-index is greater than EventList<T>.Count.</exception>
/// <exception cref="System.ArgumentNullException">collection is null.</exception>
/// <exception cref="System.ApplicationException">Unable to insert while the ReadOnly property is set to true.</exception>
public virtual void InsertRange(int index, IEnumerable<T> collection)
{
int c = index;
SuspendEvents();
foreach (T item in collection)
{
Include(item);
InnerList.Insert(c, item);
c++;
}
ResumeEvents();
}
#endregion
#region Remove
/// <summary>
/// Removes a range of elements from the EventList<T>.
/// </summary>
/// <param name="index">The zero-based starting index of the range of elements to remove.</param>
/// <param name="count">The number of elements to remove.</param>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-count is less than 0.</exception>
/// <exception cref="System.ArgumentException">index and count do not denote a valid range of elements in the EventList<T>.</exception>
/// <exception cref="System.ApplicationException">Unable to remove while the ReadOnly property is set to true.</exception>
public virtual void RemoveRange(int index, int count)
{
T[] temp = new T[count];
InnerList.CopyTo(index, temp, 0, count);
InnerList.RemoveRange(index, count);
SuspendEvents();
foreach (T item in temp)
{
Exclude(item);
}
ResumeEvents();
}
#endregion
#region BinarySearch
/// <summary>
/// Searches the entire sorted System.Collections.Generic.List<T> for an element using the default comparer and returns the zero-based index of the element.
/// </summary>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <returns>The zero-based index of item in the sorted System.Collections.Generic.List<T>, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of System.Collections.Generic.List<T>.Count.</returns>
/// <exception cref="System.InvalidOperationException">The default comparer System.Collections.Generic.Comparer<T>.Default cannot find an implementation of the System.IComparable<T> generic interface or the System.IComparable interface for type T.</exception>
public virtual int BinarySearch(T item)
{
return InnerList.BinarySearch(item);
}
#endregion
#endregion
#region Properties
/// <summary>
/// Gets whether or not the list is currently suspended
/// </summary>
public bool EventsSuspended
{
get
{
return (_suspension > 0);
}
}
#endregion
#region Event Handlers
/// <summary>
/// This is a notification that characteristics of one of the members of the list may have changed,
/// requiring a refresh, but may not involve a change to the the list itself
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemItemChanged(object sender, EventArgs e)
{
OnItemChanged(sender);
}
/// <summary>
/// Occurs when the item is changed. If this list is not suspended, it will forward the change event
/// on. Otherwise, it will ensure that when resume events is called that the on change method
/// is fired at that time.
/// </summary>
/// <param name="sender"></param>
protected virtual void OnItemChanged(object sender)
{
if (EventsSuspended)
{
_hasChanged = true;
}
else
{
if (ItemChanged != null) ItemChanged(sender, EventArgs.Empty);
}
}
private void ItemRemoveItem(object sender, EventArgs e)
{
Remove((T)sender);
OnListChanged();
}
#endregion
#region Protected Methods
/// <summary>
/// Fires the ListChanged Event
/// </summary>
protected virtual void OnListChanged()
{
if (EventsSuspended == false)
{
if (ItemChanged != null)
{
// activate this remarked code to test if the handlers are getting copied somewhere.
//int count = ItemChanged.GetInvocationList().Length;
//if (count > 1) Debug.WriteLine(this + " has " + count + " item changed handlers.");
ItemChanged(this, EventArgs.Empty);
}
}
else
{
_hasChanged = true;
}
}
/// <summary>
/// This is either a layer collection or a colorbreak collection, and so
/// this won't be called by us, but someone might want to override this for their own reasons.
/// </summary>
protected virtual void OnRemoveItem()
{
if (RemoveItem != null) RemoveItem(this, EventArgs.Empty);
}
#endregion
#region Protected Methods
/// <summary>
/// Occurs when wiring events on a new item
/// </summary>
/// <param name="item"></param>
protected override void OnInclude(T item)
{
item.ItemChanged += ItemItemChanged;
item.RemoveItem += ItemRemoveItem;
OnListChanged();
}
/// <summary>
/// Occurs when unwiring events on new items
/// </summary>
/// <param name="item"></param>
protected override void OnExclude(T item)
{
item.ItemChanged -= ItemItemChanged;
item.RemoveItem -= ItemRemoveItem;
OnListChanged();
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Sync.V1.Service.SyncMap
{
/// <summary>
/// FetchSyncMapItemOptions
/// </summary>
public class FetchSyncMapItemOptions : IOptions<SyncMapItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Sync Map Item resource to fetch
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync Map with the Sync Map Item resource to fetch
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// The key value of the Sync Map Item resource to fetch
/// </summary>
public string PathKey { get; }
/// <summary>
/// Construct a new FetchSyncMapItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Item resource to fetch </param>
/// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Item resource to fetch </param>
/// <param name="pathKey"> The key value of the Sync Map Item resource to fetch </param>
public FetchSyncMapItemOptions(string pathServiceSid, string pathMapSid, string pathKey)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
PathKey = pathKey;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// DeleteSyncMapItemOptions
/// </summary>
public class DeleteSyncMapItemOptions : IOptions<SyncMapItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Sync Map Item resource to delete
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync Map with the Sync Map Item resource to delete
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// The key value of the Sync Map Item resource to delete
/// </summary>
public string PathKey { get; }
/// <summary>
/// The If-Match HTTP request header
/// </summary>
public string IfMatch { get; set; }
/// <summary>
/// Construct a new DeleteSyncMapItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Item resource to delete </param>
/// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Item resource to delete </param>
/// <param name="pathKey"> The key value of the Sync Map Item resource to delete </param>
public DeleteSyncMapItemOptions(string pathServiceSid, string pathMapSid, string pathKey)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
PathKey = pathKey;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (IfMatch != null)
{
p.Add(new KeyValuePair<string, string>("If-Match", IfMatch));
}
return p;
}
}
/// <summary>
/// CreateSyncMapItemOptions
/// </summary>
public class CreateSyncMapItemOptions : IOptions<SyncMapItemResource>
{
/// <summary>
/// The SID of the Sync Service to create the Map Item in
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync Map to add the new Map Item to
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// The unique, user-defined key for the Map Item
/// </summary>
public string Key { get; }
/// <summary>
/// A JSON string that represents an arbitrary, schema-less object that the Map Item stores
/// </summary>
public object Data { get; }
/// <summary>
/// An alias for item_ttl
/// </summary>
public int? Ttl { get; set; }
/// <summary>
/// How long, in seconds, before the Map Item expires
/// </summary>
public int? ItemTtl { get; set; }
/// <summary>
/// How long, in seconds, before the Map Item's parent Sync Map expires and is deleted
/// </summary>
public int? CollectionTtl { get; set; }
/// <summary>
/// Construct a new CreateSyncMapItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service to create the Map Item in </param>
/// <param name="pathMapSid"> The SID of the Sync Map to add the new Map Item to </param>
/// <param name="key"> The unique, user-defined key for the Map Item </param>
/// <param name="data"> A JSON string that represents an arbitrary, schema-less object that the Map Item stores </param>
public CreateSyncMapItemOptions(string pathServiceSid, string pathMapSid, string key, object data)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
Key = key;
Data = data;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Key != null)
{
p.Add(new KeyValuePair<string, string>("Key", Key));
}
if (Data != null)
{
p.Add(new KeyValuePair<string, string>("Data", Serializers.JsonObject(Data)));
}
if (Ttl != null)
{
p.Add(new KeyValuePair<string, string>("Ttl", Ttl.ToString()));
}
if (ItemTtl != null)
{
p.Add(new KeyValuePair<string, string>("ItemTtl", ItemTtl.ToString()));
}
if (CollectionTtl != null)
{
p.Add(new KeyValuePair<string, string>("CollectionTtl", CollectionTtl.ToString()));
}
return p;
}
}
/// <summary>
/// ReadSyncMapItemOptions
/// </summary>
public class ReadSyncMapItemOptions : ReadOptions<SyncMapItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Map Item resources to read
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync Map with the Sync Map Item resource to fetch
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// How to order the Map Items returned by their key value
/// </summary>
public SyncMapItemResource.QueryResultOrderEnum Order { get; set; }
/// <summary>
/// The index of the first Sync Map Item resource to read
/// </summary>
public string From { get; set; }
/// <summary>
/// Whether to include the Map Item referenced by the from parameter
/// </summary>
public SyncMapItemResource.QueryFromBoundTypeEnum Bounds { get; set; }
/// <summary>
/// Construct a new ReadSyncMapItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Map Item resources to read </param>
/// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Item resource to fetch </param>
public ReadSyncMapItemOptions(string pathServiceSid, string pathMapSid)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Order != null)
{
p.Add(new KeyValuePair<string, string>("Order", Order.ToString()));
}
if (From != null)
{
p.Add(new KeyValuePair<string, string>("From", From));
}
if (Bounds != null)
{
p.Add(new KeyValuePair<string, string>("Bounds", Bounds.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// UpdateSyncMapItemOptions
/// </summary>
public class UpdateSyncMapItemOptions : IOptions<SyncMapItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Sync Map Item resource to update
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync Map with the Sync Map Item resource to update
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// The key value of the Sync Map Item resource to update
/// </summary>
public string PathKey { get; }
/// <summary>
/// A JSON string that represents an arbitrary, schema-less object that the Map Item stores
/// </summary>
public object Data { get; set; }
/// <summary>
/// An alias for item_ttl
/// </summary>
public int? Ttl { get; set; }
/// <summary>
/// How long, in seconds, before the Map Item expires
/// </summary>
public int? ItemTtl { get; set; }
/// <summary>
/// How long, in seconds, before the Map Item's parent Sync Map expires and is deleted
/// </summary>
public int? CollectionTtl { get; set; }
/// <summary>
/// The If-Match HTTP request header
/// </summary>
public string IfMatch { get; set; }
/// <summary>
/// Construct a new UpdateSyncMapItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Item resource to update </param>
/// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Item resource to update </param>
/// <param name="pathKey"> The key value of the Sync Map Item resource to update </param>
public UpdateSyncMapItemOptions(string pathServiceSid, string pathMapSid, string pathKey)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
PathKey = pathKey;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Data != null)
{
p.Add(new KeyValuePair<string, string>("Data", Serializers.JsonObject(Data)));
}
if (Ttl != null)
{
p.Add(new KeyValuePair<string, string>("Ttl", Ttl.ToString()));
}
if (ItemTtl != null)
{
p.Add(new KeyValuePair<string, string>("ItemTtl", ItemTtl.ToString()));
}
if (CollectionTtl != null)
{
p.Add(new KeyValuePair<string, string>("CollectionTtl", CollectionTtl.ToString()));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (IfMatch != null)
{
p.Add(new KeyValuePair<string, string>("If-Match", IfMatch));
}
return p;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using FluentNHibernate.Automapping.TestFixtures.SuperTypes;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Mapping;
using FluentNHibernate.Utils;
using NUnit.Framework;
namespace FluentNHibernate.Testing.DomainModel.Mapping
{
[TestFixture]
public class IdentityPartTester
{
[Test]
public void Defaults()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping => mapping.Id(x => x.IntId))
.Element("class/id")
.Exists()
.HasAttribute("name", "IntId")
.HasAttribute("type", typeof(int).AssemblyQualifiedName)
.Element("class/id/generator")
.Exists()
.HasAttribute("class", "identity")
.Element("class/id/column")
.Exists()
.HasAttribute("name", "IntId");
}
[Test]
public void IdIsAlwaysFirstElementInClass()
{
new MappingTester<IdentityTarget>()
.ForMapping(m =>
{
m.Map(x => x.StringId); // just a property in this case
m.Id(x => x.IntId);
})
.Element("class/*[1]").HasName("id");
}
[Test]
public void ColumnName_SpecifyColumnName()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping => mapping.Id(x => x.IntId, "Id"))
.Element("class/id/column").HasAttribute("name", "Id");
}
[Test]
public void ColumnName_SpecifyFluently()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping => mapping.Id(x => x.IntId).Column("Id"))
.Element("class/id/column").HasAttribute("name", "Id");
}
[Test]
public void GeneratorClass_Long_DefaultsToIdentity()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping => mapping.Id(x => x.LongId))
.Element("class/id").HasAttribute("type", typeof(Int64).AssemblyQualifiedName)
.Element("class/id/generator").HasAttribute("class", "identity");
}
[Test]
public void GeneratorClass_Guid_DefaultsToGuidComb()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping => mapping.Id(x => x.GuidId))
.Element("class/id").HasAttribute("type", typeof(Guid).AssemblyQualifiedName)
.Element("class/id/generator").HasAttribute("class", "guid.comb");
}
[Test]
public void GeneratorClass_String_DefaultsToAssigned()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping => mapping.Id(x => x.StringId))
.Element("class/id").HasAttribute("type", typeof(String).AssemblyQualifiedName)
.Element("class/id/generator").HasAttribute("class", "assigned");
}
[Test]
public void GeneratorClass_CanSpecifyIncrement()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.Increment())
.Element("class/id/generator").HasAttribute("class", "increment");
}
[Test]
public void GeneratorClass_CanSpecifyIdentity()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.Identity())
.Element("class/id/generator").HasAttribute("class", "identity");
}
[Test]
public void GeneratorClass_CanSpecifySequence()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.Sequence("uid_sequence"))
.Element("class/id/generator").HasAttribute("class", "sequence")
.Element("class/id/generator/param")
.Exists()
.HasAttribute("name", "sequence")
.ValueEquals("uid_sequence");
}
[Test]
public void GeneratorClass_CanSpecifyHiLo()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.HiLo("hi_value", "next_value", "100"))
.Element("class/id/generator").HasAttribute("class", "hilo")
.Element("class/id/generator/param[1]")
.Exists()
.HasAttribute("name", "table")
.ValueEquals("hi_value")
.Element("class/id/generator/param[2]")
.Exists()
.HasAttribute("name", "column")
.ValueEquals("next_value")
.Element("class/id/generator/param[3]")
.Exists()
.HasAttribute("name", "max_lo")
.ValueEquals("100");
}
[Test]
public void GeneratorClass_CanSpecifySeqHiLo()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.SeqHiLo("hi_value", "100"))
.Element("class/id/generator").HasAttribute("class", "seqhilo")
.Element("class/id/generator/param[1]")
.Exists()
.HasAttribute("name", "sequence")
.ValueEquals("hi_value")
.Element("class/id/generator/param[2]")
.Exists()
.HasAttribute("name", "max_lo")
.ValueEquals("100");
}
[Test]
public void GeneratorClass_CanSpecifyUuidHex()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.StringId)
.GeneratedBy.UuidHex("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
.Element("class/id/generator").HasAttribute("class", "uuid.hex")
.Element("class/id/generator/param")
.Exists()
.HasAttribute("name", "format")
.ValueEquals("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
[Test]
public void GeneratorClass_CanSpecifyUuidString()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.StringId)
.GeneratedBy.UuidString())
.Element("class/id/generator").HasAttribute("class", "uuid.string");
}
[Test]
public void GeneratorClass_CanSpecifyGuid()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.GuidId)
.GeneratedBy.Guid())
.Element("class/id/generator").HasAttribute("class", "guid");
}
[Test]
public void GeneratorClass_CanSpecifyGuidComb()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.GuidId)
.GeneratedBy.GuidComb())
.Element("class/id/generator").HasAttribute("class", "guid.comb");
}
[Test]
public void GeneratorClass_CanSpecifyNative()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.Native())
.Element("class/id/generator").HasAttribute("class", "native");
}
[Test]
public void GeneratorClass_CanSpecifyAssigned()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.GuidId)
.GeneratedBy.Assigned())
.Element("class/id/generator").HasAttribute("class", "assigned");
}
[Test]
public void GeneratorClass_CanSpecifyForeign()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy
.Foreign("Parent"))
.Element("class/id/generator").HasAttribute("class", "foreign")
.Element("class/id/generator/param")
.Exists()
.HasAttribute("name", "property")
.ValueEquals("Parent");
}
[Test]
public void GeneratorClass_CanSpecifyNativeWithSequence()
{
new MappingTester<IdentityTarget>()
.ForMapping(mapping =>
mapping.Id(x => x.IntId)
.GeneratedBy.Native("seq"))
.Element("class/id/generator")
.HasAttribute("class", "native")
.Element("class/id/generator/param[@name='sequence']")
.ValueEquals("seq");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeIntegral_ForIncrement()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.GuidId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.Increment();
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeIntegral_ForIdentity()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.GuidId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.Identity();
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeIntegral_ForSequence()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.GuidId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.Sequence("no");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeIntegral_ForHiLo()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.GuidId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.HiLo("no", "no", "no");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeIntegral_ForSeqHiLo()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.GuidId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.SeqHiLo("no", "no");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeString_ForUuidHex()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.IntId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.UuidHex("format");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeString_ForUuidString()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.IntId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.UuidString();
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeGuid_ForGuid()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.IntId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.Guid();
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeGuid_ForGuidComb()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.IntId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.GuidComb();
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void IdentityType_MustBeIntegral_ForNative()
{
PropertyInfo property = ReflectionHelper.GetProperty<IdentityTarget>(x => x.GuidId);
new IdentityPart(typeof(IdentityTarget), property).GeneratedBy.Native();
}
[Test]
public void WithUnsavedValue_SetsUnsavedValueAttributeOnId()
{
new MappingTester<IdentityTarget>()
.ForMapping(c => c.Id(x => x.IntId).UnsavedValue(-1))
.Element("class/id").HasAttribute("unsaved-value", "-1");
}
[Test]
public void UnsavedValueAttributeIsntSetIfThereHasntBeenAValueSpecified()
{
new MappingTester<IdentityTarget>()
.ForMapping(c => c.Id(x => x.IntId))
.Element("class/id").DoesntHaveAttribute("unsaved-value");
}
[Test]
public void TypeIsSetToTypeName()
{
new MappingTester<IdentityTarget>()
.ForMapping(c => c.Id(x => x.IntId).UnsavedValue(-1))
.Element("class/id").HasAttribute("type", typeof(int).AssemblyQualifiedName);
}
[Test]
public void TypeIsSetToFullTypeNameIfTypeGeneric()
{
new MappingTester<IdentityTarget>()
.ForMapping(c => c.Id(x => x.NullableGuidId).UnsavedValue(-1))
.Element("class/id").HasAttribute("type", typeof(Guid?).AssemblyQualifiedName);
}
[Test]
public void AppliesConventions()
{
new MappingTester<IdentityTarget>()
.Conventions(conventions => conventions.Add(new TestIdConvention()))
.ForMapping(map => map.Id(x => x.LongId))
.Element("class/id").HasAttribute("access", "field");
}
private class TestIdConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
instance.Access.Field();
}
}
}
public class IdentityTarget
{
public virtual int IntId { get; set; }
public virtual long LongId { get; set; }
public virtual Guid GuidId { get; set; }
public virtual Guid? NullableGuidId { get; set; }
public virtual string StringId { get; set; }
}
}
| |
#region namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Configuration;
using Umbraco.Core;
using Umbraco.Core.Models;
using umbraco.BusinessLogic;
using System.Security.Cryptography;
using System.Web.Util;
using System.Collections.Specialized;
using System.Configuration.Provider;
using umbraco.cms.businesslogic;
using System.Security;
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using Member = umbraco.cms.businesslogic.member.Member;
using MemberType = umbraco.cms.businesslogic.member.MemberType;
using Umbraco.Core.Models.Membership;
using User = umbraco.BusinessLogic.User;
#endregion
namespace umbraco.providers.members
{
/// <summary>
/// Custom Membership Provider for Umbraco Members (User authentication for Frontend applications NOT umbraco CMS)
/// </summary>
public class UmbracoMembershipProvider : MembershipProvider
{
#region Fields
private string m_ApplicationName;
private bool m_EnablePasswordReset;
private bool m_EnablePasswordRetrieval;
private int m_MaxInvalidPasswordAttempts;
private int m_MinRequiredNonAlphanumericCharacters;
private int m_MinRequiredPasswordLength;
private int m_PasswordAttemptWindow;
private MembershipPasswordFormat m_PasswordFormat;
private string m_PasswordStrengthRegularExpression;
private bool m_RequiresQuestionAndAnswer;
private bool m_RequiresUniqueEmail;
private string m_DefaultMemberTypeAlias;
private string m_LockPropertyTypeAlias;
private string m_FailedPasswordAttemptsPropertyTypeAlias;
private string m_ApprovedPropertyTypeAlias;
private string m_CommentPropertyTypeAlias;
private string m_LastLoginPropertyTypeAlias;
private string m_PasswordRetrievalQuestionPropertyTypeAlias;
private string m_PasswordRetrievalAnswerPropertyTypeAlias;
private string m_providerName = Member.UmbracoMemberProviderName;
#endregion
#region Properties
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
/// <value></value>
/// <returns>The name of the application using the custom membership provider.</returns>
public override string ApplicationName
{
get
{
return m_ApplicationName;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ProviderException("ApplicationName cannot be empty.");
if (value.Length > 0x100)
throw new ProviderException("Provider application name too long.");
m_ApplicationName = value;
}
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to reset their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns>
public override bool EnablePasswordReset
{
get { return m_EnablePasswordReset; }
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to retrieve their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns>
public override bool EnablePasswordRetrieval
{
get { return m_EnablePasswordRetrieval; }
}
/// <summary>
/// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns>
public override int MaxInvalidPasswordAttempts
{
get { return m_MaxInvalidPasswordAttempts; }
}
/// <summary>
/// Gets the minimum number of special characters that must be present in a valid password.
/// </summary>
/// <value></value>
/// <returns>The minimum number of special characters that must be present in a valid password.</returns>
public override int MinRequiredNonAlphanumericCharacters
{
get { return m_MinRequiredNonAlphanumericCharacters; }
}
/// <summary>
/// Gets the minimum length required for a password.
/// </summary>
/// <value></value>
/// <returns>The minimum length required for a password. </returns>
public override int MinRequiredPasswordLength
{
get { return m_MinRequiredPasswordLength; }
}
/// <summary>
/// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns>
public override int PasswordAttemptWindow
{
get { return m_PasswordAttemptWindow; }
}
/// <summary>
/// Gets a value indicating the format for storing passwords in the membership data store.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns>
public override MembershipPasswordFormat PasswordFormat
{
get { return m_PasswordFormat; }
}
/// <summary>
/// Gets the regular expression used to evaluate a password.
/// </summary>
/// <value></value>
/// <returns>A regular expression used to evaluate a password.</returns>
public override string PasswordStrengthRegularExpression
{
get { return m_PasswordStrengthRegularExpression; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
/// </summary>
/// <value></value>
/// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns>
public override bool RequiresQuestionAndAnswer
{
get { return m_RequiresQuestionAndAnswer; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns>
public override bool RequiresUniqueEmail
{
get { return m_RequiresUniqueEmail; }
}
#endregion
#region Initialization Method
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call
/// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider
/// has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config)
{
// Intialize values from web.config
if (config == null) throw new ArgumentNullException("config");
if (string.IsNullOrEmpty(name)) name = "UmbracoMembershipProvider";
// Initialize base provider class
base.Initialize(name, config);
m_providerName = name;
this.m_EnablePasswordRetrieval = SecUtility.GetBooleanValue(config, "enablePasswordRetrieval", false);
this.m_EnablePasswordReset = SecUtility.GetBooleanValue(config, "enablePasswordReset", false);
this.m_RequiresQuestionAndAnswer = SecUtility.GetBooleanValue(config, "requiresQuestionAndAnswer", false);
this.m_RequiresUniqueEmail = SecUtility.GetBooleanValue(config, "requiresUniqueEmail", true);
this.m_MaxInvalidPasswordAttempts = SecUtility.GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
this.m_PasswordAttemptWindow = SecUtility.GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
this.m_MinRequiredPasswordLength = SecUtility.GetIntValue(config, "minRequiredPasswordLength", 7, true, 0x80);
this.m_MinRequiredNonAlphanumericCharacters = SecUtility.GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 0x80);
this.m_PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
this.m_ApplicationName = config["applicationName"];
if (string.IsNullOrEmpty(this.m_ApplicationName))
this.m_ApplicationName = SecUtility.GetDefaultAppName();
// make sure password format is clear by default.
string str = config["passwordFormat"];
if (str == null) str = "Clear";
switch (str.ToLower())
{
case "clear":
this.m_PasswordFormat = MembershipPasswordFormat.Clear;
break;
case "encrypted":
this.m_PasswordFormat = MembershipPasswordFormat.Encrypted;
break;
case "hashed":
this.m_PasswordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Provider bad password format");
}
if ((this.PasswordFormat == MembershipPasswordFormat.Hashed) && this.EnablePasswordRetrieval)
throw new ProviderException("Provider can not retrieve hashed password");
// test for membertype (if not specified, choose the first member type available)
if (config["defaultMemberTypeAlias"] != null)
m_DefaultMemberTypeAlias = config["defaultMemberTypeAlias"];
else if (MemberType.GetAll.Length == 1)
m_DefaultMemberTypeAlias = MemberType.GetAll[0].Alias;
else
throw new ProviderException("No default MemberType alias is specified in the web.config string. Please add a 'defaultMemberTypeAlias' to the add element in the provider declaration in web.config");
// test for approve status
if (config["umbracoApprovePropertyTypeAlias"] != null)
{
m_ApprovedPropertyTypeAlias = config["umbracoApprovePropertyTypeAlias"];
}
// test for lock attempts
if (config["umbracoLockPropertyTypeAlias"] != null)
{
m_LockPropertyTypeAlias = config["umbracoLockPropertyTypeAlias"];
}
if (config["umbracoFailedPasswordAttemptsPropertyTypeAlias"] != null)
{
m_FailedPasswordAttemptsPropertyTypeAlias = config["umbracoFailedPasswordAttemptsPropertyTypeAlias"];
}
// comment property
if (config["umbracoCommentPropertyTypeAlias"] != null)
{
m_CommentPropertyTypeAlias = config["umbracoCommentPropertyTypeAlias"];
}
// last login date
if (config["umbracoLastLoginPropertyTypeAlias"] != null)
{
m_LastLoginPropertyTypeAlias = config["umbracoLastLoginPropertyTypeAlias"];
}
// password retrieval
if (config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"] != null)
{
m_PasswordRetrievalQuestionPropertyTypeAlias = config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"];
}
if (config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"] != null)
{
m_PasswordRetrievalAnswerPropertyTypeAlias = config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"];
}
}
#endregion
#region Methods
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">The current password for the specified user.</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
// in order to support updating passwords from the umbraco core, we can't validate the old password
Member m = Member.GetMemberFromLoginNameAndPassword(username, oldPassword);
if (m == null) return false;
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, false);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
throw args.FailureInformation;
else
throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
}
string encodedPassword = EncodePassword(newPassword);
m.ChangePassword(encodedPassword);
return (m.Password == encodedPassword) ? true : false;
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias) && !String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
if (ValidateUser(username, password))
{
Member m = Member.GetMemberFromLoginName(username);
if (m != null)
{
UpdateMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, newPasswordQuestion);
UpdateMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, newPasswordAnswer);
m.Save();
return true;
}
else
{
throw new MembershipPasswordException("The supplied user is not found!");
}
}
else {
throw new MembershipPasswordException("Invalid user/password combo");
}
}
else
{
throw new NotSupportedException("Updating the password Question and Answer is not valid if the properties aren't set in the config file");
}
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="memberTypeAlias"></param>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
public MembershipUser CreateUser(string memberTypeAlias, string username, string password, string email, string passwordQuestion,
string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
if (Member.GetMemberFromLoginName(username) != null)
status = MembershipCreateStatus.DuplicateUserName;
else if (Member.GetMemberFromEmail(email) != null && RequiresUniqueEmail)
status = MembershipCreateStatus.DuplicateEmail;
else
{
var memberType = MemberType.GetByAlias(memberTypeAlias);
if (memberType == null)
{
throw new InvalidOperationException("Could not find a member type with alias " + memberTypeAlias + ". Ensure your membership provider configuration is up to date and that the default member type exists.");
}
Member m = Member.MakeNew(username, email, memberType, User.GetUser(0));
m.Password = password;
MembershipUser mUser =
ConvertToMembershipUser(m);
// custom fields
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias))
UpdateMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, passwordQuestion);
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
UpdateMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, passwordAnswer);
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
UpdateMemberProperty(m, m_ApprovedPropertyTypeAlias, isApproved);
if (!String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
mUser.LastActivityDate = DateTime.Now;
UpdateMemberProperty(m, m_LastLoginPropertyTypeAlias, mUser.LastActivityDate);
}
// save
m.Save();
status = MembershipCreateStatus.Success;
return mUser;
}
return null;
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion,
string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
return CreateUser(m_DefaultMemberTypeAlias, username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);
}
/// <summary>
/// Removes a user from the membership data source.
/// </summary>
/// <param name="username">The name of the user to delete.</param>
/// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
/// <returns>
/// true if the user was successfully deleted; otherwise, false.
/// </returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
Member m = Member.GetMemberFromLoginName(username);
if (m == null) return false;
else
{
m.delete();
return true;
}
}
/// <summary>
/// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
/// </summary>
/// <param name="emailToMatch">The e-mail address to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
var byEmail = ApplicationContext.Current.Services.MemberService.FindMembersByEmail(emailToMatch).ToArray();
totalRecords = byEmail.Length;
var pagedResult = new PagedResult<IMember>(totalRecords, pageIndex, pageSize);
var collection = new MembershipUserCollection();
foreach (var m in byEmail.Skip(pagedResult.SkipSize).Take(pageSize))
{
collection.Add(m.AsConcreteMembershipUser());
}
return collection;
}
/// <summary>
/// Gets a collection of membership users where the user name contains the specified user name to match.
/// </summary>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
int counter = 0;
int startIndex = pageSize * pageIndex;
int endIndex = startIndex + pageSize - 1;
MembershipUserCollection membersList = new MembershipUserCollection();
Member[] memberArray = Member.GetMemberByName(usernameToMatch, false);
totalRecords = memberArray.Length;
foreach (Member m in memberArray)
{
if (counter >= startIndex)
membersList.Add(ConvertToMembershipUser(m));
if (counter >= endIndex) break;
counter++;
}
return membersList;
}
/// <summary>
/// Gets a collection of all the users in the data source in pages of data.
/// </summary>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
int counter = 0;
int startIndex = pageSize * pageIndex;
int endIndex = startIndex + pageSize - 1;
MembershipUserCollection membersList = new MembershipUserCollection();
Member[] memberArray = Member.GetAll;
totalRecords = memberArray.Length;
foreach (Member m in memberArray)
{
if (counter >= startIndex)
membersList.Add(ConvertToMembershipUser(m));
if (counter >= endIndex) break;
counter++;
}
return membersList;
}
/// <summary>
/// Gets the number of users currently accessing the application.
/// </summary>
/// <returns>
/// The number of users currently accessing the application.
/// </returns>
public override int GetNumberOfUsersOnline()
{
return Member.CachedMembers().Count;
}
/// <summary>
/// Gets the password for the specified user name from the data source.
/// </summary>
/// <param name="username">The user to retrieve the password for.</param>
/// <param name="answer">The password answer for the user.</param>
/// <returns>
/// The password for the specified user name.
/// </returns>
public override string GetPassword(string username, string answer)
{
if (!EnablePasswordRetrieval)
throw new ProviderException("Password Retrieval Not Enabled.");
if (PasswordFormat == MembershipPasswordFormat.Hashed)
throw new ProviderException("Cannot retrieve Hashed passwords.");
Member m = Member.GetMemberFromLoginName(username);
if (m != null)
{
if (RequiresQuestionAndAnswer)
{
// check if password answer property alias is set
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
// check if user is locked out
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool isLockedOut = false;
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLockedOut);
if (isLockedOut)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
}
// match password answer
if (GetMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, false) != answer)
{
throw new MembershipPasswordException("Incorrect password answer");
}
}
else
{
throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes");
}
}
}
if (m == null)
{
throw new MembershipPasswordException("The supplied user is not found");
}
else
{
return m.Password;
}
}
/// <summary>
/// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="username">The name of the user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (String.IsNullOrEmpty(username))
return null;
Member m = Member.GetMemberFromLoginName(username);
if (m == null) return null;
else return ConvertToMembershipUser(m);
}
/// <summary>
/// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
if (String.IsNullOrEmpty(providerUserKey.ToString()))
return null;
Member m = new Member(Convert.ToInt32(providerUserKey));
if (m == null) return null;
else return ConvertToMembershipUser(m);
}
/// <summary>
/// Gets the user name associated with the specified e-mail address.
/// </summary>
/// <param name="email">The e-mail address to search for.</param>
/// <returns>
/// The user name associated with the specified e-mail address. If no match is found, return null.
/// </returns>
public override string GetUserNameByEmail(string email)
{
Member m = Member.GetMemberFromEmail(email);
if (m == null) return null;
else return m.LoginName;
}
/// <summary>
/// Resets a user's password to a new, automatically generated password.
/// </summary>
/// <param name="username">The user to reset the password for.</param>
/// <param name="answer">The password answer for the specified user (not used with Umbraco).</param>
/// <returns>The new password for the specified user.</returns>
public override string ResetPassword(string username, string answer)
{
if (!EnablePasswordReset)
{
throw new NotSupportedException("Password reset is not supported");
}
Member m = Member.GetMemberFromLoginName(username);
if (m == null)
throw new MembershipPasswordException("The supplied user is not found");
else
{
if (RequiresQuestionAndAnswer)
{
// check if password answer property alias is set
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
// check if user is locked out
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool isLockedOut = false;
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLockedOut);
if (isLockedOut)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
}
// match password answer
if (GetMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, false) != answer)
{
throw new MembershipPasswordException("Incorrect password answer");
}
}
else
{
throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes");
}
}
string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
m.Password = newPassword;
return newPassword;
}
}
/// <summary>
/// Clears a lock so that the membership user can be validated.
/// </summary>
/// <param name="userName">The membership user to clear the lock status for.</param>
/// <returns>
/// true if the membership user was successfully unlocked; otherwise, false.
/// </returns>
public override bool UnlockUser(string userName)
{
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
Member m = Member.GetMemberFromLoginName(userName);
if (m != null)
{
UpdateMemberProperty(m, m_LockPropertyTypeAlias, false);
return true;
}
else
{
throw new Exception(String.Format("No member with the username '{0}' found", userName));
}
}
else
{
throw new ProviderException("To enable lock/unlocking, you need to add a 'bool' property on your membertype and add the alias of the property in the 'umbracoLockPropertyTypeAlias' attribute of the membership element in the web.config.");
}
}
/// <summary>
/// Updates e-mail and potentially approved status, lock status and comment on a user.
/// Note: To automatically support lock, approve and comments you'll need to add references to the membertype properties in the
/// 'Member' element in web.config by adding their aliases to the 'umbracoApprovePropertyTypeAlias', 'umbracoLockPropertyTypeAlias' and 'umbracoCommentPropertyTypeAlias' attributes
/// </summary>
/// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user.</param>
public override void UpdateUser(MembershipUser user)
{
Member m = Member.GetMemberFromLoginName(user.UserName);
m.Email = user.Email;
// if supported, update approve status
UpdateMemberProperty(m, m_ApprovedPropertyTypeAlias, user.IsApproved);
// if supported, update lock status
UpdateMemberProperty(m, m_LockPropertyTypeAlias, user.IsLockedOut);
// if supported, update comment
UpdateMemberProperty(m, m_CommentPropertyTypeAlias, user.Comment);
m.Save();
}
private static void UpdateMemberProperty(Member m, string propertyAlias, object propertyValue)
{
if (!String.IsNullOrEmpty(propertyAlias))
{
if (m.getProperty(propertyAlias) != null)
{
m.getProperty(propertyAlias).Value =
propertyValue;
}
}
}
private static string GetMemberProperty(Member m, string propertyAlias, bool isBool)
{
if (!String.IsNullOrEmpty(propertyAlias))
{
if (m.getProperty(propertyAlias) != null &&
m.getProperty(propertyAlias).Value != null)
{
if (isBool)
{
// Umbraco stored true as 1, which means it can be bool.tryParse'd
return m.getProperty(propertyAlias).Value.ToString().Replace("1", "true").Replace("0", "false");
}
else
return m.getProperty(propertyAlias).Value.ToString();
}
}
return null;
}
/// <summary>
/// Verifies that the specified user name and password exist in the data source.
/// </summary>
/// <param name="username">The name of the user to validate.</param>
/// <param name="password">The password for the specified user.</param>
/// <returns>
/// true if the specified username and password are valid; otherwise, false.
/// </returns>
public override bool ValidateUser(string username, string password)
{
Member m = Member.GetMemberFromLoginAndEncodedPassword(username, EncodePassword(password));
if (m != null)
{
// check for lock status. If locked, then set the member property to null
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
string lockedStatus = GetMemberProperty(m, m_LockPropertyTypeAlias, true);
if (!String.IsNullOrEmpty(lockedStatus))
{
bool isLocked = false;
if (bool.TryParse(lockedStatus, out isLocked))
{
if (isLocked)
{
m = null;
}
}
}
}
// check for approve status. If not approved, then set the member property to null
if (!CheckApproveStatus(m)) {
m = null;
}
// maybe update login date
if (m != null && !String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
UpdateMemberProperty(m, m_LastLoginPropertyTypeAlias, DateTime.Now);
}
// maybe reset password attempts
if (m != null && !String.IsNullOrEmpty(m_FailedPasswordAttemptsPropertyTypeAlias))
{
UpdateMemberProperty(m, m_FailedPasswordAttemptsPropertyTypeAlias, 0);
}
// persist data
if (m != null)
m.Save();
}
else if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias)
&& !String.IsNullOrEmpty(m_FailedPasswordAttemptsPropertyTypeAlias))
{
Member updateMemberDataObject = Member.GetMemberFromLoginName(username);
// update fail rate if it's approved
if (updateMemberDataObject != null && CheckApproveStatus(updateMemberDataObject))
{
int failedAttempts = 0;
int.TryParse(GetMemberProperty(updateMemberDataObject, m_FailedPasswordAttemptsPropertyTypeAlias, false), out failedAttempts);
failedAttempts = failedAttempts+1;
UpdateMemberProperty(updateMemberDataObject, m_FailedPasswordAttemptsPropertyTypeAlias, failedAttempts);
// lock user?
if (failedAttempts >= MaxInvalidPasswordAttempts)
{
UpdateMemberProperty(updateMemberDataObject, m_LockPropertyTypeAlias, true);
}
updateMemberDataObject.Save();
}
}
return (m != null);
}
private bool CheckApproveStatus(Member m)
{
bool isApproved = false;
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
{
if (m != null)
{
string approveStatus = GetMemberProperty(m, m_ApprovedPropertyTypeAlias, true);
if (!String.IsNullOrEmpty(approveStatus))
{
bool.TryParse(approveStatus, out isApproved);
}
}
}
else {
// if we don't use approve statuses
isApproved = true;
}
return isApproved;
}
#endregion
#region Helper Methods
/// <summary>
/// Checks the password.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="dbPassword">The dbPassword.</param>
/// <returns></returns>
internal bool CheckPassword(string password, string dbPassword)
{
string pass1 = password;
string pass2 = dbPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Encrypted:
pass2 = UnEncodePassword(dbPassword);
break;
case MembershipPasswordFormat.Hashed:
pass1 = EncodePassword(password);
break;
default:
break;
}
return (pass1 == pass2) ? true : false;
}
/// <summary>
/// Encodes the password.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The encoded password.</returns>
public string EncodePassword(string password)
{
string encodedPassword = password;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword =
Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
default:
throw new ProviderException("Unsupported password format.");
}
return encodedPassword;
}
/// <summary>
/// Unencode password.
/// </summary>
/// <param name="encodedPassword">The encoded password.</param>
/// <returns>The unencoded password.</returns>
public string UnEncodePassword(string encodedPassword)
{
string password = encodedPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
break;
case MembershipPasswordFormat.Hashed:
throw new ProviderException("Cannot decrypt a hashed password.");
default:
throw new ProviderException("Unsupported password format.");
}
return password;
}
/// <summary>
/// Converts to membership user.
/// </summary>
/// <param name="m">The m.</param>
/// <returns></returns>
private MembershipUser ConvertToMembershipUser(Member m)
{
if (m == null) return null;
else
{
DateTime lastLogin = DateTime.Now;
bool isApproved = true;
bool isLocked = false;
string comment = "";
string passwordQuestion = "";
// last login
if (!String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
DateTime.TryParse(GetMemberProperty(m, m_LastLoginPropertyTypeAlias, false), out lastLogin);
}
// approved
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
{
bool.TryParse(GetMemberProperty(m, m_ApprovedPropertyTypeAlias, true), out isApproved);
}
// locked
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLocked);
}
// comment
if (!String.IsNullOrEmpty(m_CommentPropertyTypeAlias))
{
comment = GetMemberProperty(m, m_CommentPropertyTypeAlias, false);
}
// password question
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias))
{
passwordQuestion = GetMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, false);
}
return new MembershipUser(m_providerName, m.LoginName, m.Id, m.Email, passwordQuestion, comment, isApproved, isLocked, m.CreateDateTime, lastLogin,
DateTime.Now, DateTime.Now, DateTime.Now);
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="GlobalizationSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration {
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Web.Util;
using System.Security.Permissions;
/*
<!--
globalization Attributes:
requestEncoding="[Encoding value]" - Encoding to use for request
responseEncoding="[Encoding value]" - Encoding to use for response
enableBestFitResponseEncoding="[true|false]" - Enable best fit character encoding for response
responseHeaderEncoding="[Encoding value]" - Encoding to use for response headers (default is utf-8)
fileEncoding="[Encoding value]" - Encoding to use for files
culture="[Culture]" - default Thread.CurrentCulture
uiCulture="[Culture]" - default Thread.CurrentUICulture
resourceProviderFactoryType="[type]"
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>
*/
public sealed class GlobalizationSection : ConfigurationSection {
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propRequestEncoding =
new ConfigurationProperty("requestEncoding", typeof(string), Encoding.UTF8.WebName, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propResponseEncoding =
new ConfigurationProperty("responseEncoding", typeof(string), Encoding.UTF8.WebName, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propFileEncoding =
new ConfigurationProperty("fileEncoding", typeof(string), String.Empty, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCulture =
new ConfigurationProperty("culture", typeof(string), String.Empty, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propUICulture =
new ConfigurationProperty("uiCulture", typeof(string), String.Empty, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propEnableClientBasedCulture =
new ConfigurationProperty("enableClientBasedCulture", typeof(bool), false, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propResponseHeaderEncoding =
new ConfigurationProperty("responseHeaderEncoding", typeof(string), Encoding.UTF8.WebName, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propResourceProviderFactoryType =
new ConfigurationProperty("resourceProviderFactoryType", typeof(string), String.Empty, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propEnableBestFitResponseEncoding =
new ConfigurationProperty("enableBestFitResponseEncoding", typeof(bool), false, ConfigurationPropertyOptions.None);
private Encoding responseEncodingCache = null;
private Encoding responseHeaderEncodingCache = null;
private Encoding requestEncodingCache = null;
private Encoding fileEncodingCache = null;
private String cultureCache = null;
private String uiCultureCache = null;
private Type _resourceProviderFactoryType;
static GlobalizationSection() {
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propRequestEncoding);
_properties.Add(_propResponseEncoding);
_properties.Add(_propFileEncoding);
_properties.Add(_propCulture);
_properties.Add(_propUICulture);
_properties.Add(_propEnableClientBasedCulture);
_properties.Add(_propResponseHeaderEncoding);
_properties.Add(_propResourceProviderFactoryType);
_properties.Add(_propEnableBestFitResponseEncoding);
}
public GlobalizationSection() {
}
protected override ConfigurationPropertyCollection Properties {
get {
return _properties;
}
}
[ConfigurationProperty("requestEncoding", DefaultValue = "utf-8")]
public Encoding RequestEncoding {
get {
if (requestEncodingCache == null) {
requestEncodingCache = Encoding.UTF8;
}
return requestEncodingCache;
}
set {
if (value != null) {
base[_propRequestEncoding] = value.WebName;
requestEncodingCache = value;
}
else {
base[_propRequestEncoding] = value;
requestEncodingCache = Encoding.UTF8;
}
}
}
[ConfigurationProperty("responseEncoding", DefaultValue = "utf-8")]
public Encoding ResponseEncoding {
get {
if (responseEncodingCache == null)
responseEncodingCache = Encoding.UTF8;
return responseEncodingCache;
}
set {
if (value != null) {
base[_propResponseEncoding] = value.WebName;
responseEncodingCache = value;
}
else {
base[_propResponseEncoding] = value;
responseEncodingCache = Encoding.UTF8;
}
}
}
[ConfigurationProperty("responseHeaderEncoding", DefaultValue = "utf-8")]
public Encoding ResponseHeaderEncoding {
get {
if (responseHeaderEncodingCache == null) {
responseHeaderEncodingCache = Encoding.UTF8;
}
return responseHeaderEncodingCache;
}
set {
if (value != null) {
base[_propResponseHeaderEncoding] = value.WebName;
responseHeaderEncodingCache = value;
}
else {
base[_propResponseHeaderEncoding] = value;
responseHeaderEncodingCache = Encoding.UTF8;
}
}
}
[ConfigurationProperty("fileEncoding")]
public Encoding FileEncoding {
get {
if (fileEncodingCache == null) {
fileEncodingCache = Encoding.Default;
}
return fileEncodingCache;
}
set {
if (value != null) {
base[_propFileEncoding] = value.WebName;
fileEncodingCache = value;
}
else {
base[_propFileEncoding] = value;
fileEncodingCache = Encoding.Default;
}
}
}
[ConfigurationProperty("culture", DefaultValue = "")]
public string Culture {
get {
if (cultureCache == null) {
cultureCache = (string)base[_propCulture];
}
return cultureCache;
}
set {
base[_propCulture] = value;
cultureCache = value;
}
}
[ConfigurationProperty("uiCulture", DefaultValue = "")]
public string UICulture {
get {
if (uiCultureCache == null) {
uiCultureCache = (string)base[_propUICulture];
}
return uiCultureCache;
}
set {
base[_propUICulture] = value;
uiCultureCache = value;
}
}
[ConfigurationProperty("enableClientBasedCulture", DefaultValue = false)]
public bool EnableClientBasedCulture {
get {
return (bool)base[_propEnableClientBasedCulture];
}
set {
base[_propEnableClientBasedCulture] = value;
}
}
[ConfigurationProperty("resourceProviderFactoryType", DefaultValue = "")]
public string ResourceProviderFactoryType {
get {
return (string)base[_propResourceProviderFactoryType];
}
set {
base[_propResourceProviderFactoryType] = value;
}
}
[ConfigurationProperty("enableBestFitResponseEncoding", DefaultValue = false)]
public bool EnableBestFitResponseEncoding {
get {
return (bool)base[_propEnableBestFitResponseEncoding];
}
set {
base[_propEnableBestFitResponseEncoding] = value;
}
}
internal Type ResourceProviderFactoryTypeInternal {
get {
if (_resourceProviderFactoryType == null && !String.IsNullOrEmpty(ResourceProviderFactoryType)) {
lock (this) {
if (_resourceProviderFactoryType == null) {
Type resourceProviderFactoryType = ConfigUtil.GetType(ResourceProviderFactoryType, "resourceProviderFactoryType", this);
ConfigUtil.CheckBaseType(typeof(System.Web.Compilation.ResourceProviderFactory), resourceProviderFactoryType, "resourceProviderFactoryType", this);
_resourceProviderFactoryType = resourceProviderFactoryType;
}
}
}
return _resourceProviderFactoryType;
}
}
private void CheckCulture(string configCulture) {
if (StringUtil.EqualsIgnoreCase(configCulture, HttpApplication.AutoCulture)) {
return;
}
else if (StringUtil.StringStartsWithIgnoreCase(configCulture, HttpApplication.AutoCulture)) {
// This will throw if bad
CultureInfo dummyCultureInfo = new CultureInfo(configCulture.Substring(5));
return;
}
// This will throw if bad
new CultureInfo(configCulture);
}
protected override void PreSerialize(XmlWriter writer) {
PostDeserialize();
}
protected override void PostDeserialize() {
ConfigurationPropertyCollection props = Properties;
// Need to check that the encodings provided are valid here
ConfigurationProperty errorProperty = null;
int errorLine = Int32.MaxValue;
try {
if (!String.IsNullOrEmpty((string)base[_propResponseEncoding]))
responseEncodingCache = (Encoding)Encoding.GetEncoding((string)base[_propResponseEncoding]);
}
catch {
errorProperty = _propResponseEncoding;
errorLine = ElementInformation.Properties[errorProperty.Name].LineNumber;
}
try {
if (!String.IsNullOrEmpty((string)base[_propResponseHeaderEncoding])) {
responseHeaderEncodingCache = (Encoding)Encoding.GetEncoding((string)base[_propResponseHeaderEncoding]);
}
}
catch {
if (errorLine > ElementInformation.Properties[_propResponseHeaderEncoding.Name].LineNumber) {
errorProperty = _propResponseHeaderEncoding;
errorLine = ElementInformation.Properties[errorProperty.Name].LineNumber;
}
}
try {
if (!String.IsNullOrEmpty((string)base[_propRequestEncoding])) {
requestEncodingCache = (Encoding)Encoding.GetEncoding((string)base[_propRequestEncoding]);
}
}
catch {
if (errorLine > ElementInformation.Properties[_propRequestEncoding.Name].LineNumber) {
errorProperty = _propRequestEncoding;
errorLine = ElementInformation.Properties[errorProperty.Name].LineNumber;
}
}
try {
if (!String.IsNullOrEmpty((string)base[_propFileEncoding])) {
fileEncodingCache = (Encoding)Encoding.GetEncoding((string)base[_propFileEncoding]);
}
}
catch {
if (errorLine > ElementInformation.Properties[_propFileEncoding.Name].LineNumber) {
errorProperty = _propFileEncoding;
errorLine = ElementInformation.Properties[errorProperty.Name].LineNumber;
}
}
try {
if (!String.IsNullOrEmpty((string)base[_propCulture])) {
CheckCulture((string)base[_propCulture]);
}
}
catch {
if (errorLine > ElementInformation.Properties[_propCulture.Name].LineNumber) {
errorProperty = _propCulture;
errorLine = ElementInformation.Properties[_propCulture.Name].LineNumber;
}
}
try {
if (!String.IsNullOrEmpty((string)base[_propUICulture])) {
CheckCulture((string)base[_propUICulture]);
}
}
catch {
if (errorLine > ElementInformation.Properties[_propUICulture.Name].LineNumber) {
errorProperty = _propUICulture;
errorLine = ElementInformation.Properties[_propUICulture.Name].LineNumber;
}
}
if (errorProperty != null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_value_for_globalization_attr, errorProperty.Name),
ElementInformation.Properties[errorProperty.Name].Source, ElementInformation.Properties[errorProperty.Name].LineNumber);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Linq;
using System.Reflection;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace Aurora.Services.DataService
{
public class LocalEstateConnector : ConnectorBase, IEstateConnector
{
private IGenericData GD;
private string m_estateTable = "estatesettings";
private string m_estateRegionsTable = "estateregions";
#region IEstateConnector Members
public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore registry,
string defaultConnectionString)
{
GD = GenericData;
m_registry = registry;
if (source.Configs[Name] != null)
defaultConnectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);
GD.ConnectToDatabase(defaultConnectionString, "Estate",
source.Configs["AuroraConnectors"].GetBoolean("ValidateTables", true));
DataManager.DataManager.RegisterPlugin(Name + "Local", this);
if (source.Configs["AuroraConnectors"].GetString("EstateConnector", "LocalConnector") == "LocalConnector")
{
DataManager.DataManager.RegisterPlugin(this);
}
Init(registry, Name);
}
public string Name
{
get { return "IEstateConnector"; }
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public EstateSettings GetEstateSettings(UUID regionID)
{
object remoteValue = DoRemote(regionID);
if (remoteValue != null || m_doRemoteOnly)
return ReturnEstateSettings(remoteValue);
EstateSettings settings = new EstateSettings() { EstateID = 0 };
int estateID = GetEstateID(regionID);
if (estateID == 0)
return settings;
settings = GetEstate(estateID);
return settings;
}
public EstateSettings GetEstateSettings(int EstateID)
{
object remoteValue = DoRemote(EstateID);
if (remoteValue != null || m_doRemoteOnly)
return ReturnEstateSettings(remoteValue);
return GetEstate(EstateID);
}
private EstateSettings ReturnEstateSettings(object remoteValue)
{
EstateSettings es = (EstateSettings)remoteValue;
if(es != null)
es.OnSave += SaveEstateSettings;
return es;
}
public EstateSettings GetEstateSettings(string name)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateName"] = name;
return ReturnEstateSettings(GetEstate(
int.Parse(GD.Query(new string[1]{ "EstateID" }, "estatesettings", filter, null, null, null)[0]))
);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public int CreateNewEstate(EstateSettings es, UUID RegionID)
{
object remoteValue = DoRemote(es.ToOSD(), RegionID);
if (remoteValue != null || m_doRemoteOnly)
return (int)remoteValue;
int estateID = GetEstate(es.EstateOwner, es.EstateName);
if (estateID > 0)
{
if (LinkRegion(RegionID, estateID))
return estateID;
return 0;
}
es.EstateID = GetNewEstateID();
SaveEstateSettings(es, true);
LinkRegion(RegionID, (int)es.EstateID);
return (int)es.EstateID;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public void SaveEstateSettings(EstateSettings es)
{
object remoteValue = DoRemote(es.ToOSD());
if (remoteValue != null || m_doRemoteOnly)
return;
SaveEstateSettings(es, false);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public bool LinkRegion(UUID regionID, int estateID)
{
object remoteValue = DoRemote(regionID, estateID);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
Dictionary<string, object> row = new Dictionary<string, object>(2);
row["RegionID"] = regionID;
row["EstateID"] = estateID;
GD.Replace(m_estateRegionsTable, row);
return true;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public bool DelinkRegion(UUID regionID)
{
object remoteValue = DoRemote(regionID);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["RegionID"] = regionID;
GD.Delete(m_estateRegionsTable, filter);
return true;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.High)]
public bool DeleteEstate(int estateID)
{
object remoteValue = DoRemote(estateID);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateID"] = estateID;
GD.Delete(m_estateRegionsTable, filter);
GD.Delete(m_estateTable, filter);
return true;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public int GetEstate(UUID ownerID, string name)
{
object remoteValue = DoRemote(ownerID, name);
if (remoteValue != null || m_doRemoteOnly)
return (int)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateName"] = name;
filter.andFilters["EstateOwner"] = ownerID;
List<string> retVal = GD.Query(new string[1] { "EstateID" }, "estatesettings", filter, null, null, null);
if (retVal.Count > 0)
return int.Parse(retVal[0]);
return 0;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<UUID> GetRegions(int estateID)
{
object remoteValue = DoRemote(estateID);
if (remoteValue != null || m_doRemoteOnly)
return (List<UUID>)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateID"] = estateID;
return GD.Query(new string[1] { "RegionID" }, m_estateRegionsTable, filter, null, null, null).ConvertAll(x => UUID.Parse(x));
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<EstateSettings> GetEstates(UUID OwnerID)
{
return GetEstates(OwnerID, new Dictionary<string,bool>(0));
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<EstateSettings> GetEstates(UUID OwnerID, Dictionary<string, bool> boolFields)
{
object remoteValue = DoRemote(OwnerID, boolFields);
if (remoteValue != null || m_doRemoteOnly)
return (List<EstateSettings>)remoteValue;
List<EstateSettings> settings = new List<EstateSettings>();
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateOwner"] = OwnerID;
List<int> retVal = GD.Query(new string[1] { "EstateID" }, m_estateTable, filter, null, null, null).ConvertAll(x => int.Parse(x));
foreach (int estateID in retVal)
{
bool Add = true;
EstateSettings es = GetEstate(estateID);
if(boolFields.Count > 0){
OSDMap esmap = es.ToOSD();
foreach(KeyValuePair<string, bool> field in boolFields){
if(esmap.ContainsKey(field.Key) && esmap[field.Key].AsBoolean() != field.Value){
Add = false;
break;
}
}
}
if (Add)
{
settings.Add(ReturnEstateSettings(es));
}
}
return settings;
}
#endregion
#region Helpers
public int GetEstateID(UUID regionID)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["RegionID"] = regionID;
List<string> retVal = GD.Query(new string[1] { "EstateID" }, m_estateRegionsTable, filter, null, null, null);
return (retVal.Count > 0) ? int.Parse(retVal[0]) : 0;
}
private EstateSettings GetEstate(int estateID)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateID"] = estateID;
List<string> retVals = GD.Query(new string[1] { "*" }, m_estateTable, filter, null, null, null);
EstateSettings settings = new EstateSettings{
EstateID = 0
};
if (retVals.Count > 0)
{
settings.FromOSD((OSDMap)OSDParser.DeserializeJson(retVals[4]));
}
settings.OnSave += SaveEstateSettings;
return settings;
}
private uint GetNewEstateID()
{
List<string> QueryResults = GD.Query(new string[2]{
"COUNT(EstateID)",
"MAX(EstateID)"
}, m_estateTable, null, null, null, null);
return (uint.Parse(QueryResults[0]) > 0) ? uint.Parse(QueryResults[1]) + 1 : 100;
}
protected void SaveEstateSettings(EstateSettings es, bool doInsert)
{
Dictionary<string, object> values = new Dictionary<string, object>(5);
values["EstateID"] = es.EstateID;
values["EstateName"] = es.EstateName;
values["EstateOwner"] = es.EstateOwner;
values["ParentEstateID"] = es.ParentEstateID;
values["Settings"] = OSDParser.SerializeJsonString(es.ToOSD());
if (!doInsert)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["EstateID"] = es.EstateID;
GD.Update(m_estateTable, values, null, filter, null, null);
}
else
{
GD.Insert(m_estateTable, values);
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.CoreModules.Scripting.LSLHttp;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for HTTP related functions in LSL
/// </summary>
[TestFixture]
public class LSL_ApiHttpTests : OpenSimTestCase
{
private Scene m_scene;
private MockScriptEngine m_engine;
private UrlModule m_urlModule;
private TaskInventoryItem m_scriptItem;
private LSL_Api m_lslApi;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TestFixureTearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// This is an unfortunate bit of clean up we have to do because MainServer manages things through static
// variables and the VM is not restarted between tests.
uint port = 9999;
MainServer.RemoveHttpServer(port);
BaseHttpServer server = new BaseHttpServer(port, false, 0, "");
MainServer.AddHttpServer(server);
MainServer.Instance = server;
server.Start();
m_engine = new MockScriptEngine();
m_urlModule = new UrlModule();
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, new IniConfigSource(), m_engine, m_urlModule);
SceneObjectGroup so = SceneHelpers.AddSceneObject(m_scene);
m_scriptItem = TaskInventoryHelpers.AddScript(m_scene.AssetService, so.RootPart);
// This is disconnected from the actual script - the mock engine does not set up any LSL_Api atm.
// Possibly this could be done and we could obtain it directly from the MockScriptEngine.
m_lslApi = new LSL_Api();
m_lslApi.Initialize(m_engine, so.RootPart, m_scriptItem);
}
[TearDown]
public void TearDown()
{
MainServer.Instance.Stop();
}
[Test]
public void TestLlReleaseUrl()
{
TestHelpers.InMethod();
m_lslApi.llRequestURL();
string returnedUri = m_engine.PostedEvents[m_scriptItem.ItemID][0].Params[2].ToString();
{
// Check that the initial number of URLs is correct
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check releasing a non-url
m_lslApi.llReleaseURL("GARBAGE");
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check releasing a non-existing url
m_lslApi.llReleaseURL("http://example.com");
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check URL release
m_lslApi.llReleaseURL(returnedUri);
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(returnedUri);
bool gotExpectedException = false;
try
{
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{}
}
catch (WebException e)
{
using (HttpWebResponse response = (HttpWebResponse)e.Response)
gotExpectedException = response.StatusCode == HttpStatusCode.NotFound;
}
Assert.That(gotExpectedException, Is.True);
}
{
// Check releasing the same URL again
m_lslApi.llReleaseURL(returnedUri);
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls));
}
}
[Test]
public void TestLlRequestUrl()
{
TestHelpers.InMethod();
string requestId = m_lslApi.llRequestURL();
Assert.That(requestId, Is.Not.EqualTo(UUID.Zero.ToString()));
string returnedUri;
{
// Check that URL is correctly set up
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
Assert.That(m_engine.PostedEvents.ContainsKey(m_scriptItem.ItemID));
List<EventParams> events = m_engine.PostedEvents[m_scriptItem.ItemID];
Assert.That(events.Count, Is.EqualTo(1));
EventParams eventParams = events[0];
Assert.That(eventParams.EventName, Is.EqualTo("http_request"));
UUID returnKey;
string rawReturnKey = eventParams.Params[0].ToString();
string method = eventParams.Params[1].ToString();
returnedUri = eventParams.Params[2].ToString();
Assert.That(UUID.TryParse(rawReturnKey, out returnKey), Is.True);
Assert.That(method, Is.EqualTo(ScriptBaseClass.URL_REQUEST_GRANTED));
Assert.That(Uri.IsWellFormedUriString(returnedUri, UriKind.Absolute), Is.True);
}
{
// Check that request to URL works.
string testResponse = "Hello World";
m_engine.ClearPostedEvents();
m_engine.PostEventHook
+= (itemId, evp) => m_lslApi.llHTTPResponse(evp.Params[0].ToString(), 200, testResponse);
// Console.WriteLine("Trying {0}", returnedUri);
AssertHttpResponse(returnedUri, testResponse);
Assert.That(m_engine.PostedEvents.ContainsKey(m_scriptItem.ItemID));
List<EventParams> events = m_engine.PostedEvents[m_scriptItem.ItemID];
Assert.That(events.Count, Is.EqualTo(1));
EventParams eventParams = events[0];
Assert.That(eventParams.EventName, Is.EqualTo("http_request"));
UUID returnKey;
string rawReturnKey = eventParams.Params[0].ToString();
string method = eventParams.Params[1].ToString();
string body = eventParams.Params[2].ToString();
Assert.That(UUID.TryParse(rawReturnKey, out returnKey), Is.True);
Assert.That(method, Is.EqualTo("GET"));
Assert.That(body, Is.EqualTo(""));
}
}
private void AssertHttpResponse(string uri, string expectedResponse)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream stream = webResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
Assert.That(reader.ReadToEnd(), Is.EqualTo(expectedResponse));
}
}
}
}
}
}
| |
/*
* 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 java = biz.ritter.javapi;
namespace biz.ritter.javapi.security
{
/**
* {@code SecureRandom} is an engine class which is capable of generating
* cryptographically secure pseudo-random numbers.
*/
public class SecureRandom : Random {
private const long serialVersionUID = 4940670005562187L;
// The service name.
[NonSerialized]
private const String SERVICE = "SecureRandom"; //$NON-NLS-1$
// Used to access common engine functionality
[NonSerialized]
private static Engine engine = new Engine(SERVICE);
private Provider provider;
private SecureRandomSpi secureRandomSpi;
private String algorithm;
private byte[] state;
private byte[] randomBytes;
private int randomBytesUsed;
private long counter;
// Internal SecureRandom used for getSeed(int)
[NonSerialized]
private static SecureRandom internalSecureRandom;
/**
* Constructs a new instance of {@code SecureRandom}. An implementation for
* the highest-priority provider is returned. The constructed instance will
* not have been seeded.
*/
public SecureRandom() :base(0){
Provider.Service service = findService();
if (service == null) {
this.provider = null;
this.secureRandomSpi = new SHA1PRNG_SecureRandomImpl();
this.algorithm = "SHA1PRNG"; //$NON-NLS-1$
} else {
try {
this.provider = service.getProvider();
this.secureRandomSpi = (SecureRandomSpi)service.newInstance(null);
this.algorithm = service.getAlgorithm();
} catch (java.lang.Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* Constructs a new instance of {@code SecureRandom}. An implementation for
* the highest-priority provider is returned. The constructed instance will
* be seeded with the parameter.
*
* @param seed
* the seed for this generator.
*/
public SecureRandom(byte[] seed) :this(){
setSeed(seed);
}
//Find SecureRandom service.
private Provider.Service findService() {
java.util.Set<Object> s;
Provider.Service service;
for (java.util.Iterator<Object> it1 = Services.getProvidersList().iterator(); it1.hasNext();) {
service = ((Provider)it1.next()).getService("SecureRandom"); //$NON-NLS-1$
if (service != null) {
return service;
}
}
return null;
}
/**
* Constructs a new instance of {@code SecureRandom} using the given
* implementation from the specified provider.
*
* @param secureRandomSpi
* the implementation.
* @param provider
* the security provider.
*/
protected SecureRandom(SecureRandomSpi secureRandomSpi,
Provider provider) :
this(secureRandomSpi, provider, "unknown"){ //$NON-NLS-1$
}
// Constructor
private SecureRandom(SecureRandomSpi secureRandomSpi,
Provider provider,
String algorithm) :base(0){
this.provider = provider;
this.algorithm = algorithm;
this.secureRandomSpi = secureRandomSpi;
}
/**
* Returns a new instance of {@code SecureRandom} that utilizes the
* specified algorithm.
*
* @param algorithm
* the name of the algorithm to use.
* @return a new instance of {@code SecureRandom} that utilizes the
* specified algorithm.
* @throws NoSuchAlgorithmException
* if the specified algorithm is not available.
* @throws NullPointerException
* if {@code algorithm} is {@code null}.
*/
public static SecureRandom getInstance(String algorithm)
{//throws NoSuchAlgorithmException {
if (algorithm == null) {
throw new java.lang.NullPointerException(Messages.getString("security.01")); //$NON-NLS-1$
}
lock (engine) {
engine.getInstance(algorithm, null);
return new SecureRandom((SecureRandomSpi)engine.spi, engine.provider, algorithm);
}
}
/**
* Returns a new instance of {@code SecureRandom} that utilizes the
* specified algorithm from the specified provider.
*
* @param algorithm
* the name of the algorithm to use.
* @param provider
* the name of the provider.
* @return a new instance of {@code SecureRandom} that utilizes the
* specified algorithm from the specified provider.
* @throws NoSuchAlgorithmException
* if the specified algorithm is not available.
* @throws NoSuchProviderException
* if the specified provider is not available.
* @throws NullPointerException
* if {@code algorithm} is {@code null}.
*/
public static SecureRandom getInstance(String algorithm, String provider)
{//throws NoSuchAlgorithmException, NoSuchProviderException {
if ((provider == null) || (provider.length() == 0)) {
throw new java.lang.IllegalArgumentException(
Messages.getString("security.02")); //$NON-NLS-1$
}
Provider p = Security.getProvider(provider);
if (p == null) {
throw new NoSuchProviderException(Messages.getString("security.03", provider)); //$NON-NLS-1$
}
return getInstance(algorithm, p);
}
/**
* Returns a new instance of {@code SecureRandom} that utilizes the
* specified algorithm from the specified provider.
*
* @param algorithm
* the name of the algorithm to use.
* @param provider
* the security provider.
* @return a new instance of {@code SecureRandom} that utilizes the
* specified algorithm from the specified provider.
* @throws NoSuchAlgorithmException
* if the specified algorithm is not available.
* @throws NullPointerException
* if {@code algorithm} is {@code null}.
*/
public static SecureRandom getInstance(String algorithm, Provider provider)
{//throws NoSuchAlgorithmException {
if (provider == null) {
throw new java.lang.IllegalArgumentException(Messages.getString("security.04")); //$NON-NLS-1$
}
if (algorithm == null) {
throw new java.lang.NullPointerException(Messages.getString("security.01")); //$NON-NLS-1$
}
lock (engine) {
engine.getInstance(algorithm, provider, null);
return new SecureRandom((SecureRandomSpi)engine.spi, provider, algorithm);
}
}
/**
* Returns the provider associated with this {@code SecureRandom}.
*
* @return the provider associated with this {@code SecureRandom}.
*/
public Provider getProvider() {
return provider;
}
/**
* Returns the name of the algorithm of this {@code SecureRandom}.
*
* @return the name of the algorithm of this {@code SecureRandom}.
*/
public virtual String getAlgorithm() {
return algorithm;
}
/**
* Reseeds this {@code SecureRandom} instance with the specified {@code
* seed}. The seed of this {@code SecureRandom} instance is supplemented,
* not replaced.
*
* @param seed
* the new seed.
*/
public virtual void setSeed(byte[] seed) {
lock(this) {
secureRandomSpi.engineSetSeed(seed);
}
}
/**
* Reseeds this this {@code SecureRandom} instance with the eight bytes
* described by the representation of the given {@code long seed}. The seed
* of this {@code SecureRandom} instance is supplemented, not replaced.
*
* @param seed
* the new seed.
*/
public virtual void setSeed(long seed) {
if (seed == 0) { // skip call from Random
return;
}
byte[] byteSeed = {
(byte)((seed >> 56) & 0xFF),
(byte)((seed >> 48) & 0xFF),
(byte)((seed >> 40) & 0xFF),
(byte)((seed >> 32) & 0xFF),
(byte)((seed >> 24) & 0xFF),
(byte)((seed >> 16) & 0xFF),
(byte)((seed >> 8) & 0xFF),
(byte)((seed) & 0xFF)
};
setSeed(byteSeed);
}
/**
* Generates and stores random bytes in the given {@code byte[]} for each
* array element.
*
* @param bytes
* the {@code byte[]} to be filled with random bytes.
*/
public virtual void nextBytes(byte[] bytes) {
lock(this){
secureRandomSpi.engineNextBytes(bytes);
}
}
/**
* Generates and returns an {@code int} containing the specified number of
* random bits (right justified, with leading zeros).
*
* @param numBits
* number of bits to be generated. An input value should be in
* the range [0, 32].
* @return an {@code int} containing the specified number of random bits.
*/
protected int next(int numBits) {
if (numBits < 0) {
numBits = 0;
} else {
if (numBits > 32) {
numBits = 32;
}
}
int bytes = (numBits+7)/8;
byte[] next = new byte[bytes];
int ret = 0;
nextBytes(next);
for (int i = 0; i < bytes; i++) {
ret = (next[i] & 0xFF) | (ret << 8);
}
ret = dotnet.lang.Operator.shiftRightUnsignet( ret, (bytes*8 - numBits));
return ret;
}
/**
* Generates and returns the specified number of seed bytes, computed using
* the seed generation algorithm used by this {@code SecureRandom}.
*
* @param numBytes
* the number of seed bytes.
* @return the seed bytes
*/
public static byte[] getSeed(int numBytes) {
if (internalSecureRandom == null) {
internalSecureRandom = new SecureRandom();
}
return internalSecureRandom.generateSeed(numBytes);
}
/**
* Generates and returns the specified number of seed bytes, computed using
* the seed generation algorithm used by this {@code SecureRandom}.
*
* @param numBytes
* the number of seed bytes.
* @return the seed bytes.
*/
public byte[] generateSeed(int numBytes) {
return secureRandomSpi.engineGenerateSeed(numBytes);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A set of high-level properties associated with an SR.
/// </summary>
public partial class Sr_stat : XenObject<Sr_stat>
{
#region Constructors
public Sr_stat()
{
}
public Sr_stat(string uuid,
string name_label,
string name_description,
long free_space,
long total_space,
bool clustered,
sr_health health)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.free_space = free_space;
this.total_space = total_space;
this.clustered = clustered;
this.health = health;
}
/// <summary>
/// Creates a new Sr_stat from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Sr_stat(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Sr_stat from a Proxy_Sr_stat.
/// </summary>
/// <param name="proxy"></param>
public Sr_stat(Proxy_Sr_stat proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Sr_stat.
/// </summary>
public override void UpdateFrom(Sr_stat update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
free_space = update.free_space;
total_space = update.total_space;
clustered = update.clustered;
health = update.health;
}
internal void UpdateFrom(Proxy_Sr_stat proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
free_space = proxy.free_space == null ? 0 : long.Parse(proxy.free_space);
total_space = proxy.total_space == null ? 0 : long.Parse(proxy.total_space);
clustered = (bool)proxy.clustered;
health = proxy.health == null ? (sr_health) 0 : (sr_health)Helper.EnumParseDefault(typeof(sr_health), (string)proxy.health);
}
public Proxy_Sr_stat ToProxy()
{
Proxy_Sr_stat result_ = new Proxy_Sr_stat();
result_.uuid = uuid;
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.free_space = free_space.ToString();
result_.total_space = total_space.ToString();
result_.clustered = clustered;
result_.health = sr_health_helper.ToString(health);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Sr_stat
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("free_space"))
free_space = Marshalling.ParseLong(table, "free_space");
if (table.ContainsKey("total_space"))
total_space = Marshalling.ParseLong(table, "total_space");
if (table.ContainsKey("clustered"))
clustered = Marshalling.ParseBool(table, "clustered");
if (table.ContainsKey("health"))
health = (sr_health)Helper.EnumParseDefault(typeof(sr_health), Marshalling.ParseString(table, "health"));
}
public bool DeepEquals(Sr_stat other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._free_space, other._free_space) &&
Helper.AreEqual2(this._total_space, other._total_space) &&
Helper.AreEqual2(this._clustered, other._clustered) &&
Helper.AreEqual2(this._health, other._health);
}
internal static List<Sr_stat> ProxyArrayToObjectList(Proxy_Sr_stat[] input)
{
var result = new List<Sr_stat>();
foreach (var item in input)
result.Add(new Sr_stat(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Sr_stat server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Uuid that uniquely identifies this SR, if one is available.
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Short, human-readable label for the SR.
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// Longer, human-readable description of the SR. Descriptions are generally only displayed by clients when the user is examining SRs in detail.
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Number of bytes free on the backing storage (in bytes)
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual long free_space
{
get { return _free_space; }
set
{
if (!Helper.AreEqual(value, _free_space))
{
_free_space = value;
NotifyPropertyChanged("free_space");
}
}
}
private long _free_space;
/// <summary>
/// Total physical size of the backing storage (in bytes)
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual long total_space
{
get { return _total_space; }
set
{
if (!Helper.AreEqual(value, _total_space))
{
_total_space = value;
NotifyPropertyChanged("total_space");
}
}
}
private long _total_space;
/// <summary>
/// Indicates whether the SR uses clustered local storage.
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual bool clustered
{
get { return _clustered; }
set
{
if (!Helper.AreEqual(value, _clustered))
{
_clustered = value;
NotifyPropertyChanged("clustered");
}
}
}
private bool _clustered;
/// <summary>
/// The health status of the SR.
/// Experimental. First published in XenServer 7.5.
/// </summary>
[JsonConverter(typeof(sr_healthConverter))]
public virtual sr_health health
{
get { return _health; }
set
{
if (!Helper.AreEqual(value, _health))
{
_health = value;
NotifyPropertyChanged("health");
}
}
}
private sr_health _health;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0.
// See THIRD-PARTY-NOTICES.TXT in the project root for license information.
using System.Diagnostics;
namespace System.Net.Http.HPack
{
internal static class HPackEncoder
{
// Things we should add:
// * Huffman encoding
//
// Things we should consider adding:
// * Dynamic table encoding:
// This would make the encoder stateful, which complicates things significantly.
// Additionally, it's not clear exactly what strings we would add to the dynamic table
// without some additional guidance from the user about this.
// So for now, don't do dynamic encoding.
/// <summary>Encodes an "Indexed Header Field".</summary>
public static bool EncodeIndexedHeaderField(int index, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-6.1
// ----------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 1 | Index (7+) |
// +---+---------------------------+
if (destination.Length != 0)
{
destination[0] = 0x80;
return IntegerEncoder.Encode(index, 7, destination, out bytesWritten);
}
bytesWritten = 0;
return false;
}
/// <summary>Encodes a "Literal Header Field without Indexing".</summary>
public static bool EncodeLiteralHeaderFieldWithoutIndexing(int index, string value, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-6.2.2
// ------------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 0 | 0 | Index (4+) |
// +---+---+-----------------------+
// | H | Value Length (7+) |
// +---+---------------------------+
// | Value String (Length octets) |
// +-------------------------------+
if ((uint)destination.Length >= 2)
{
destination[0] = 0;
if (IntegerEncoder.Encode(index, 4, destination, out int indexLength))
{
Debug.Assert(indexLength >= 1);
if (EncodeStringLiteral(value, destination.Slice(indexLength), out int nameLength))
{
bytesWritten = indexLength + nameLength;
return true;
}
}
}
bytesWritten = 0;
return false;
}
/// <summary>
/// Encodes a "Literal Header Field without Indexing", but only the index portion;
/// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value.
/// </summary>
public static bool EncodeLiteralHeaderFieldWithoutIndexing(int index, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-6.2.2
// ------------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 0 | 0 | Index (4+) |
// +---+---+-----------------------+
//
// ... expected after this:
//
// | H | Value Length (7+) |
// +---+---------------------------+
// | Value String (Length octets) |
// +-------------------------------+
if ((uint)destination.Length != 0)
{
destination[0] = 0;
if (IntegerEncoder.Encode(index, 4, destination, out int indexLength))
{
Debug.Assert(indexLength >= 1);
bytesWritten = indexLength;
return true;
}
}
bytesWritten = 0;
return false;
}
/// <summary>Encodes a "Literal Header Field without Indexing - New Name".</summary>
public static bool EncodeLiteralHeaderFieldWithoutIndexingNewName(string name, string[] values, string separator, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-6.2.2
// ------------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 0 | 0 | 0 |
// +---+---+-----------------------+
// | H | Name Length (7+) |
// +---+---------------------------+
// | Name String (Length octets) |
// +---+---------------------------+
// | H | Value Length (7+) |
// +---+---------------------------+
// | Value String (Length octets) |
// +-------------------------------+
if ((uint)destination.Length >= 3)
{
destination[0] = 0;
if (EncodeLiteralHeaderName(name, destination.Slice(1), out int nameLength) &&
EncodeStringLiterals(values, separator, destination.Slice(1 + nameLength), out int valueLength))
{
bytesWritten = 1 + nameLength + valueLength;
return true;
}
}
bytesWritten = 0;
return false;
}
/// <summary>
/// Encodes a "Literal Header Field without Indexing - New Name", but only the name portion;
/// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value.
/// </summary>
public static bool EncodeLiteralHeaderFieldWithoutIndexingNewName(string name, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-6.2.2
// ------------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 0 | 0 | 0 |
// +---+---+-----------------------+
// | H | Name Length (7+) |
// +---+---------------------------+
// | Name String (Length octets) |
// +---+---------------------------+
//
// ... expected after this:
//
// | H | Value Length (7+) |
// +---+---------------------------+
// | Value String (Length octets) |
// +-------------------------------+
if ((uint)destination.Length >= 2)
{
destination[0] = 0;
if (EncodeLiteralHeaderName(name, destination.Slice(1), out int nameLength))
{
bytesWritten = 1 + nameLength;
return true;
}
}
bytesWritten = 0;
return false;
}
private static bool EncodeLiteralHeaderName(string value, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-5.2
// ------------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | H | String Length (7+) |
// +---+---------------------------+
// | String Data (Length octets) |
// +-------------------------------+
if (destination.Length != 0)
{
destination[0] = 0; // TODO: Use Huffman encoding
if (IntegerEncoder.Encode(value.Length, 7, destination, out int integerLength))
{
Debug.Assert(integerLength >= 1);
destination = destination.Slice(integerLength);
if (value.Length <= destination.Length)
{
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
destination[i] = (byte)((uint)(c - 'A') <= ('Z' - 'A') ? c | 0x20 : c);
}
bytesWritten = integerLength + value.Length;
return true;
}
}
}
bytesWritten = 0;
return false;
}
private static bool EncodeStringLiteralValue(string value, Span<byte> destination, out int bytesWritten)
{
if (value.Length <= destination.Length)
{
int mask = StaticHttpSettings.EncodingValidationMask;
for (int i = 0; i < value.Length; i++)
{
int c = value[i];
if ((c & mask) != 0)
{
throw new HttpRequestException(SR.net_http_request_invalid_char_encoding);
}
destination[i] = (byte)c;
}
bytesWritten = value.Length;
return true;
}
bytesWritten = 0;
return false;
}
public static bool EncodeStringLiteral(string value, Span<byte> destination, out int bytesWritten)
{
// From https://tools.ietf.org/html/rfc7541#section-5.2
// ------------------------------------------------------
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | H | String Length (7+) |
// +---+---------------------------+
// | String Data (Length octets) |
// +-------------------------------+
if (destination.Length != 0)
{
destination[0] = 0; // TODO: Use Huffman encoding
if (IntegerEncoder.Encode(value.Length, 7, destination, out int integerLength))
{
Debug.Assert(integerLength >= 1);
if (EncodeStringLiteralValue(value, destination.Slice(integerLength), out int valueLength))
{
bytesWritten = integerLength + valueLength;
return true;
}
}
}
bytesWritten = 0;
return false;
}
public static bool EncodeStringLiterals(string[] values, string separator, Span<byte> destination, out int bytesWritten)
{
bytesWritten = 0;
if (values.Length == 0)
{
return EncodeStringLiteral("", destination, out bytesWritten);
}
else if (values.Length == 1)
{
return EncodeStringLiteral(values[0], destination, out bytesWritten);
}
if (destination.Length != 0)
{
int valueLength = 0;
// Calculate length of all parts and separators.
foreach (string part in values)
{
valueLength = checked((int)(valueLength + part.Length));
}
valueLength = checked((int)(valueLength + (values.Length - 1) * separator.Length));
destination[0] = 0;
if (IntegerEncoder.Encode(valueLength, 7, destination, out int integerLength))
{
Debug.Assert(integerLength >= 1);
int encodedLength = 0;
for (int j = 0; j < values.Length; j++)
{
if (j != 0 && !EncodeStringLiteralValue(separator, destination.Slice(integerLength), out encodedLength))
{
return false;
}
integerLength += encodedLength;
if (!EncodeStringLiteralValue(values[j], destination.Slice(integerLength), out encodedLength))
{
return false;
}
integerLength += encodedLength;
}
bytesWritten = integerLength;
return true;
}
}
return false;
}
/// <summary>
/// Encodes a "Literal Header Field without Indexing" to a new array, but only the index portion;
/// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value.
/// </summary>
public static byte[] EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(int index)
{
Span<byte> span = stackalloc byte[256];
bool success = EncodeLiteralHeaderFieldWithoutIndexing(index, span, out int length);
Debug.Assert(success, $"Stack-allocated space was too small for index '{index}'.");
return span.Slice(0, length).ToArray();
}
/// <summary>
/// Encodes a "Literal Header Field without Indexing - New Name" to a new array, but only the name portion;
/// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value.
/// </summary>
public static byte[] EncodeLiteralHeaderFieldWithoutIndexingNewNameToAllocatedArray(string name)
{
Span<byte> span = stackalloc byte[256];
bool success = EncodeLiteralHeaderFieldWithoutIndexingNewName(name, span, out int length);
Debug.Assert(success, $"Stack-allocated space was too small for \"{name}\".");
return span.Slice(0, length).ToArray();
}
/// <summary>Encodes a "Literal Header Field without Indexing" to a new array.</summary>
public static byte[] EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(int index, string value)
{
Span<byte> span =
#if DEBUG
stackalloc byte[4]; // to validate growth algorithm
#else
stackalloc byte[512];
#endif
while (true)
{
if (EncodeLiteralHeaderFieldWithoutIndexing(index, value, span, out int length))
{
return span.Slice(0, length).ToArray();
}
// This is a rare path, only used once per HTTP/2 connection and only
// for very long host names. Just allocate rather than complicate
// the code with ArrayPool usage. In practice we should never hit this,
// as hostnames should be <= 255 characters.
span = new byte[span.Length * 2];
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SecureWebSocketServerTests.cs" company="Reimers.dk">
// The MIT License
// Copyright (c) 2012-2014 sta.blockhead
// Copyright (c) 2014 Reimers.dk
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary>
// Defines the SecureWebSocketServerTests type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace WebSocketSharp.Tests
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using WebSocketSharp.Net;
using WebSocketSharp.Server;
public sealed class SecureWebSocketServerTests
{
public class GivenASecureWebSocketServer
{
private WebSocketServer _sut;
[SetUp]
public void Setup()
{
var cert = GetRandomCertificate();
var serverSslConfiguration = new ServerSslConfiguration(
cert,
true,
SslProtocols.Tls,
clientCertificateValidationCallback: (sender, certificate, chain, errors) => true);
_sut = new WebSocketServer(port: 443, certificate: serverSslConfiguration);
_sut.AddWebSocketService<TestEchoService>("/echo");
_sut.AddWebSocketService<TestRadioService>("/radio");
_sut.Start();
}
[TearDown]
public Task Teardown()
{
return _sut.Stop();
}
[Test]
public void CanGetDefinedPort()
{
Assert.AreEqual(443, _sut.Port);
}
[Test]
public async Task ClientCanConnectToServer()
{
var clientSslConfiguration = new ClientSslConfiguration(
"localhost",
clientCertificates: new X509Certificate2Collection(GetRandomCertificate()),
enabledSslProtocols: SslProtocols.Tls,
certificateValidationCallback: (sender, certificate, chain, errors) => true);
using (var client = new WebSocket("wss://localhost:443/echo", sslAuthConfiguration: clientSslConfiguration))
{
await client.Connect().ConfigureAwait(false);
Assert.AreEqual(WebSocketState.Open, client.ReadyState);
}
}
[Test]
public async Task WhenClientSendsTextMessageThenResponds()
{
const string Message = "Message";
var waitHandle = new ManualResetEventSlim(false);
var clientSslConfiguration = new ClientSslConfiguration("localhost", certificateValidationCallback: (sender, certificate, chain, errors) => true);
Func<MessageEventArgs, Task> onMessage = e =>
{
if (e.Text.ReadToEnd() == Message)
{
waitHandle.Set();
}
return AsyncEx.Completed();
};
using (var client = new WebSocket("wss://localhost:443/echo", sslAuthConfiguration: clientSslConfiguration, onMessage: onMessage))
{
await client.Connect().ConfigureAwait(false);
await client.Send(Message).ConfigureAwait(false);
var result = waitHandle.Wait(Debugger.IsAttached ? 30000 : 2000);
Assert.True(result);
}
}
[Test]
public async Task WhenClientSendsMultipleTextMessageThenResponds([Random(1, 100, 10)]int multiplicity)
{
int count = 0;
const string Message = "Message";
var waitHandle = new ManualResetEventSlim(false);
var clientSslConfiguration = new ClientSslConfiguration("localhost", certificateValidationCallback: (sender, certificate, chain, errors) => true);
Func<MessageEventArgs, Task> onMessage = async e =>
{
if (await e.Text.ReadToEndAsync().ConfigureAwait(false) == Message)
{
if (Interlocked.Increment(ref count) == multiplicity)
{
waitHandle.Set();
}
}
};
using (var client = new WebSocket("wss://localhost:443/echo", sslAuthConfiguration: clientSslConfiguration, onMessage: onMessage))
{
await client.Connect().ConfigureAwait(false);
for (int i = 0; i < multiplicity; i++)
{
await client.Send(Message).ConfigureAwait(false);
}
var result = waitHandle.Wait(Debugger.IsAttached ? 30000 : 5000);
Assert.True(result);
}
}
[Test]
public async Task WhenStreamVeryLargeStreamToServerThenResponds()
{
var responseLength = 0;
const int Length = 1000000;
var stream = new EnumerableStream(Enumerable.Repeat((byte)123, Length));
var waitHandle = new ManualResetEventSlim(false);
var clientSslConfiguration = new ClientSslConfiguration("localhost", certificateValidationCallback: (sender, certificate, chain, errors) => true);
Func<MessageEventArgs, Task> onMessage = async e =>
{
var bytes = await e.Data.ReadBytes(Length).ConfigureAwait(false);
responseLength = bytes.Count(x => x == 123);
waitHandle.Set();
};
using (var client = new WebSocket("wss://localhost:443/echo", sslAuthConfiguration: clientSslConfiguration, onMessage: onMessage))
{
await client.Connect().ConfigureAwait(false);
await client.Send(stream).ConfigureAwait(false);
var result = waitHandle.Wait(Debugger.IsAttached ? -1 : 30000);
Assert.AreEqual(Length, responseLength);
}
}
[Test]
[Timeout(30000)]
public async Task WhenStreamVeryLargeStreamToServerThenBroadcasts()
{
var responseLength = 0;
const int Length = 1000000;
var stream = new EnumerableStream(Enumerable.Repeat((byte)123, Length));
var waitHandle = new ManualResetEventSlim(false);
var clientSslConfiguration = new ClientSslConfiguration("localhost", certificateValidationCallback: (sender, certificate, chain, errors) => true);
Func<MessageEventArgs, Task> onMessage = async e =>
{
var bytes = await e.Data.ReadBytes(Length).ConfigureAwait(false);
responseLength = bytes.Count(x => x == 123);
waitHandle.Set();
};
using (var sender = new WebSocket("wss://localhost:443/radio", sslAuthConfiguration: clientSslConfiguration))
{
using (var client = new WebSocket("wss://localhost:443/radio", sslAuthConfiguration: clientSslConfiguration, onMessage: onMessage))
{
await sender.Connect().ConfigureAwait(false);
await client.Connect().ConfigureAwait(false);
await sender.Send(stream).ConfigureAwait(false);
waitHandle.Wait();
Assert.AreEqual(Length, responseLength);
}
}
}
private static X509Certificate2 GetRandomCertificate()
{
var st = new X509Store(StoreName.My, StoreLocation.LocalMachine);
st.Open(OpenFlags.ReadOnly);
try
{
var certCollection = st.Certificates;
return certCollection.Count == 0 ? null : certCollection[0];
}
finally
{
st.Close();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.IO;
using NodeDefinition;
using Pathfinding;
using Particles2DPipelineSample;
using System.Globalization;
namespace HackPrototype
{
abstract class HackGameBoardEventTrigger
{
public HackGameBoardEventTrigger(string triggerdatastring) { }
public abstract bool Update(GameTime time, HackGameBoard board);
}
class HackGameBoardEventTrigger_Timed : HackGameBoardEventTrigger
{
float timeremainingseconds;
public HackGameBoardEventTrigger_Timed(string triggerdatastring)
: base(triggerdatastring)
{
timeremainingseconds = HackGameBoardEvent.TryParseTime(triggerdatastring);
}
public HackGameBoardEventTrigger_Timed(float seconds)
: base("0:00.0")
{
timeremainingseconds = seconds;
}
public override bool Update(GameTime time, HackGameBoard board)
{
if (timeremainingseconds > 0)
{
timeremainingseconds -= (float)time.ElapsedGameTime.TotalSeconds;
if (timeremainingseconds <= 0)
{
return true;
}
else
{
return false;
}
}
return true;
}
}
class HackGameBoardEventTrigger_PlayerScore : HackGameBoardEventTrigger
{
UInt64 targetscore;
public HackGameBoardEventTrigger_PlayerScore(string triggerdatastring)
: base(triggerdatastring)
{
bool success = UInt64.TryParse(triggerdatastring, out targetscore);
if (!success)
{
throw new InvalidOperationException("HackGameBoardEventTrigger_PlayerScore got a badly-formatted trigger string.");
}
}
public override bool Update(GameTime time, HackGameBoard board)
{
if (board.GetScore() >= targetscore)
return true;
return false;
}
}
abstract class HackGameBoardEvent
{
public enum HackGameBoardEvent_Type
{
HackGameBoardEvent_Type_ThrowText, //0
HackGameBoardEvent_Type_SpawnAI, //1
HackGameBoardEvent_Type_RaiseAlertLevel, //2
HackGameBoardEvent_Type_OpenExit, //3
HackGameBoardEvent_Type_SpawnPlayer, //4
HackGameBoardEvent_Type_CameraSnap, //5
HackGameBoardEvent_Type_CameraLerp, //6
HackGameBoardEvent_Type_BeginCollapse, //7
HackGameBoardEvent_Type_SetSpeed //8
}
HackGameBoardEvent_Type type;
HackGameBoardEventTrigger trigger;
public HackGameBoardEvent(HackGameBoardEvent_Type eventtype, string typedatastring, HackGameBoardEventTrigger eventtrigger) { type = eventtype; trigger = eventtrigger; }
public bool Update(GameTime time, HackGameBoard board)
{
return (trigger.Update(time, board));
}
public HackGameBoardEvent_Type GetEventType()
{
return type;
}
public static float TryParseTime(string datastring)
{
//xx:yy.zz
char[] delims = { ':', '.' };
string[] bits = datastring.Split(delims, StringSplitOptions.RemoveEmptyEntries);
if (bits.Length < 3)
{
throw new InvalidOperationException("HackGameBoardEvent_TryParseTime got a badly-formatted typedata string.");
}
return ((float)(int.Parse(bits[0])) * 60.0f) + ((float)(int.Parse(bits[1]))) + ((float)(int.Parse(bits[2])) * 0.01f);
}
public static Point TryParsePoint(string datastring)
{
Point retpoint = new Point();
//xx:yy.zz
char[] delims = { ',' };
string[] bits = datastring.Split(delims, StringSplitOptions.RemoveEmptyEntries);
if (bits.Length != 2)
{
throw new InvalidOperationException("HackGameBoardEvent_TryParsePoint got a badly-formatted typedata string.");
}
CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.NumberDecimalSeparator = ".";
ci.NumberFormat.NumberGroupSeparator = ",";
retpoint.X = int.Parse(bits[0],ci);
retpoint.Y = int.Parse(bits[1],ci);
return retpoint;
}
public static Vector3 TryParseVector3(string datastring)
{
Vector3 retpoint = new Vector3();
//xx:yy.zz
char[] delims = { ',' };
string[] bits = datastring.Split(delims, StringSplitOptions.RemoveEmptyEntries);
if (bits.Length != 3)
{
throw new InvalidOperationException("HackGameBoardEvent_TryParseVector3 got a badly-formatted typedata string.");
}
CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.NumberDecimalSeparator = ".";
ci.NumberFormat.NumberGroupSeparator = ",";
retpoint.X = float.Parse(bits[0], ci);
retpoint.Y = float.Parse(bits[1], ci);
retpoint.Z = float.Parse(bits[2], ci);
/*
retpoint.X = float.Parse(bits[0]);
retpoint.Y = float.Parse(bits[1]);
retpoint.Z = float.Parse(bits[2]);
* */
return retpoint;
}
}
class HackGameBoardEvent_CameraSnap : HackGameBoardEvent
{
Point location;
float zoom;
public HackGameBoardEvent_CameraSnap(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_CameraSnap, typedatastring, trigger)
{
Vector3 parsed = TryParseVector3(typedatastring);
location.X = (int)parsed.X;
location.Y = (int)parsed.Y;
zoom = parsed.Z;
}
public Point GetSnapToElement()
{
return location;
}
public float GetSnapToZoom()
{
return zoom;
}
}
class HackGameBoardEvent_CameraLerp : HackGameBoardEvent
{
Point location;
float zoom;
public HackGameBoardEvent_CameraLerp(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_CameraLerp, typedatastring, trigger)
{
Vector3 parsed = TryParseVector3(typedatastring);
location.X = (int)parsed.X;
location.Y = (int)parsed.Y;
zoom = parsed.Z;
}
public Point GetLerpToElement()
{
return location;
}
public float GetLerpToZoom()
{
return zoom;
}
}
class HackGameBoardEvent_SpawnPlayer : HackGameBoardEvent
{
Point location;
public HackGameBoardEvent_SpawnPlayer(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_SpawnPlayer, typedatastring, trigger)
{
location = TryParsePoint(typedatastring);
}
public Point GetPlayerPosition()
{
return location;
}
}
class HackGameBoardEvent_ThrowText : HackGameBoardEvent
{
string textToThrow;
public HackGameBoardEvent_ThrowText(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_ThrowText, typedatastring, trigger)
{
textToThrow = typedatastring;
}
public string GetText()
{
return textToThrow;
}
}
class HackGameBoardEvent_SpawnAI : HackGameBoardEvent
{
public HackGameBoardEvent_SpawnAI(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_SpawnAI, typedatastring, trigger)
{
}
}
class HackGameBoardEvent_RaiseAlertLevel : HackGameBoardEvent
{
public HackGameBoardEvent_RaiseAlertLevel(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_RaiseAlertLevel, typedatastring, trigger)
{
}
}
class HackGameBoardEvent_OpenExit : HackGameBoardEvent
{
Point location;
public HackGameBoardEvent_OpenExit(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_OpenExit, typedatastring, trigger)
{
location = TryParsePoint(typedatastring);
}
public Point GetExitLocation()
{
return location;
}
}
class HackGameBoardEvent_BeginCollapse : HackGameBoardEvent
{
float timeToCollapse;
public HackGameBoardEvent_BeginCollapse(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_BeginCollapse, typedatastring, trigger)
{
timeToCollapse = TryParseTime(typedatastring);
}
public float GetTimeToCollapse()
{
return timeToCollapse;
}
}
class HackGameBoardEvent_SetSpeed : HackGameBoardEvent
{
float speedFactor;
public HackGameBoardEvent_SetSpeed(string typedatastring, HackGameBoardEventTrigger trigger)
: base(HackGameBoardEvent_Type.HackGameBoardEvent_Type_SetSpeed, typedatastring, trigger)
{
speedFactor = float.Parse(typedatastring);
}
public float GetSpeedFactor()
{
return speedFactor;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CSharp.RuntimeBinder.Errors
{
internal static class ErrorFacts
{
public static string GetMessage(ErrorCode code)
{
string codeStr;
switch (code)
{
case ErrorCode.ERR_BadBinaryOps:
codeStr = SR.BadBinaryOps;
break;
case ErrorCode.ERR_BadIndexLHS:
codeStr = SR.BadIndexLHS;
break;
case ErrorCode.ERR_BadIndexCount:
codeStr = SR.BadIndexCount;
break;
case ErrorCode.ERR_BadUnaryOp:
codeStr = SR.BadUnaryOp;
break;
case ErrorCode.ERR_NoImplicitConv:
codeStr = SR.NoImplicitConv;
break;
case ErrorCode.ERR_NoExplicitConv:
codeStr = SR.NoExplicitConv;
break;
case ErrorCode.ERR_ConstOutOfRange:
codeStr = SR.ConstOutOfRange;
break;
case ErrorCode.ERR_AmbigBinaryOps:
codeStr = SR.AmbigBinaryOps;
break;
case ErrorCode.ERR_AmbigUnaryOp:
codeStr = SR.AmbigUnaryOp;
break;
case ErrorCode.ERR_ValueCantBeNull:
codeStr = SR.ValueCantBeNull;
break;
case ErrorCode.ERR_NoSuchMember:
codeStr = SR.NoSuchMember;
break;
case ErrorCode.ERR_ObjectRequired:
codeStr = SR.ObjectRequired;
break;
case ErrorCode.ERR_AmbigCall:
codeStr = SR.AmbigCall;
break;
case ErrorCode.ERR_BadAccess:
codeStr = SR.BadAccess;
break;
case ErrorCode.ERR_AssgLvalueExpected:
codeStr = SR.AssgLvalueExpected;
break;
case ErrorCode.ERR_NoConstructors:
codeStr = SR.NoConstructors;
break;
case ErrorCode.ERR_PropertyLacksGet:
codeStr = SR.PropertyLacksGet;
break;
case ErrorCode.ERR_ObjectProhibited:
codeStr = SR.ObjectProhibited;
break;
case ErrorCode.ERR_AssgReadonly:
codeStr = SR.AssgReadonly;
break;
case ErrorCode.ERR_AssgReadonlyStatic:
codeStr = SR.AssgReadonlyStatic;
break;
case ErrorCode.ERR_AssgReadonlyProp:
codeStr = SR.AssgReadonlyProp;
break;
case ErrorCode.ERR_UnsafeNeeded:
codeStr = SR.UnsafeNeeded;
break;
case ErrorCode.ERR_BadBoolOp:
codeStr = SR.BadBoolOp;
break;
case ErrorCode.ERR_MustHaveOpTF:
codeStr = SR.MustHaveOpTF;
break;
case ErrorCode.ERR_ConstOutOfRangeChecked:
codeStr = SR.ConstOutOfRangeChecked;
break;
case ErrorCode.ERR_AmbigMember:
codeStr = SR.AmbigMember;
break;
case ErrorCode.ERR_NoImplicitConvCast:
codeStr = SR.NoImplicitConvCast;
break;
case ErrorCode.ERR_InaccessibleGetter:
codeStr = SR.InaccessibleGetter;
break;
case ErrorCode.ERR_InaccessibleSetter:
codeStr = SR.InaccessibleSetter;
break;
case ErrorCode.ERR_BadArity:
codeStr = SR.BadArity;
break;
case ErrorCode.ERR_TypeArgsNotAllowed:
codeStr = SR.TypeArgsNotAllowed;
break;
case ErrorCode.ERR_HasNoTypeVars:
codeStr = SR.HasNoTypeVars;
break;
case ErrorCode.ERR_NewConstraintNotSatisfied:
codeStr = SR.NewConstraintNotSatisfied;
break;
case ErrorCode.ERR_GenericConstraintNotSatisfiedRefType:
codeStr = SR.GenericConstraintNotSatisfiedRefType;
break;
case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum:
codeStr = SR.GenericConstraintNotSatisfiedNullableEnum;
break;
case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface:
codeStr = SR.GenericConstraintNotSatisfiedNullableInterface;
break;
case ErrorCode.ERR_GenericConstraintNotSatisfiedValType:
codeStr = SR.GenericConstraintNotSatisfiedValType;
break;
case ErrorCode.ERR_CantInferMethTypeArgs:
codeStr = SR.CantInferMethTypeArgs;
break;
case ErrorCode.ERR_RefConstraintNotSatisfied:
codeStr = SR.RefConstraintNotSatisfied;
break;
case ErrorCode.ERR_ValConstraintNotSatisfied:
codeStr = SR.ValConstraintNotSatisfied;
break;
case ErrorCode.ERR_AmbigUDConv:
codeStr = SR.AmbigUDConv;
break;
case ErrorCode.ERR_BindToBogus:
codeStr = SR.BindToBogus;
break;
case ErrorCode.ERR_CantCallSpecialMethod:
codeStr = SR.CantCallSpecialMethod;
break;
case ErrorCode.ERR_ConvertToStaticClass:
codeStr = SR.ConvertToStaticClass;
break;
case ErrorCode.ERR_IncrementLvalueExpected:
codeStr = SR.IncrementLvalueExpected;
break;
case ErrorCode.ERR_BadArgCount:
codeStr = SR.BadArgCount;
break;
case ErrorCode.ERR_BadArgTypes:
codeStr = SR.BadArgTypes;
break;
case ErrorCode.ERR_BadProtectedAccess:
codeStr = SR.BadProtectedAccess;
break;
case ErrorCode.ERR_BindToBogusProp2:
codeStr = SR.BindToBogusProp2;
break;
case ErrorCode.ERR_BindToBogusProp1:
codeStr = SR.BindToBogusProp1;
break;
case ErrorCode.ERR_BadDelArgCount:
codeStr = SR.BadDelArgCount;
break;
case ErrorCode.ERR_BadDelArgTypes:
codeStr = SR.BadDelArgTypes;
break;
case ErrorCode.ERR_BadCtorArgCount:
codeStr = SR.BadCtorArgCount;
break;
case ErrorCode.ERR_NonInvocableMemberCalled:
codeStr = SR.NonInvocableMemberCalled;
break;
case ErrorCode.ERR_BadNamedArgument:
codeStr = SR.BadNamedArgument;
break;
case ErrorCode.ERR_BadNamedArgumentForDelegateInvoke:
codeStr = SR.BadNamedArgumentForDelegateInvoke;
break;
case ErrorCode.ERR_DuplicateNamedArgument:
codeStr = SR.DuplicateNamedArgument;
break;
case ErrorCode.ERR_NamedArgumentUsedInPositional:
codeStr = SR.NamedArgumentUsedInPositional;
break;
case ErrorCode.ERR_BadNonTrailingNamedArgument:
codeStr = SR.BadNonTrailingNamedArgument;
break;
default:
// means missing resources match the code entry
Debug.Fail("Missing resources for the error " + code.ToString());
codeStr = null;
break;
}
return codeStr;
}
public static string GetMessage(MessageID id)
{
string idStr = id.ToString();
return SR.GetResourceString(idStr, idStr);
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/fraction.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Type {
/// <summary>Holder for reflection information generated from google/type/fraction.proto</summary>
public static partial class FractionReflection {
#region Descriptor
/// <summary>File descriptor for google/type/fraction.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FractionReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chpnb29nbGUvdHlwZS9mcmFjdGlvbi5wcm90bxILZ29vZ2xlLnR5cGUiMgoI",
"RnJhY3Rpb24SEQoJbnVtZXJhdG9yGAEgASgDEhMKC2Rlbm9taW5hdG9yGAIg",
"ASgDQmYKD2NvbS5nb29nbGUudHlwZUINRnJhY3Rpb25Qcm90b1ABWjxnb29n",
"bGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3R5cGUvZnJhY3Rp",
"b247ZnJhY3Rpb26iAgNHVFBiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.Fraction), global::Google.Type.Fraction.Parser, new[]{ "Numerator", "Denominator" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Represents a fraction in terms of a numerator divided by a denominator.
/// </summary>
public sealed partial class Fraction : pb::IMessage<Fraction>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Fraction> _parser = new pb::MessageParser<Fraction>(() => new Fraction());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Fraction> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.FractionReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Fraction() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Fraction(Fraction other) : this() {
numerator_ = other.numerator_;
denominator_ = other.denominator_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Fraction Clone() {
return new Fraction(this);
}
/// <summary>Field number for the "numerator" field.</summary>
public const int NumeratorFieldNumber = 1;
private long numerator_;
/// <summary>
/// The numerator in the fraction, e.g. 2 in 2/3.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public long Numerator {
get { return numerator_; }
set {
numerator_ = value;
}
}
/// <summary>Field number for the "denominator" field.</summary>
public const int DenominatorFieldNumber = 2;
private long denominator_;
/// <summary>
/// The value by which the numerator is divided, e.g. 3 in 2/3. Must be
/// positive.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public long Denominator {
get { return denominator_; }
set {
denominator_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Fraction);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Fraction other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Numerator != other.Numerator) return false;
if (Denominator != other.Denominator) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Numerator != 0L) hash ^= Numerator.GetHashCode();
if (Denominator != 0L) hash ^= Denominator.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Numerator != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Numerator);
}
if (Denominator != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Denominator);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Numerator != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Numerator);
}
if (Denominator != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Denominator);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Numerator != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Numerator);
}
if (Denominator != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Denominator);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Fraction other) {
if (other == null) {
return;
}
if (other.Numerator != 0L) {
Numerator = other.Numerator;
}
if (other.Denominator != 0L) {
Denominator = other.Denominator;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Numerator = input.ReadInt64();
break;
}
case 16: {
Denominator = input.ReadInt64();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Numerator = input.ReadInt64();
break;
}
case 16: {
Denominator = input.ReadInt64();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace AudienceNetwork.Editor
{
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using AudienceNetwork;
using UnityEditor;
using UnityEngine;
public class ManifestMod
{
public static string AudienceNetworkPath = Path.Combine(Application.dataPath, "AudienceNetwork/");
public static string AudienceNetworkPluginsPath = Path.Combine(AudienceNetworkPath, "Plugins/");
public static string InterstitialActivityName = "com.facebook.ads.AudienceNetworkActivity";
public static string AndroidPluginPath = Path.Combine(AudienceNetworkPluginsPath, "Android/");
public static string AndroidManifestName = "AndroidManifest.xml";
public static string AndroidManifestPath = Path.Combine(AndroidPluginPath, AndroidManifestName);
public static string FacebookDefaultAndroidManifestPath = Path.Combine(Application.dataPath, "AudienceNetwork/Editor/Android/DefaultAndroidManifest.xml");
public static void GenerateManifest ()
{
var outputFile = ManifestMod.AndroidManifestPath;
// Create containing directory if it does not exist
Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
// only copy over a fresh copy of the AndroidManifest if one does not exist
if (!File.Exists (outputFile)) {
ManifestMod.CreateDefaultAndroidManifest(outputFile);
}
UpdateManifest (outputFile);
}
public static bool CheckManifest()
{
bool result = true;
var outputFile = ManifestMod.AndroidManifestPath;
if (!File.Exists(outputFile))
{
Debug.LogError("An android manifest must be generated for the Audience Network SDK to work. " +
"Go to Tools->Audience Network and press \"Regenerate Android Manifest\"");
return false;
}
XmlDocument doc = new XmlDocument();
doc.Load(outputFile);
if (doc == null)
{
Debug.LogError("Couldn't load " + outputFile);
return false;
}
XmlNode manNode = FindChildNode(doc, "manifest");
XmlNode dict = FindChildNode(manNode, "application");
if (dict == null)
{
Debug.LogError("Error parsing " + outputFile);
return false;
}
XmlElement loginElement;
if (!ManifestMod.TryFindElementWithAndroidName(dict, InterstitialActivityName, out loginElement))
{
Debug.LogError(string.Format("{0} is missing from your android manifest. " +
"Go to Tools->Audience Network and press \"Regenerate Android Manifest\"", InterstitialActivityName));
result = false;
}
return result;
}
public static void UpdateManifest (string fullPath)
{
XmlDocument doc = new XmlDocument ();
doc.Load (fullPath);
if (doc == null) {
Debug.LogError ("Couldn't load " + fullPath);
return;
}
XmlNode manNode = FindChildNode (doc, "manifest");
XmlNode dict = FindChildNode (manNode, "application");
if (dict == null) {
Debug.LogError ("Error parsing " + fullPath);
return;
}
string ns = dict.GetNamespaceOfPrefix ("android");
ManifestMod.AddPermission (doc, manNode, ns, "android.permission.INTERNET");
ManifestMod.AddPermission (doc, manNode, ns, "android.permission.ACCESS_NETWORK_STATE");
var configOptions = new Dictionary<string, string> ();
configOptions.Add ("configChanges", "keyboardHidden|orientation|screenSize");
ManifestMod.AddSimpleActivity (doc, dict, ns, InterstitialActivityName, configOptions);
// Save the document formatted
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter xmlWriter = XmlWriter.Create(fullPath, settings)) {
doc.Save (xmlWriter);
}
}
private static XmlNode FindChildNode (XmlNode parent, string name)
{
XmlNode curr = parent.FirstChild;
while (curr != null) {
if (curr.Name.Equals (name)) {
return curr;
}
curr = curr.NextSibling;
}
return null;
}
private static void SetOrReplaceXmlElement (
XmlNode parent,
XmlElement newElement)
{
string attrNameValue = newElement.GetAttribute ("name");
string elementType = newElement.Name;
XmlElement existingElment;
if (TryFindElementWithAndroidName (parent, attrNameValue, out existingElment, elementType)) {
parent.ReplaceChild (newElement, existingElment);
} else {
parent.AppendChild (newElement);
}
}
private static bool TryFindElementWithAndroidName (
XmlNode parent,
string attrNameValue,
out XmlElement element,
string elementType = "activity")
{
string ns = parent.GetNamespaceOfPrefix ("android");
var curr = parent.FirstChild;
while (curr != null) {
var currXmlElement = curr as XmlElement;
if (currXmlElement != null &&
currXmlElement.Name == elementType &&
currXmlElement.GetAttribute ("name", ns) == attrNameValue) {
element = currXmlElement;
return true;
}
curr = curr.NextSibling;
}
element = null;
return false;
}
private static void AddSimpleActivity (XmlDocument doc,
XmlNode xmlNode,
string ns,
string className,
Dictionary<string, string> customOptions = null,
bool export = false)
{
XmlElement element = CreateActivityElement (doc, ns, className, customOptions, export);
ManifestMod.SetOrReplaceXmlElement (xmlNode, element);
}
private static XmlElement CreateActivityElement (XmlDocument doc,
string ns,
string activityName,
Dictionary<string, string> customOptions = null,
bool exported = false)
{
// <activity android:name="activityName" android:exported="true">
// </activity>
XmlElement activityElement = doc.CreateElement ("activity");
activityElement.SetAttribute ("name", ns, activityName);
if (exported) {
activityElement.SetAttribute ("exported", ns, "true");
}
if (customOptions != null) {
foreach (var key in customOptions.Keys) {
var value = customOptions [key];
activityElement.SetAttribute (key, ns, value);
}
}
return activityElement;
}
private static void AddPermission (XmlDocument doc,
XmlNode xmlNode,
string ns,
string permissionName)
{
XmlElement element = CreatePermissionElement (doc, ns, permissionName);
ManifestMod.SetOrReplaceXmlElement (xmlNode, element);
}
private static XmlElement CreatePermissionElement (XmlDocument doc,
string ns,
string permissionName)
{
// <uses-permission android:name="android.permission.INTERNET" />
// <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
XmlElement activityElement = doc.CreateElement ("uses-permission");
activityElement.SetAttribute ("name", ns, permissionName);
return activityElement;
}
private static void CreateDefaultAndroidManifest(string outputFile)
{
var inputFile = Path.Combine(
EditorApplication.applicationContentsPath,
"PlaybackEngines/androidplayer/AndroidManifest.xml");
if (!File.Exists(inputFile))
{
// Unity moved this file. Try to get it at its new location
inputFile = Path.Combine(
EditorApplication.applicationContentsPath,
"PlaybackEngines/AndroidPlayer/Apk/AndroidManifest.xml");
if (!File.Exists(inputFile))
{
// On Unity 5.3+ we don't have default manifest so use our own
// manifest and warn the user that they may need to modify it manually
inputFile = FacebookDefaultAndroidManifestPath;
Debug.LogWarning(
string.Format(
"No existing android manifest found at '{0}'. Creating a default manifest file",
outputFile));
}
}
File.Copy(inputFile, outputFile);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
#if !JSONNET_XMLDISABLE
using System.Xml;
#endif
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public class JsonTextWriter : JsonWriter
{
private readonly TextWriter _writer;
private Base64Encoder _base64Encoder;
private char _indentChar;
private int _indentation;
private char _quoteChar;
private bool _quoteName;
private Base64Encoder Base64Encoder
{
get
{
if (_base64Encoder == null)
_base64Encoder = new Base64Encoder(_writer);
return _base64Encoder;
}
}
/// <summary>
/// Gets or sets how many IndentChars to write for each level in the hierarchy when <see cref="Formatting"/> is set to <c>Formatting.Indented</c>.
/// </summary>
public int Indentation
{
get { return _indentation; }
set
{
if (value < 0)
throw new ArgumentException("Indentation value must be greater than 0.");
_indentation = value;
}
}
/// <summary>
/// Gets or sets which character to use to quote attribute values.
/// </summary>
public char QuoteChar
{
get { return _quoteChar; }
set
{
if (value != '"' && value != '\'')
throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and "".");
_quoteChar = value;
}
}
/// <summary>
/// Gets or sets which character to use for indenting when <see cref="Formatting"/> is set to <c>Formatting.Indented</c>.
/// </summary>
public char IndentChar
{
get { return _indentChar; }
set { _indentChar = value; }
}
/// <summary>
/// Gets or sets a value indicating whether object names will be surrounded with quotes.
/// </summary>
public bool QuoteName
{
get { return _quoteName; }
set { _quoteName = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <c>TextWriter</c> to write to.</param>
public JsonTextWriter(TextWriter textWriter)
{
if (textWriter == null)
throw new ArgumentNullException("textWriter");
_writer = textWriter;
_quoteChar = '"';
_quoteName = true;
_indentChar = ' ';
_indentation = 2;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public override void Flush()
{
_writer.Flush();
}
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public override void Close()
{
base.Close();
if (CloseOutput && _writer != null)
_writer.Close();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public override void WriteStartObject()
{
base.WriteStartObject();
_writer.Write("{");
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public override void WriteStartArray()
{
base.WriteStartArray();
_writer.Write("[");
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
base.WriteStartConstructor(name);
_writer.Write("new ");
_writer.Write(name);
_writer.Write("(");
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected override void WriteEnd(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
_writer.Write("}");
break;
case JsonToken.EndArray:
_writer.Write("]");
break;
case JsonToken.EndConstructor:
_writer.Write(")");
break;
default:
throw new JsonWriterException("Invalid JsonToken: " + token);
}
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public override void WritePropertyName(string name)
{
base.WritePropertyName(name);
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, name, _quoteChar, _quoteName);
_writer.Write(':');
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected override void WriteIndent()
{
if (Formatting == Formatting.Indented)
{
_writer.Write(Environment.NewLine);
// levels of indentation multiplied by the indent count
int currentIndentCount = Top * _indentation;
for (int i = 0; i < currentIndentCount; i++)
{
_writer.Write(_indentChar);
}
}
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected override void WriteValueDelimiter()
{
_writer.Write(',');
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected override void WriteIndentSpace()
{
_writer.Write(' ');
}
private void WriteValueInternal(string value, JsonToken token)
{
_writer.Write(value);
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public override void WriteNull()
{
base.WriteNull();
WriteValueInternal(JsonConvert.Null, JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public override void WriteUndefined()
{
base.WriteUndefined();
WriteValueInternal(JsonConvert.Undefined, JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
{
base.WriteRaw(json);
_writer.Write(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
{
base.WriteValue(value);
if (value == null)
WriteValueInternal(JsonConvert.Null, JsonToken.Null);
else
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, true);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public override void WriteValue(int value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
//
public override void WriteValue(uint value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public override void WriteValue(long value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
//
public override void WriteValue(ulong value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public override void WriteValue(float value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public override void WriteValue(double value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public override void WriteValue(bool value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public override void WriteValue(short value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
//
public override void WriteValue(ushort value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public override void WriteValue(char value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public override void WriteValue(byte value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
//
public override void WriteValue(sbyte value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public override void WriteValue(decimal value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public override void WriteValue(DateTime value)
{
base.WriteValue(value);
JsonConvert.WriteDateTimeString(_writer, value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public override void WriteValue(byte[] value)
{
base.WriteValue(value);
if (value != null)
{
_writer.Write(_quoteChar);
Base64Encoder.Encode(value, 0, value.Length);
Base64Encoder.Flush();
_writer.Write(_quoteChar);
}
}
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public override void WriteValue(DateTimeOffset value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public override void WriteValue(Guid value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public override void WriteValue(TimeSpan value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Date);
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
base.WriteComment(text);
_writer.Write("/*");
_writer.Write(text);
_writer.Write("*/");
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public override void WriteWhitespace(string ws)
{
base.WriteWhitespace(ws);
_writer.Write(ws);
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.