context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// 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.Linq;
using System.Xml.Linq;
using Xunit;
namespace CoreXml.Test.XLinq.FunctionalTests.EventsTests
{
public class EventsXElementName
{
public static object[][] ExecuteXElementVariationParams = new object[][] {
new object[] { new XElement("element"), (XName)"newName" },
new object[] { new XElement("parent", new XElement("child", "child text")), (XName)"{b}newName" },
};
[Theory, MemberData(nameof(ExecuteXElementVariationParams))]
public void ExecuteXElementVariation(XElement toChange, XName newName)
{
XElement original = new XElement(toChange);
using (UndoManager undo = new UndoManager(toChange))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(toChange))
{
toChange.Name = newName;
Assert.True(newName.Namespace == toChange.Name.Namespace, "Namespace did not change");
Assert.True(newName.LocalName == toChange.Name.LocalName, "LocalName did not change");
eHelper.Verify(XObjectChange.Name, toChange);
}
undo.Undo();
Assert.True(XNode.DeepEquals(toChange, original), "Undo did not work");
}
}
[Fact]
public void XProcessingInstructionPIVariation()
{
XProcessingInstruction toChange = new XProcessingInstruction("target", "data");
XProcessingInstruction original = new XProcessingInstruction(toChange);
using (UndoManager undo = new UndoManager(toChange))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(toChange))
{
toChange.Target = "newTarget";
Assert.True(toChange.Target.Equals("newTarget"), "Name did not change");
eHelper.Verify(XObjectChange.Name, toChange);
}
undo.Undo();
Assert.True(XNode.DeepEquals(toChange, original), "Undo did not work");
}
}
[Fact]
public void XDocumentTypeDocTypeVariation()
{
XDocumentType toChange = new XDocumentType("root", "", "", "");
XDocumentType original = new XDocumentType(toChange);
using (EventsHelper eHelper = new EventsHelper(toChange))
{
toChange.Name = "newName";
Assert.True(toChange.Name.Equals("newName"), "Name did not change");
eHelper.Verify(XObjectChange.Name, toChange);
}
}
}
public class EventsSpecialCases
{
private static void ChangingDelegate(object sender, XObjectChangeEventArgs e) { }
private static void ChangedDelegate(object sender, XObjectChangeEventArgs e) { }
[Fact]
public void AddingRemovingNullListenersXElementRemoveNullEventListner()
{
XDocument xDoc = new XDocument(InputSpace.GetElement(10, 10));
EventHandler<XObjectChangeEventArgs> d1 = ChangingDelegate;
EventHandler<XObjectChangeEventArgs> d2 = ChangedDelegate;
//Add null first, this should add nothing
xDoc.Changing += null;
xDoc.Changed += null;
//Add the actual delegate
xDoc.Changing += new EventHandler<XObjectChangeEventArgs>(d1);
xDoc.Changed += new EventHandler<XObjectChangeEventArgs>(d2);
//Now set it to null
d1 = null;
d2 = null;
xDoc.Root.Add(new XComment("This is a comment"));
//Remove nulls
xDoc.Changing -= null;
xDoc.Changed -= null;
//Try removing the originally added delegates
d1 = ChangingDelegate;
d2 = ChangedDelegate;
xDoc.Changing -= new EventHandler<XObjectChangeEventArgs>(d1);
xDoc.Changed -= new EventHandler<XObjectChangeEventArgs>(d2);
}
[Fact]
public void RemoveBothEventListenersXElementRemoveBothEventListners()
{
XDocument xDoc = new XDocument(InputSpace.GetElement(10, 10));
EventHandler<XObjectChangeEventArgs> d1 = ChangingDelegate;
EventHandler<XObjectChangeEventArgs> d2 = ChangedDelegate;
xDoc.Changing += new EventHandler<XObjectChangeEventArgs>(d1);
xDoc.Changed += new EventHandler<XObjectChangeEventArgs>(d2);
xDoc.Root.Add(new XComment("This is a comment"));
xDoc.Changing -= new EventHandler<XObjectChangeEventArgs>(d1);
xDoc.Changed -= new EventHandler<XObjectChangeEventArgs>(d2);
//Remove it again
xDoc.Changing -= new EventHandler<XObjectChangeEventArgs>(d1);
xDoc.Changed -= new EventHandler<XObjectChangeEventArgs>(d2);
//Change the order
xDoc.Changed += new EventHandler<XObjectChangeEventArgs>(d2);
xDoc.Changing += new EventHandler<XObjectChangeEventArgs>(d1);
xDoc.Root.Add(new XComment("This is a comment"));
xDoc.Changed -= new EventHandler<XObjectChangeEventArgs>(d2);
xDoc.Changing -= new EventHandler<XObjectChangeEventArgs>(d1);
//Remove it again
xDoc.Changed -= new EventHandler<XObjectChangeEventArgs>(d2);
xDoc.Changing -= new EventHandler<XObjectChangeEventArgs>(d1);
}
[Fact]
public void AddChangedListnerInPreEventAddListnerInPreEvent()
{
XElement element = XElement.Parse("<root></root>");
element.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
element.Changed += new EventHandler<XObjectChangeEventArgs>(ChangedDelegate);
});
element.Add(new XElement("Add", "Me"));
element.Verify();
Assert.True(element.Element("Add") != null, "Did not add the element");
}
[Fact]
public void AddAndRemoveEventListnersXElementAddRemoveEventListners()
{
XDocument xDoc = new XDocument(InputSpace.GetElement(10, 10));
EventsHelper docHelper = new EventsHelper(xDoc);
EventsHelper eHelper = new EventsHelper(xDoc.Root);
xDoc.Root.Add(new XElement("Add", "Me"));
docHelper.Verify(XObjectChange.Add);
eHelper.Verify(XObjectChange.Add);
eHelper.RemoveListners();
xDoc.Root.Add(new XComment("Comment"));
eHelper.Verify(0);
docHelper.Verify(XObjectChange.Add);
}
[Fact]
public void AttachListnersAtEachLevelNestedElementsXElementAttachAtEachLevel()
{
XDocument xDoc = new XDocument(XElement.Parse(@"<a>a<b>b<c>c<d>c<e>e<f>f</f></e></d></c></b></a>"));
EventsHelper[] listeners = new EventsHelper[xDoc.Descendants().Count()];
int i = 0;
foreach (XElement x in xDoc.Descendants())
listeners[i++] = new EventsHelper(x);
// f element
XElement toChange = xDoc.Descendants().ElementAt(5);
// Add element
toChange.Add(new XElement("Add", "Me"));
foreach (EventsHelper e in listeners)
e.Verify(XObjectChange.Add);
// Add xattribute
toChange.Add(new XAttribute("at", "value"));
foreach (EventsHelper e in listeners)
e.Verify(XObjectChange.Add);
}
[Fact]
public void ExceptionInPREEventHandlerXElementPreException()
{
XDocument xDoc = new XDocument(InputSpace.GetElement(10, 10));
XElement toChange = xDoc.Descendants().ElementAt(5);
xDoc.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
throw new InvalidOperationException("This should be propagated and operation should be aborted");
});
xDoc.Changed += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
// This should never be called
});
Assert.Throws<InvalidOperationException>(() => { toChange.Add(new XElement("Add", "Me")); });
xDoc.Root.Verify();
Assert.Null(toChange.Element("Add"));
}
[Fact]
public void ExceptionInPOSTEventHandlerXElementPostException()
{
XDocument xDoc = new XDocument(InputSpace.GetElement(10, 10));
XElement toChange = xDoc.Descendants().ElementAt(5);
xDoc.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
// Do nothing
});
xDoc.Changed += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
throw new InvalidOperationException("This should be propagated and operation should perform");
});
Assert.Throws<InvalidOperationException>(() => { toChange.Add(new XElement("Add", "Me")); });
xDoc.Root.Verify();
Assert.NotNull(toChange.Element("Add"));
}
}
}
| |
/*
* 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.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.MySQL
{
/// <summary>
/// A MySQL Interface for the Asset Server
/// </summary>
public class MySQLAssetData : AssetDataBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#region IPlugin Members
public override string Version { get { return "1.0.0.0"; } }
/// <summary>
/// <para>Initialises Asset interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the MySQL storage plugin.</item>
/// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string</param>
public override void Initialise(string connect)
{
m_connectionString = connect;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "AssetStore");
m.Update();
}
}
public override void Initialise()
{
throw new NotImplementedException();
}
public override void Dispose() { }
/// <summary>
/// The name of this DB provider
/// </summary>
override public string Name
{
get { return "MySQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset <paramref name="assetID"/> from database
/// </summary>
/// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
override public AssetBase GetAsset(UUID assetID)
{
AssetBase asset = null;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(
"SELECT name, description, assetType, local, temporary, asset_flags, CreatorID, data FROM assets WHERE id=?id",
dbcon))
{
cmd.Parameters.AddWithValue("?id", assetID.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], dbReader["CreatorID"].ToString());
asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"];
string local = dbReader["local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
asset.Local = true;
else
asset.Local = false;
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
}
}
}
catch (Exception e)
{
m_log.Error(
string.Format("[ASSETS DB]: MySql failure fetching asset {0}. Exception ", assetID), e);
}
}
}
return asset;
}
/// <summary>
/// Create an asset in database, or update it if existing.
/// </summary>
/// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
override public bool StoreAsset(AssetBase asset)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
using (MySqlCommand cmd =
new MySqlCommand(
"replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, asset_flags, CreatorID, data)" +
"VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?asset_flags, ?CreatorID, ?data)",
dbcon))
{
try
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?id", asset.ID);
cmd.Parameters.AddWithValue("?name", assetName);
cmd.Parameters.AddWithValue("?description", assetDescription);
cmd.Parameters.AddWithValue("?assetType", asset.Type);
cmd.Parameters.AddWithValue("?local", asset.Local);
cmd.Parameters.AddWithValue("?temporary", asset.Temporary);
cmd.Parameters.AddWithValue("?create_time", now);
cmd.Parameters.AddWithValue("?access_time", now);
cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
cmd.Parameters.AddWithValue("?asset_flags", (int)asset.Flags);
cmd.Parameters.AddWithValue("?data", asset.Data);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
return false;
}
}
}
}
private void UpdateAccessTime(AssetBase asset)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd
= new MySqlCommand("update assets set access_time=?access_time where id=?id", dbcon))
{
try
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?id", asset.ID);
cmd.Parameters.AddWithValue("?access_time", now);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
m_log.Error(
string.Format(
"[ASSETS DB]: Failure updating access_time for asset {0} with name {1}. Exception ",
asset.FullID, asset.Name),
e);
}
}
}
}
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuidss">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public override bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(sql, dbcon))
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
UUID id = DBGuid.FromDB(dbReader["id"]);
exist.Add(id);
}
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd
= new MySqlCommand(
"SELECT name,description,assetType,temporary,id,asset_flags,CreatorID FROM assets LIMIT ?start, ?count",
dbcon))
{
cmd.Parameters.AddWithValue("?start", start);
cmd.Parameters.AddWithValue("?count", count);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.Name = (string)dbReader["name"];
metadata.Description = (string)dbReader["description"];
metadata.Type = (sbyte)dbReader["assetType"];
metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
metadata.FullID = DBGuid.FromDB(dbReader["id"]);
metadata.CreatorID = dbReader["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = new byte[] { };
retList.Add(metadata);
}
}
}
catch (Exception e)
{
m_log.Error(
string.Format(
"[ASSETS DB]: MySql failure fetching asset set from {0}, count {1}. Exception ",
start, count),
e);
}
}
}
return retList;
}
public override bool Delete(string id)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand("delete from assets where id=?id", dbcon))
{
cmd.Parameters.AddWithValue("?id", id);
cmd.ExecuteNonQuery();
}
}
return true;
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Ink.Stroke.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.Windows.Ink
{
public partial class Stroke : System.ComponentModel.INotifyPropertyChanged
{
#region Methods and constructors
public void AddPropertyData(Guid propertyDataId, Object propertyData)
{
}
public virtual new System.Windows.Ink.Stroke Clone()
{
return default(System.Windows.Ink.Stroke);
}
public bool ContainsPropertyData(Guid propertyDataId)
{
return default(bool);
}
public void Draw(System.Windows.Media.DrawingContext drawingContext, DrawingAttributes drawingAttributes)
{
}
public void Draw(System.Windows.Media.DrawingContext context)
{
}
protected virtual new void DrawCore(System.Windows.Media.DrawingContext drawingContext, DrawingAttributes drawingAttributes)
{
}
public System.Windows.Input.StylusPointCollection GetBezierStylusPoints()
{
return default(System.Windows.Input.StylusPointCollection);
}
public virtual new System.Windows.Rect GetBounds()
{
return default(System.Windows.Rect);
}
public StrokeCollection GetClipResult(IEnumerable<System.Windows.Point> lassoPoints)
{
return default(StrokeCollection);
}
public StrokeCollection GetClipResult(System.Windows.Rect bounds)
{
return default(StrokeCollection);
}
public StrokeCollection GetEraseResult(IEnumerable<System.Windows.Point> eraserPath, StylusShape eraserShape)
{
return default(StrokeCollection);
}
public StrokeCollection GetEraseResult(System.Windows.Rect bounds)
{
return default(StrokeCollection);
}
public StrokeCollection GetEraseResult(IEnumerable<System.Windows.Point> lassoPoints)
{
return default(StrokeCollection);
}
public System.Windows.Media.Geometry GetGeometry()
{
return default(System.Windows.Media.Geometry);
}
public System.Windows.Media.Geometry GetGeometry(DrawingAttributes drawingAttributes)
{
return default(System.Windows.Media.Geometry);
}
public Object GetPropertyData(Guid propertyDataId)
{
return default(Object);
}
public Guid[] GetPropertyDataIds()
{
return default(Guid[]);
}
public bool HitTest(System.Windows.Point point)
{
return default(bool);
}
public bool HitTest(IEnumerable<System.Windows.Point> lassoPoints, int percentageWithinLasso)
{
return default(bool);
}
public bool HitTest(System.Windows.Rect bounds, int percentageWithinBounds)
{
return default(bool);
}
public bool HitTest(IEnumerable<System.Windows.Point> path, StylusShape stylusShape)
{
return default(bool);
}
public bool HitTest(System.Windows.Point point, double diameter)
{
return default(bool);
}
protected virtual new void OnDrawingAttributesChanged(PropertyDataChangedEventArgs e)
{
}
protected virtual new void OnDrawingAttributesReplaced(DrawingAttributesReplacedEventArgs e)
{
}
protected virtual new void OnInvalidated(EventArgs e)
{
}
protected virtual new void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e)
{
}
protected virtual new void OnPropertyDataChanged(PropertyDataChangedEventArgs e)
{
}
protected virtual new void OnStylusPointsChanged(EventArgs e)
{
}
protected virtual new void OnStylusPointsReplaced(StylusPointsReplacedEventArgs e)
{
}
public void RemovePropertyData(Guid propertyDataId)
{
}
public Stroke(System.Windows.Input.StylusPointCollection stylusPoints, DrawingAttributes drawingAttributes)
{
}
public Stroke(System.Windows.Input.StylusPointCollection stylusPoints)
{
}
public virtual new void Transform(System.Windows.Media.Matrix transformMatrix, bool applyToStylusTip)
{
}
#endregion
#region Properties and indexers
public DrawingAttributes DrawingAttributes
{
get
{
return default(DrawingAttributes);
}
set
{
}
}
public System.Windows.Input.StylusPointCollection StylusPoints
{
get
{
return default(System.Windows.Input.StylusPointCollection);
}
set
{
}
}
#endregion
#region Events
public event PropertyDataChangedEventHandler DrawingAttributesChanged
{
add
{
}
remove
{
}
}
public event DrawingAttributesReplacedEventHandler DrawingAttributesReplaced
{
add
{
}
remove
{
}
}
public event EventHandler Invalidated
{
add
{
}
remove
{
}
}
event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged
{
add
{
}
remove
{
}
}
public event PropertyDataChangedEventHandler PropertyDataChanged
{
add
{
}
remove
{
}
}
public event EventHandler StylusPointsChanged
{
add
{
}
remove
{
}
}
public event StylusPointsReplacedEventHandler StylusPointsReplaced
{
add
{
}
remove
{
}
}
#endregion
}
}
| |
using Android.App;
using Android.Content;
using Android.Database;
using Android.Provider;
using Plugin.Calendars.Abstractions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Calendar = Plugin.Calendars.Abstractions.Calendar;
#nullable enable
namespace Plugin.Calendars
{
/// <summary>
/// Implementation for Calendars
/// </summary>
public class CalendarsImplementation : ICalendars
{
#region Constants
private static readonly Android.Net.Uri? _calendarsUri = CalendarContract.Calendars.ContentUri;
private static readonly Android.Net.Uri? _eventsUri = CalendarContract.Events.ContentUri;
private static readonly Android.Net.Uri? _remindersUri = CalendarContract.Reminders.ContentUri;
private static readonly string[] _calendarsProjection =
{
CalendarContract.Calendars.InterfaceConsts.Id,
CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName,
CalendarContract.Calendars.InterfaceConsts.CalendarColor,
CalendarContract.Calendars.InterfaceConsts.AccountName,
CalendarContract.Calendars.InterfaceConsts.CalendarAccessLevel,
CalendarContract.Calendars.InterfaceConsts.AccountType
};
#endregion
#region Properties
/// <summary>
/// Gets or sets the name of the account to use for creating/editing calendars.
/// Defaults to application package label.
/// </summary>
/// <value>The name of the account.</value>
public string? AccountName { get; set; }
/// <summary>
/// Gets or sets the owner account to use for creating/editing calendars.
/// Defaults to application package label.
/// </summary>
/// <value>The owner account.</value>
public string? OwnerAccount { get; set; }
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="Plugin.Calendars.CalendarsImplementation"/> class.
/// </summary>
public CalendarsImplementation()
{
AccountName = OwnerAccount = Application.Context.PackageManager != null
? Application.Context.ApplicationInfo?.LoadLabel(Application.Context.PackageManager) : null;
}
#endregion
#region ICalendars implementation
/// <summary>
/// Gets a list of all calendars on the device.
/// </summary>
/// <returns>Calendars</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public Task<IList<Calendar>> GetCalendarsAsync() => Task.Run(() =>
{
var cursor = Query(_calendarsUri, _calendarsProjection);
var calendars = IterateCursor(cursor, () => GetCalendar(cursor));
return calendars;
});
/// <summary>
/// Gets a single calendar by platform-specific ID.
/// </summary>
/// <param name="externalId">Platform-specific calendar identifier</param>
/// <returns>The corresponding calendar, or null if not found</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public Task<Calendar?> GetCalendarByIdAsync(string? externalId)
{
long calendarId = -1;
if (!long.TryParse(externalId, out calendarId))
{
return Task.FromResult<Calendar?>(null);
}
return Task.Run(() =>
{
if (_calendarsUri == null)
{
throw new NullReferenceException(nameof(_calendarsUri));
}
var cursor = Query(
ContentUris.WithAppendedId(_calendarsUri, calendarId),
_calendarsProjection);
var calendar = SingleItemFromCursor(cursor, () => GetCalendar(cursor));
return calendar;
});
}
/// <summary>
/// Gets all events for a calendar within the specified time range.
/// </summary>
/// <param name="calendar">Calendar containing events</param>
/// <param name="start">Start of event range</param>
/// <param name="end">End of event range</param>
/// <returns>Calendar events</returns>
/// <exception cref="System.ArgumentException">Calendar does not exist on device</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<IList<CalendarEvent>> GetEventsAsync(Calendar calendar, DateTime start, DateTime end)
{
var deviceCalendar = await GetCalendarByIdAsync(calendar.ExternalID).ConfigureAwait(false);
if (deviceCalendar == null)
{
throw new ArgumentException("Specified calendar not found on device");
}
var eventsUriBuilder = CalendarContract.Instances.ContentUri!.BuildUpon()!;
// Note that this is slightly different from the GetEventById projection
// due to the Instances API vs. Event API (specifically, IDs and start/end times)
//
string[] eventsProjection =
{
CalendarContract.Events.InterfaceConsts.Title,
CalendarContract.Events.InterfaceConsts.Description,
CalendarContract.Instances.Begin,
CalendarContract.Instances.End,
CalendarContract.Events.InterfaceConsts.AllDay,
CalendarContract.Events.InterfaceConsts.EventLocation,
CalendarContract.Instances.EventId
};
ContentUris.AppendId(eventsUriBuilder, DateConversions.GetDateAsAndroidMS(start));
ContentUris.AppendId(eventsUriBuilder, DateConversions.GetDateAsAndroidMS(end));
var eventsUri = eventsUriBuilder?.Build();
return await Task.Run(() =>
{
var cursor = Query(eventsUri, eventsProjection,
string.Format("{0} = {1}", CalendarContract.Events.InterfaceConsts.CalendarId, calendar.ExternalID),
null, CalendarContract.Events.InterfaceConsts.Dtstart + " ASC");
var events = IterateCursor(cursor, () =>
{
bool allDay = cursor.GetBoolean(CalendarContract.Events.InterfaceConsts.AllDay);
var calendarEvent = new CalendarEvent
{
Name = cursor.GetString(CalendarContract.Events.InterfaceConsts.Title),
ExternalID = cursor.GetString(CalendarContract.Instances.EventId),
Description = cursor.GetString(CalendarContract.Events.InterfaceConsts.Description),
Start = cursor.GetDateTime(CalendarContract.Instances.Begin, allDay),
End = cursor.GetDateTime(CalendarContract.Instances.End, allDay),
Location = cursor.GetString(CalendarContract.Events.InterfaceConsts.EventLocation),
AllDay = allDay
};
calendarEvent.Reminders = GetEventReminders(calendarEvent.ExternalID);
return calendarEvent;
});
return events;
}).ConfigureAwait(false);
}
/// <summary>
/// Gets a single calendar event by platform-specific ID.
/// </summary>
/// <param name="externalId">Platform-specific calendar event identifier</param>
/// <returns>The corresponding calendar event, or null if not found</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public Task<CalendarEvent?> GetEventByIdAsync(string externalId) => Task.Run(() => GetEventById(externalId));
/// <summary>
/// Creates a new calendar or updates the name and color of an existing one.
/// If a new calendar was created, the ExternalID property will be set on the Calendar object,
/// to support future queries/updates.
/// </summary>
/// <param name="calendar">The calendar to create/update</param>
/// <exception cref="System.ArgumentException">Calendar does not exist on device or is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task AddOrUpdateCalendarAsync(Calendar calendar)
{
bool updateExisting = false;
long existingId = -1;
if (long.TryParse(calendar.ExternalID, out existingId))
{
var existingCalendar = await GetCalendarByIdAsync(calendar.ExternalID).ConfigureAwait(false);
if (existingCalendar != null)
{
if (!existingCalendar.CanEditCalendar)
{
throw new ArgumentException("Destination calendar is not writable");
}
updateExisting = true;
}
else
{
throw new ArgumentException("Specified calendar does not exist on device", nameof(calendar));
}
}
var values = new ContentValues();
values.Put(CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName, calendar.Name);
values.Put(CalendarContract.Calendars.Name, calendar.Name);
// Unlike iOS/WinPhone, Android does not automatically assign a color for us,
// so we use our own default of blue.
//
int colorInt = unchecked((int)0xFF0000FF);
// TODO: Remove redundant null check after migrating to .net6
if (calendar.Color != null && !string.IsNullOrEmpty(calendar.Color))
{
int.TryParse(calendar.Color.Trim('#'), NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out colorInt);
}
values.Put(CalendarContract.Calendars.InterfaceConsts.CalendarColor, colorInt);
if (!updateExisting)
{
values.Put(CalendarContract.Calendars.InterfaceConsts.CalendarAccessLevel, (int)CalendarAccess.AccessOwner);
values.Put(CalendarContract.Calendars.InterfaceConsts.AccountName, AccountName);
values.Put(CalendarContract.Calendars.InterfaceConsts.OwnerAccount, OwnerAccount);
values.Put(CalendarContract.Calendars.InterfaceConsts.Visible, true);
values.Put(CalendarContract.Calendars.InterfaceConsts.SyncEvents, true);
values.Put(CalendarContract.Calendars.InterfaceConsts.AccountType, CalendarContract.AccountTypeLocal);
}
await Task.Run(() =>
{
if (updateExisting)
{
Update(_calendarsUri, existingId, values);
}
else
{
var uri = _calendarsUri?.BuildUpon()
?.AppendQueryParameter(CalendarContract.CallerIsSyncadapter, "true")
?.AppendQueryParameter(CalendarContract.Calendars.InterfaceConsts.AccountName, AccountName)
?.AppendQueryParameter(CalendarContract.Calendars.InterfaceConsts.AccountType, CalendarContract.AccountTypeLocal)
?.Build();
calendar.ExternalID = Insert(uri, values);
calendar.CanEditCalendar = true;
calendar.CanEditEvents = true;
calendar.Color = "#" + colorInt.ToString("x8");
}
}).ConfigureAwait(false);
}
/// <summary>
/// Add new event to a calendar or update an existing event.
/// If a new event was added, the ExternalID property will be set on the CalendarEvent object,
/// to support future queries/updates.
/// </summary>
/// <param name="calendar">Destination calendar</param>
/// <param name="calendarEvent">Event to add or update</param>
/// <exception cref="System.ArgumentException">Calendar is not specified, does not exist on device, or is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="System.InvalidOperationException">Editing recurring events is not supported</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task AddOrUpdateEventAsync(Calendar calendar, CalendarEvent calendarEvent)
{
if (string.IsNullOrEmpty(calendar.ExternalID))
{
throw new ArgumentException("Missing calendar identifier", nameof(calendar));
}
else
{
// Verify calendar exists (Android actually allows using a nonexistent calendar ID...)
//
var deviceCalendar = await GetCalendarByIdAsync(calendar.ExternalID).ConfigureAwait(false);
if (deviceCalendar == null)
{
throw new ArgumentException("Specified calendar not found on device");
}
}
// Validate times
if (calendarEvent.End < calendarEvent.Start)
{
throw new ArgumentException("End time may not precede start time", nameof(calendarEvent));
}
bool updateExisting = false;
long existingId = -1;
CalendarEvent? existingEvent = null;
await Task.Run(() =>
{
// TODO: Remove redundant null check after migrating to .net6
if (calendarEvent.ExternalID != null && long.TryParse(calendarEvent.ExternalID, out existingId))
{
if (IsEventRecurring(calendarEvent.ExternalID))
{
throw new InvalidOperationException("Editing recurring events is not supported");
}
var calendarId = GetCalendarIdForEventId(calendarEvent.ExternalID);
if (calendarId.HasValue && calendarId.Value.ToString() == calendar.ExternalID)
{
updateExisting = true;
existingEvent = GetEventById(calendarEvent.ExternalID);
}
}
bool allDay = calendarEvent.AllDay;
var start = allDay
? DateTime.SpecifyKind(calendarEvent.Start.Date, DateTimeKind.Utc)
: calendarEvent.Start;
var end = allDay
? DateTime.SpecifyKind(calendarEvent.End.Date, DateTimeKind.Utc)
: calendarEvent.End;
var eventValues = new ContentValues();
eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId,
calendar.ExternalID);
eventValues.Put(CalendarContract.Events.InterfaceConsts.Title,
calendarEvent.Name);
eventValues.Put(CalendarContract.Events.InterfaceConsts.Description,
calendarEvent.Description);
eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart,
DateConversions.GetDateAsAndroidMS(start));
eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend,
DateConversions.GetDateAsAndroidMS(end));
eventValues.Put(CalendarContract.Events.InterfaceConsts.AllDay,
allDay ? 1 : 0);
eventValues.Put(CalendarContract.Events.InterfaceConsts.EventLocation,
calendarEvent.Location ?? string.Empty);
// If we're updating an existing event, don't mess with the existing
// time zone (since we don't support explicitly setting it yet).
// *Unless* we're toggling the "all day" setting
// (because that would mean the time zone is UTC rather than local...).
//
if (!updateExisting || allDay != existingEvent?.AllDay)
{
eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone,
allDay
? Java.Util.TimeZone.GetTimeZone("UTC")?.ID ?? string.Empty
: Java.Util.TimeZone.Default?.ID ?? string.Empty);
}
if (_eventsUri == null)
{
throw new NullReferenceException(nameof(_eventsUri));
}
var operations = new List<ContentProviderOperation>();
var eventOperation = updateExisting
? ContentProviderOperation.NewUpdate(ContentUris.WithAppendedId(_eventsUri, existingId))
: ContentProviderOperation.NewInsert(_eventsUri);
eventOperation = eventOperation?.WithValues(eventValues);
operations.Add(eventOperation?.Build() ?? throw new NullReferenceException(nameof(eventOperation)));
operations.AddRange(BuildReminderUpdateOperations(calendarEvent.Reminders, existingEvent));
var results = ApplyBatch(operations);
if (!updateExisting)
{
calendarEvent.ExternalID = results[0].Uri?.LastPathSegment;
}
}).ConfigureAwait(false);
}
/// <summary>
/// Adds an event reminder to specified calendar event
/// </summary>
/// <param name="calendarEvent">Event to add the reminder to</param>
/// <param name="reminder">The reminder</param>
/// <exception cref="ArgumentException">Calendar event is not created or not valid</exception>
/// <exception cref="System.InvalidOperationException">Editing recurring events is not supported</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task AddEventReminderAsync(CalendarEvent calendarEvent, CalendarEventReminder reminder)
{
// TODO: Remove redundant null check after migrating to .net6
if (calendarEvent.ExternalID == null || string.IsNullOrEmpty(calendarEvent.ExternalID))
{
throw new ArgumentException("Missing calendar event identifier", nameof(calendarEvent));
}
// Verify calendar event exists
var existingAppt = await GetEventByIdAsync(calendarEvent.ExternalID).ConfigureAwait(false);
if (existingAppt == null)
{
throw new ArgumentException("Specified calendar event not found on device");
}
await Task.Run(() =>
{
if (IsEventRecurring(calendarEvent.ExternalID))
{
throw new InvalidOperationException("Editing recurring events is not supported");
}
Insert(_remindersUri, reminder.ToContentValues(calendarEvent.ExternalID));
}).ConfigureAwait(false);
}
/// <summary>
/// Removes a calendar and all its events from the system.
/// </summary>
/// <param name="calendar">Calendar to delete</param>
/// <returns>True if successfully removed</returns>
/// <exception cref="System.ArgumentException">Calendar is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<bool> DeleteCalendarAsync(Calendar calendar)
{
var existing = await GetCalendarByIdAsync(calendar.ExternalID).ConfigureAwait(false);
if (existing == null)
{
return false;
}
else if (!existing.CanEditCalendar)
{
throw new ArgumentException("Cannot delete calendar (probably because it's non-local)", nameof(calendar));
}
return await Task.Run(() => Delete(_calendarsUri, long.Parse(calendar.ExternalID))).ConfigureAwait(false);
}
/// <summary>
/// Removes an event from the specified calendar.
/// </summary>
/// <param name="calendar">Calendar to remove event from</param>
/// <param name="calendarEvent">Event to remove</param>
/// <returns>True if successfully removed</returns>
/// <exception cref="System.ArgumentException">Calendar is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="System.InvalidOperationException">Editing recurring events is not supported</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<bool> DeleteEventAsync(Calendar calendar, CalendarEvent calendarEvent)
{
long existingId = -1;
// Even though a Calendar was passed-in, we get this to both verify
// that the calendar exists and to make sure we have accurate permissions
// (rather than trusting the permissions that were passed to us...)
//
var existingCal = await GetCalendarByIdAsync(calendar.ExternalID).ConfigureAwait(false);
if (existingCal == null)
{
return false;
}
else if (!existingCal.CanEditEvents)
{
throw new ArgumentException("Cannot delete event from readonly calendar", nameof(calendar));
}
// TODO: Remove redundant null check after migrating to .net6
if (calendarEvent.ExternalID != null && long.TryParse(calendarEvent.ExternalID, out existingId))
{
return await Task.Run(() =>
{
if (IsEventRecurring(calendarEvent.ExternalID))
{
throw new InvalidOperationException("Editing recurring events is not supported");
}
var calendarId = GetCalendarIdForEventId(calendarEvent.ExternalID);
if (calendarId.HasValue && calendarId.Value.ToString() == calendar.ExternalID)
{
var eventsUri = CalendarContract.Events.ContentUri;
return Delete(eventsUri, existingId);
}
return false;
}).ConfigureAwait(false);
}
return false;
}
#endregion
#region Private Methods
private static bool IsCalendarWritable(int accessLevel) => (CalendarAccess)accessLevel switch
{
CalendarAccess.AccessContributor
or CalendarAccess.AccessEditor
or CalendarAccess.AccessOwner
or CalendarAccess.AccessRoot => true,
_ => false,
};
private static long? GetCalendarIdForEventId(string externalId)
{
string[] eventsProjection =
{
CalendarContract.Events.InterfaceConsts.CalendarId
};
if (_eventsUri == null)
{
throw new NullReferenceException(nameof(_eventsUri));
}
var cursor = Query(
ContentUris.WithAppendedId(_eventsUri, long.Parse(externalId)),
eventsProjection);
var calendarId = SingleItemFromCursor<long?>(cursor, () => cursor.GetLong(CalendarContract.Events.InterfaceConsts.CalendarId));
return calendarId;
}
private static bool IsEventRecurring(string externalId)
{
string[] eventsProjection =
{
// There are a number of properties related to recurrence that
// we could check. The Android docs state: "For non-recurring events,
// you must include DTEND. For recurring events, you must include a
// DURATION in addition to RRULE or RDATE." The API will also throw
// an exception if you try to set both DTEND and DURATION on an
// event. Thus, it seems reasonable to trust that DURATION will
// only be present if the event is recurring.
//
CalendarContract.Events.InterfaceConsts.Duration
};
if (_eventsUri == null)
{
throw new NullReferenceException(nameof(_eventsUri));
}
var cursor = Query(
ContentUris.WithAppendedId(_eventsUri, long.Parse(externalId)),
eventsProjection);
bool isRecurring = SingleItemFromCursor(cursor,
() => !string.IsNullOrEmpty(cursor.GetString(CalendarContract.Events.InterfaceConsts.Duration)));
return isRecurring;
}
/// <summary>
/// Gets a single calendar event by platform-specific ID.
/// </summary>
/// <param name="externalId">Platform-specific calendar event identifier</param>
/// <returns>The corresponding calendar event, or null if not found</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
private CalendarEvent? GetEventById(string externalId)
{
// Note that this is slightly different from the GetEvents projection
// due to the Instances API vs Events API (specifically, IDs and start/end times)
//
string[] eventsProjection =
{
CalendarContract.Events.InterfaceConsts.Id,
CalendarContract.Events.InterfaceConsts.Title,
CalendarContract.Events.InterfaceConsts.Description,
CalendarContract.Events.InterfaceConsts.Dtstart,
CalendarContract.Events.InterfaceConsts.Dtend,
CalendarContract.Events.InterfaceConsts.EventLocation,
CalendarContract.Events.InterfaceConsts.AllDay
};
if (_eventsUri == null)
{
throw new NullReferenceException(nameof(_eventsUri));
}
var cursor = Query(
ContentUris.WithAppendedId(_eventsUri, long.Parse(externalId)),
eventsProjection);
var calendarEvent = SingleItemFromCursor(cursor, () =>
{
bool allDay = cursor.GetBoolean(CalendarContract.Events.InterfaceConsts.AllDay);
string? externalID = cursor.GetString(CalendarContract.Events.InterfaceConsts.Id);
return new CalendarEvent
{
Name = cursor.GetString(CalendarContract.Events.InterfaceConsts.Title),
ExternalID = externalId,
Description = cursor.GetString(CalendarContract.Events.InterfaceConsts.Description),
Start = cursor.GetDateTime(CalendarContract.Events.InterfaceConsts.Dtstart, allDay),
End = cursor.GetDateTime(CalendarContract.Events.InterfaceConsts.Dtend, allDay),
Location = cursor.GetString(CalendarContract.Events.InterfaceConsts.EventLocation),
AllDay = allDay,
Reminders = GetEventReminders(externalID)
};
});
return calendarEvent;
}
/// <summary>
/// Get reminders for an event.
/// Assumes that event existence/validity has already been verified.
/// </summary>
/// <param name="eventID">Event ID for which to retrieve reminders</param>
/// <returns>Reminders</returns>
private IList<CalendarEventReminder> GetEventReminders(string? eventID)
{
if (string.IsNullOrEmpty(eventID))
{
throw new ArgumentException("Missing calendar event identifier", nameof(eventID));
}
// Not bothering to verify that event exists because this is intended for internal use
// so we should already know that it exists.
string[] remindersProjection =
{
CalendarContract.Reminders.InterfaceConsts.Minutes,
CalendarContract.Reminders.InterfaceConsts.Method
};
var cursor = Query(CalendarContract.Reminders.ContentUri, remindersProjection,
$"{CalendarContract.Reminders.InterfaceConsts.EventId} = {eventID}",
null, null);
var reminders = IterateCursor(cursor, () => new CalendarEventReminder
{
TimeBefore = TimeSpan.FromMinutes(cursor.GetInt(CalendarContract.Reminders.InterfaceConsts.Minutes)),
Method = ((RemindersMethod)cursor.GetInt(CalendarContract.Reminders.InterfaceConsts.Method)).ToCalendarReminderMethod()
});
return reminders;
}
/// <summary>
/// Builds ContentProviderOperations for adding/removing reminders.
/// Specifically intended for use by AddOrUpdateEvent, as if existingEvent is omitted,
/// this requires that the operations are added to a batch in which the first operation
/// inserts the event.
/// </summary>
/// <param name="reminders">New reminders (replacing existing reminders, if any)</param>
/// <param name="existingEvent">(optional) Existing event to update reminders for</param>
/// <returns>List of ContentProviderOperations for applying reminder updates as part of a batched update</returns>
private IList<ContentProviderOperation> BuildReminderUpdateOperations(IList<CalendarEventReminder>? reminders, CalendarEvent? existingEvent = null)
{
var operations = new List<ContentProviderOperation>();
// If reminders are null or haven't changed, do nothing
//
if (reminders == null ||
(existingEvent?.Reminders != null && reminders.SequenceEqual(existingEvent.Reminders)))
{
return operations;
}
if (_remindersUri == null)
{
throw new NullReferenceException(nameof(_remindersUri));
}
// Build operations that remove all existing reminders and add new ones
if (existingEvent?.Reminders != null)
{
operations.AddRange(existingEvent.Reminders.Select(reminder =>
ContentProviderOperation.NewDelete(_remindersUri)
?.WithSelection($"{CalendarContract.Reminders.InterfaceConsts.EventId} = {existingEvent.ExternalID}", null)
?.Build()!));
}
if (reminders != null)
{
if (existingEvent != null)
{
operations.AddRange(reminders.Select(reminder =>
ContentProviderOperation.NewInsert(_remindersUri)
?.WithValues(reminder.ToContentValues(existingEvent.ExternalID))
?.Build()!));
}
else
{
// This assumes that these operations are being added to a batch in which the first operation
// is the event insertion operation
//
operations.AddRange(reminders.Select(reminder =>
ContentProviderOperation.NewInsert(_remindersUri)
?.WithValues(reminder.ToContentValues())
?.WithValueBackReference(CalendarContract.Reminders.InterfaceConsts.EventId, 0)
?.Build()!));
}
}
return operations;
}
private static Calendar GetCalendar(ICursor cursor)
{
var accessLevel = cursor.GetInt(CalendarContract.Calendars.InterfaceConsts.CalendarAccessLevel);
var accountType = cursor.GetString(CalendarContract.Calendars.InterfaceConsts.AccountType);
var colorInt = cursor.GetInt(CalendarContract.Calendars.InterfaceConsts.CalendarColor);
var colorString = string.Format("#{0:x8}", colorInt);
return new Calendar
{
Name = cursor.GetString(CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName),
ExternalID = cursor.GetString(CalendarContract.Calendars.InterfaceConsts.Id),
CanEditCalendar = accountType == CalendarContract.AccountTypeLocal,
CanEditEvents = IsCalendarWritable(accessLevel),
Color = colorString,
AccountName = cursor.GetString(CalendarContract.Calendars.InterfaceConsts.AccountName)
};
}
private static ICursor Query(Android.Net.Uri? uri, string[] projection, string? selection = null,
string[]? selectionArgs = null, string? sortOrder = null)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
try
{
return Application.Context.ContentResolver?.Query(uri, projection, selection, selectionArgs, sortOrder)
?? throw new NullReferenceException("Application.Context.ContentResolver");
}
catch (Java.Lang.Exception ex)
{
throw TranslateException(ex);
}
}
/// <summary>
/// Returns ID of new item
/// </summary>
private static string Insert(Android.Net.Uri? uri, ContentValues values)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
try
{
return Application.Context.ContentResolver?.Insert(uri, values)?.LastPathSegment
?? throw new NullReferenceException("Application.Context.ContentResolver");
}
catch (Java.Lang.Exception ex)
{
throw TranslateException(ex);
}
}
private static void Update(Android.Net.Uri? uri, long id, ContentValues values)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
try
{
Application.Context.ContentResolver?.Update(ContentUris.WithAppendedId(uri, id), values, null, null);
}
catch (Java.Lang.Exception ex)
{
throw TranslateException(ex);
}
}
private static bool Delete(Android.Net.Uri? uri, long id)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
try
{
return 0 < Application.Context.ContentResolver?.Delete(ContentUris.WithAppendedId(uri, id), null, null);
}
catch (Java.Lang.Exception ex)
{
throw TranslateException(ex);
}
}
private static ContentProviderResult[] ApplyBatch(IList<ContentProviderOperation> operations)
{
try
{
return Application.Context.ContentResolver?.ApplyBatch(CalendarContract.Authority, operations)
?? throw new NullReferenceException("Application.Context.ContentResolver");
}
catch (Java.Lang.Exception ex)
{
throw TranslateException(ex);
}
}
private static Exception TranslateException(Java.Lang.Exception ex)
{
if (ex is Java.Lang.SecurityException)
{
return new UnauthorizedAccessException(ex.Message, ex);
}
else
{
return new PlatformException(ex.Message, ex);
}
}
private static IList<T> IterateCursor<T>(ICursor cursor, Func<T> func)
{
var list = new List<T>();
try
{
if (cursor.MoveToFirst())
{
do
{
list.Add(func());
} while (cursor.MoveToNext());
}
}
catch (Java.Lang.Exception ex)
{
throw new PlatformException(ex.Message, ex);
}
finally
{
cursor.Close();
}
return list;
}
private static T? SingleItemFromCursor<T>(ICursor cursor, Func<T> func)
{
try
{
if (cursor.MoveToFirst())
{
return func();
}
}
catch (Java.Lang.Exception ex)
{
throw new PlatformException(ex.Message, ex);
}
finally
{
cursor.Close();
}
return default;
}
#endregion
}
}
| |
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Image = ImageSharp.Image;
namespace NadekoBot.Modules.Gambling
{
public partial class Gambling
{
[Group]
public class DriceRollCommands : NadekoSubmodule
{
private Regex dndRegex { get; } = new Regex(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled);
private Regex fudgeRegex { get; } = new Regex(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private readonly char[] _fateRolls = { '-', ' ', '+' };
[NadekoCommand, Usage, Description, Aliases]
public async Task Roll()
{
var rng = new NadekoRandom();
var gen = rng.Next(1, 101);
var num1 = gen / 10;
var num2 = gen % 10;
var imageStream = await Task.Run(() =>
{
var ms = new MemoryStream();
new[] { GetDice(num1), GetDice(num2) }.Merge().Save(ms);
ms.Position = 0;
return ms;
}).ConfigureAwait(false);
await Context.Channel.SendFileAsync(imageStream,
"dice.png",
Context.User.Mention + " " + GetText("dice_rolled", Format.Code(gen.ToString()))).ConfigureAwait(false);
}
public enum RollOrderType
{
Ordered,
Unordered
}
[NadekoCommand, Usage, Description, Aliases]
[Priority(0)]
public async Task Roll(int num)
{
await InternalRoll(num, true).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[Priority(0)]
public async Task Rolluo(int num = 1)
{
await InternalRoll(num, false).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[Priority(1)]
public async Task Roll(string arg)
{
await InternallDndRoll(arg, true).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[Priority(1)]
public async Task Rolluo(string arg)
{
await InternallDndRoll(arg, false).ConfigureAwait(false);
}
private async Task InternalRoll(int num, bool ordered)
{
if (num < 1 || num > 30)
{
await ReplyErrorLocalized("dice_invalid_number", 1, 30).ConfigureAwait(false);
return;
}
var rng = new NadekoRandom();
var dice = new List<Image>(num);
var values = new List<int>(num);
for (var i = 0; i < num; i++)
{
var randomNumber = rng.Next(1, 7);
var toInsert = dice.Count;
if (ordered)
{
if (randomNumber == 6 || dice.Count == 0)
toInsert = 0;
else if (randomNumber != 1)
for (var j = 0; j < dice.Count; j++)
{
if (values[j] < randomNumber)
{
toInsert = j;
break;
}
}
}
else
{
toInsert = dice.Count;
}
dice.Insert(toInsert, GetDice(randomNumber));
values.Insert(toInsert, randomNumber);
}
var bitmap = dice.Merge();
var ms = new MemoryStream();
bitmap.Save(ms);
ms.Position = 0;
await Context.Channel.SendFileAsync(ms, "dice.png",
Context.User.Mention + " " +
GetText("dice_rolled_num", Format.Bold(values.Count.ToString())) +
" " + GetText("total_average",
Format.Bold(values.Sum().ToString()),
Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))).ConfigureAwait(false);
}
private async Task InternallDndRoll(string arg, bool ordered)
{
Match match;
int n1;
int n2;
if ((match = fudgeRegex.Match(arg)).Length != 0 &&
int.TryParse(match.Groups["n1"].ToString(), out n1) &&
n1 > 0 && n1 < 500)
{
var rng = new NadekoRandom();
var rolls = new List<char>();
for (int i = 0; i < n1; i++)
{
rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]);
}
var embed = new EmbedBuilder().WithOkColor().WithDescription(Context.User.Mention + " " + GetText("dice_rolled_num", Format.Bold(n1.ToString())))
.AddField(efb => efb.WithName(Format.Bold("Result"))
.WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]")))));
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
else if ((match = dndRegex.Match(arg)).Length != 0)
{
var rng = new NadekoRandom();
if (int.TryParse(match.Groups["n1"].ToString(), out n1) &&
int.TryParse(match.Groups["n2"].ToString(), out n2) &&
n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0)
{
var add = 0;
var sub = 0;
int.TryParse(match.Groups["add"].Value, out add);
int.TryParse(match.Groups["sub"].Value, out sub);
var arr = new int[n1];
for (int i = 0; i < n1; i++)
{
arr[i] = rng.Next(1, n2 + 1);
}
var sum = arr.Sum();
var embed = new EmbedBuilder().WithOkColor().WithDescription(Context.User.Mention + " " +GetText("dice_rolled_num", n1) + $"`1 - {n2}`")
.AddField(efb => efb.WithName(Format.Bold("Rolls"))
.WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString())))))
.AddField(efb => efb.WithName(Format.Bold("Sum"))
.WithValue(sum + " + " + add + " - " + sub + " = " + (sum + add - sub)));
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
}
}
[NadekoCommand, Usage, Description, Aliases]
public async Task NRoll([Remainder] string range)
{
int rolled;
if (range.Contains("-"))
{
var arr = range.Split('-')
.Take(2)
.Select(int.Parse)
.ToArray();
if (arr[0] > arr[1])
{
await ReplyErrorLocalized("second_larger_than_first").ConfigureAwait(false);
return;
}
rolled = new NadekoRandom().Next(arr[0], arr[1] + 1);
}
else
{
rolled = new NadekoRandom().Next(0, int.Parse(range) + 1);
}
await ReplyConfirmLocalized("dice_rolled", Format.Bold(rolled.ToString())).ConfigureAwait(false);
}
private Image GetDice(int num)
{
if (num < 0 || num > 10)
throw new ArgumentOutOfRangeException(nameof(num));
if (num == 10)
{
var images = NadekoBot.Images.Dice;
using (var imgOneStream = images[1].Value.ToStream())
using (var imgZeroStream = images[0].Value.ToStream())
{
Image imgOne = new Image(imgOneStream);
Image imgZero = new Image(imgZeroStream);
return new[] { imgOne, imgZero }.Merge();
}
}
using (var die = NadekoBot.Images.Dice[num].Value.ToStream())
{
return new Image(die);
}
}
}
}
}
| |
#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.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal static class ReflectionUtils
{
public static Type GetObjectType(object v)
{
return (v != null) ? v.GetType() : null;
}
public static bool IsInstantiatableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsAbstract || t.IsInterface || t.IsArray || t.IsGenericTypeDefinition || t == typeof(void))
return false;
if (!HasDefaultConstructor(t))
return false;
return true;
}
public static bool HasDefaultConstructor(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsValueType)
return true;
return (t.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null) != null);
}
public static bool IsNullable(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsValueType)
return IsNullableType(t);
return true;
}
public static bool IsNullableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
//public static bool IsValueTypeUnitializedValue(ValueType value)
//{
// if (value == null)
// return true;
// return value.Equals(CreateUnitializedValue(value.GetType()));
//}
public static bool IsUnitializedValue(object value)
{
if (value == null)
{
return true;
}
else
{
object unitializedValue = CreateUnitializedValue(value.GetType());
return value.Equals(unitializedValue);
}
}
public static object CreateUnitializedValue(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsGenericTypeDefinition)
throw new ArgumentException("Type {0} is a generic type definition and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type");
if (type.IsClass || type.IsInterface || type == typeof(void))
return null;
else if (type.IsValueType)
return Activator.CreateInstance(type);
else
throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type");
}
public static bool IsPropertyIndexed(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, "property");
return !CollectionUtils.IsNullOrEmpty<ParameterInfo>(property.GetIndexParameters());
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition");
if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition)
throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition));
if (type.IsInterface)
{
if (type.IsGenericType)
{
Type interfaceDefinition = type.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = type;
return true;
}
}
}
foreach (Type i in type.GetInterfaces())
{
if (i.IsGenericType)
{
Type interfaceDefinition = i.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = i;
return true;
}
}
}
implementingType = null;
return false;
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition)
{
Type implementingType;
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition");
if (!genericClassDefinition.IsClass || !genericClassDefinition.IsGenericTypeDefinition)
throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition));
return InheritsGenericDefinitionInternal(type, type, genericClassDefinition, out implementingType);
}
private static bool InheritsGenericDefinitionInternal(Type initialType, Type currentType, Type genericClassDefinition, out Type implementingType)
{
if (currentType.IsGenericType)
{
Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition();
if (genericClassDefinition == currentGenericClassDefinition)
{
implementingType = currentType;
return true;
}
}
if (currentType.BaseType == null)
{
implementingType = null;
return false;
}
return InheritsGenericDefinitionInternal(initialType, currentType.BaseType, genericClassDefinition, out implementingType);
}
/// <summary>
/// Gets the type of the typed collection's items.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type of the typed collection's items.</returns>
public static Type GetCollectionItemType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
Type genericListType;
if (type.IsArray)
{
return type.GetElementType();
}
else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
{
if (genericListType.IsGenericTypeDefinition)
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
return genericListType.GetGenericArguments()[0];
}
else if (typeof(ICollection).IsAssignableFrom(type))
{
return null;
}
else
{
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
}
public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
{
ValidationUtils.ArgumentNotNull(dictionaryType, "type");
Type genericDictionaryType;
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition)
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
keyType = dictionaryGenericArguments[0];
valueType = dictionaryGenericArguments[1];
return;
}
else if (typeof(IDictionary).IsAssignableFrom(dictionaryType))
{
keyType = null;
valueType = null;
return;
}
else
{
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
}
public static Type GetDictionaryValueType(Type dictionaryType)
{
Type keyType;
Type valueType;
GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType);
return valueType;
}
public static Type GetDictionaryKeyType(Type dictionaryType)
{
Type keyType;
Type valueType;
GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType);
return keyType;
}
/// <summary>
/// Tests whether the list's items are their unitialized value.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>Whether the list's items are their unitialized value</returns>
public static bool ItemsUnitializedValue<T>(IList<T> list)
{
ValidationUtils.ArgumentNotNull(list, "list");
Type elementType = GetCollectionItemType(list.GetType());
if (elementType.IsValueType)
{
object unitializedValue = CreateUnitializedValue(elementType);
for (int i = 0; i < list.Count; i++)
{
if (!list[i].Equals(unitializedValue))
return false;
}
}
else if (elementType.IsClass)
{
for (int i = 0; i < list.Count; i++)
{
object value = list[i];
if (value != null)
return false;
}
}
else
{
throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType));
}
return true;
}
/// <summary>
/// Gets the member's underlying type.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>The underlying type of the member.</returns>
public static Type GetMemberUnderlyingType(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, "member");
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
default:
throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member");
}
}
/// <summary>
/// Determines whether the member is an indexed property.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, "member");
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
return IsIndexedProperty(propertyInfo);
else
return false;
}
/// <summary>
/// Determines whether the property is an indexed property.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>
/// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, "property");
return (property.GetIndexParameters().Length > 0);
}
/// <summary>
/// Gets the member's value on the object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
public static object GetMemberValue(MemberInfo member, object target)
{
ValidationUtils.ArgumentNotNull(member, "member");
ValidationUtils.ArgumentNotNull(target, "target");
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).GetValue(target);
case MemberTypes.Property:
try
{
return ((PropertyInfo)member).GetValue(target, null);
}
catch (TargetParameterCountException e)
{
throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e);
}
default:
throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member");
}
}
/// <summary>
/// Sets the member's value on the target object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public static void SetMemberValue(MemberInfo member, object target, object value)
{
ValidationUtils.ArgumentNotNull(member, "member");
ValidationUtils.ArgumentNotNull(target, "target");
switch (member.MemberType)
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(target, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member");
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be read.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be read.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.
/// </returns>
public static bool CanReadMemberValue(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return ((PropertyInfo)member).CanRead;
default:
return false;
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be set.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be set.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.
/// </returns>
public static bool CanSetMemberValue(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return ((PropertyInfo)member).CanWrite;
default:
return false;
}
}
public static List<MemberInfo> GetFieldsAndProperties<T>(BindingFlags bindingAttr)
{
return GetFieldsAndProperties(typeof(T), bindingAttr);
}
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
targetMembers.AddRange(type.GetFields(bindingAttr));
targetMembers.AddRange(type.GetProperties(bindingAttr));
// for some reason .NET returns multiple members when overriding a generic member on a base class
// http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/
// filter members to only return the override on the topmost class
List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count);
var groupedMembers = targetMembers.GroupBy(m => m.Name).Select(g => new { Count = g.Count(), Members = g.Cast<MemberInfo>() });
foreach (var groupedMember in groupedMembers)
{
if (groupedMember.Count == 1)
distinctMembers.Add(groupedMember.Members.First());
else
distinctMembers.Add(groupedMember.Members.Where(m => !IsOverridenGenericMember(m, bindingAttr)).First());
}
return distinctMembers;
}
private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr)
{
if (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property)
throw new ArgumentException("Member must be a field or property.");
Type declaringType = memberInfo.DeclaringType;
if (!declaringType.IsGenericType)
return false;
Type genericTypeDefinition = declaringType.GetGenericTypeDefinition();
if (genericTypeDefinition == null)
return false;
MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr);
if (members.Length == 0)
return false;
Type memberUnderlyingType = GetMemberUnderlyingType(members[0]);
if (!memberUnderlyingType.IsGenericParameter)
return false;
return true;
}
public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
{
return GetAttribute<T>(attributeProvider, true);
}
public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute
{
T[] attributes = GetAttributes<T>(attributeProvider, inherit);
return CollectionUtils.GetSingleItem(attributes, true);
}
public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute
{
ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider");
return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit);
}
public static string GetNameAndAssessmblyName(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
return t.FullName + ", " + t.Assembly.GetName().Name;
}
public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes)
{
ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition");
ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes");
ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition));
return genericTypeDefinition.MakeGenericType(innerTypes);
}
public static object CreateGeneric(Type genericTypeDefinition, Type innerType, params object[] args)
{
return CreateGeneric(genericTypeDefinition, new Type[] { innerType }, args);
}
public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, params object[] args)
{
return CreateGeneric(genericTypeDefinition, innerTypes, (t, a) => ReflectionUtils.CreateInstance(t, a.ToArray()), args);
}
public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, Func<Type, IList<object>, object> instanceCreator, params object[] args)
{
ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition");
ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes");
ValidationUtils.ArgumentNotNull(instanceCreator, "createInstance");
Type specificType = MakeGenericType(genericTypeDefinition, CollectionUtils.CreateArray(innerTypes));
return instanceCreator(specificType, args);
}
static object CreateInstance(this Assembly a, string typeName, params object[] pars)
{
var t = a.GetType(typeName);
var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray());
if (c == null)
return null;
return c.Invoke(pars);
}
public static bool IsCompatibleValue(object value, Type type)
{
if (value == null && IsNullable(type))
return true;
if (type.IsAssignableFrom(value.GetType()))
return true;
return false;
}
public static object CreateInstance(Type type, params object[] args)
{
ValidationUtils.ArgumentNotNull(type, "type");
#if !PocketPC
return Activator.CreateInstance(type, args);
#else
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfo match = constructors.Where(c =>
{
ParameterInfo[] parameters = c.GetParameters();
if (parameters.Length != args.Length)
return false;
for (int i = 0; i < parameters.Length; i++)
{
ParameterInfo parameter = parameters[i];
object value = args[i];
if (!IsCompatibleValue(value, parameter.ParameterType))
return false;
}
return true;
}).FirstOrDefault();
if (match == null)
throw new Exception("Could not create '{0}' with given parameters.".FormatWith(CultureInfo.InvariantCulture, args));
return match.Invoke(args);
#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;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Text;
using System.Security.Principal;
namespace System.DirectoryServices.AccountManagement
{
internal class ADUtils
{
// To stop the compiler from autogenerating a constructor for this class
private ADUtils() { }
// We use this, rather than simply testing DirectoryEntry.SchemaClassName, because we don't
// want to miss objects that are of a derived type.
// Note that, since computer is a derived class of user in AD, if you don't want to confuse
// computers with users, you must test an object for computer status before testing it for
// user status.
static internal bool IsOfObjectClass(DirectoryEntry de, string classToCompare)
{
return de.Properties["objectClass"].Contains(classToCompare);
}
static internal bool IsOfObjectClass(SearchResult sr, string classToCompare)
{
return sr.Properties["objectClass"].Contains(classToCompare);
}
// Retrieves the name of the actual server that the DirectoryEntry is connected to
static internal string GetServerName(DirectoryEntry de)
{
UnsafeNativeMethods.IAdsObjectOptions objOptions = (UnsafeNativeMethods.IAdsObjectOptions)de.NativeObject;
return (string)objOptions.GetOption(0 /* == ADS_OPTION_SERVERNAME */);
}
// This routine escapes values used in DNs, per RFC 2253 and ADSI escaping rules.
// It treats its input as a unescaped literal and produces a LDAP string that represents that literal
// and that is escaped according to RFC 2253 and ADSI rules for DN components.
static internal string EscapeDNComponent(string dnComponent)
{
//
// From RFC 2254:
//
// If the UTF-8 string does not have any of the following characters
// which need escaping, then that string can be used as the string
// representation of the value.
//
// o a space or "#" character occurring at the beginning of the
// string
//
// o a space character occurring at the end of the string
//
// o one of the characters ",", "+", """, "\", "<", ">" or ";"
//
// Implementations MAY escape other characters.
//
// If a character to be escaped is one of the list shown above, then it
// is prefixed by a backslash ('\' ASCII 92).
//
// Otherwise the character to be escaped is replaced by a backslash and
// two hex digits, which form a single byte in the code of the
// character.
//
// ADSI imposes the additional requirement that occurrences of '=' be escaped.
// For ADsPaths, ADSI also requires the '/' (forward slash) to be escaped,
// but not for the individual DN components that we're building here
// (e.g., for IADsContainer::Create).
StringBuilder sb = new StringBuilder(dnComponent.Length);
// If it starts with ' ' or '#', escape the first character (clause one)
int startingIndex = 0;
if (dnComponent[0] == ' ' || dnComponent[0] == '#')
{
sb.Append(@"\");
sb.Append(dnComponent[0]);
startingIndex++;
}
// Handle the escaping of the remaining characters (clause three)
for (int i = startingIndex; i < dnComponent.Length; i++)
{
char c = dnComponent[i];
switch (c)
{
case ',':
sb.Append(@"\,");
break;
case '+':
sb.Append(@"\+");
break;
case '\"':
sb.Append("\\\""); // that's the literal sequence "backslash followed by a quotation mark"
break;
case '\\':
sb.Append(@"\\");
break;
case '>':
sb.Append(@"\>");
break;
case '<':
sb.Append(@"\<");
break;
case ';':
sb.Append(@"\;");
break;
case '=':
sb.Append(@"\=");
break;
default:
sb.Append(c.ToString());
break;
}
}
// If it ends in a space, escape that space (clause two)
if (sb[sb.Length - 1] == ' ')
{
sb.Remove(sb.Length - 1, 1);
sb.Append(@"\ ");
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"ADUtils",
"EscapeDNComponent: mapped '{0}' to '{1}'",
dnComponent,
sb.ToString());
return sb.ToString();
}
// This routine escapes values used in search filters, per RFC 2254 escaping rules.
// It treats its input as a unescaped literal and produces a LDAP string that represents that literal
// and that is escaped according to RFC 2254 rules.
static internal string EscapeRFC2254SpecialChars(string s)
{
StringBuilder sb = new StringBuilder(s.Length);
foreach (char c in s)
{
switch (c)
{
case '(':
sb.Append(@"\28");
break;
case ')':
sb.Append(@"\29");
break;
case '*':
sb.Append(@"\2a");
break;
case '\\':
sb.Append(@"\5c");
break;
default:
sb.Append(c.ToString());
break;
}
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"ADUtils",
"EscapeRFC2254SpecialChars: mapped '{0}' to '{1}'",
s,
sb.ToString());
return sb.ToString();
}
// This routine escapes PAPI string values that may contain wilcards.
// It treats its input string as a PAPI string filter (escaped according to
// PAPI rules, and possibly containing wildcards), and produces a string
// escaped to RFC 2254 rules and possibly containing wildcards.
static internal string PAPIQueryToLdapQueryString(string papiString)
{
//
// Wildcard
// * --> *
//
// Escaped Literals
// \* --> \2a
// \\ --> \5c
//
// Other
// ( --> \28
// ) --> \29
// \( --> \28
// \) --> \29
// x --> x (where x is anything else)
// \x --> x (where x is anything else)
StringBuilder sb = new StringBuilder(papiString.Length);
bool escapeMode = false;
foreach (char c in papiString)
{
if (escapeMode == false)
{
switch (c)
{
case '(':
sb.Append(@"\28"); // ( --> \28
break;
case ')':
sb.Append(@"\29"); // ) --> \29
break;
case '\\':
escapeMode = true;
break;
default:
// including the '*' wildcard
sb.Append(c.ToString()); // * --> * and x --> x
break;
}
}
else
{
escapeMode = false;
switch (c)
{
case '(':
sb.Append(@"\28"); // \( --> \28
break;
case ')':
sb.Append(@"\29"); // \) --> \29
break;
case '*':
sb.Append(@"\2a"); // \* --> \2a
break;
case '\\':
sb.Append(@"\5c"); // \\ --> \5c
break;
default:
sb.Append(c.ToString()); // \x --> x
break;
}
}
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"ADUtils",
"PAPIQueryToLdapQueryString: mapped '{0}' to '{1}'",
papiString,
sb.ToString());
return sb.ToString();
}
static internal string EscapeBinaryValue(byte[] bytes)
{
StringBuilder sb = new StringBuilder(bytes.Length * 3);
foreach (byte b in bytes)
{
sb.Append(@"\");
sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
return sb.ToString();
}
static internal string DateTimeToADString(DateTime dateTime)
{
// DateTime --> FILETIME --> stringized FILETIME
long fileTime = dateTime.ToFileTimeUtc();
return fileTime.ToString(CultureInfo.InvariantCulture);
}
static internal DateTime ADFileTimeToDateTime(Int64 filetime)
{
// int64 FILETIME --> DateTime
return DateTime.FromFileTimeUtc(filetime);
}
static internal Int64 DateTimeToADFileTime(DateTime dt)
{
// DateTime --> int64 FILETIME
return dt.ToFileTimeUtc();
}
static internal Int64 LargeIntToInt64(UnsafeNativeMethods.IADsLargeInteger largeInt)
{
uint lowPart = (uint)largeInt.LowPart;
uint highPart = (uint)largeInt.HighPart;
Int64 i = (long)(((ulong)lowPart) | (((ulong)highPart) << 32));
return i;
}
// Transform from hex string ("1AFF") to LDAP hex string ("\1A\FF").
// Returns null if input string is not a valid hex string.
static internal string HexStringToLdapHexString(string s)
{
Debug.Assert(s != null);
if (s.Length % 2 != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADUtils", "HexStringToLdapHexString: string has bad length " + s.Length);
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < (s.Length) / 2; i++)
{
char firstChar = s[i * 2];
char secondChar = s[(i * 2) + 1];
if (((firstChar >= '0' && firstChar <= '9') || (firstChar >= 'A' && firstChar <= 'F') || (firstChar >= 'a' && firstChar <= 'f')) &&
((secondChar >= '0' && secondChar <= '9') || (secondChar >= 'A' && secondChar <= 'F') || (secondChar >= 'a' && secondChar <= 'f')))
{
sb.Append(@"\");
sb.Append(firstChar);
sb.Append(secondChar);
}
else
{
// not a hex character
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADUtils", "HexStringToLdapHexString: invalid string " + s);
return null;
}
}
return sb.ToString();
}
static internal bool ArePrincipalsInSameForest(Principal p1, Principal p2)
{
string p1DnsForestName = ((ADStoreCtx)p1.GetStoreCtxToUse()).DnsForestName;
string p2DnsForestName = ((ADStoreCtx)p2.GetStoreCtxToUse()).DnsForestName;
return (String.Compare(p1DnsForestName, p2DnsForestName, StringComparison.OrdinalIgnoreCase) == 0);
}
///
/// <summary>
/// Returns true if the specified SIDs are from the same domain.
/// Otherwise return false.
/// </summary>
/// <param name="sid1"></param>
/// <param name="sid2"></param>
/// <returns>Returns true if the specified SIDs are from the same domain.
/// Otherwise return false
/// </returns>
///
static internal bool AreSidsInSameDomain(SecurityIdentifier sid1, SecurityIdentifier sid2)
{
if (sid1.IsAccountSid() && sid2.IsAccountSid())
{
return (sid1.AccountDomainSid.Equals(sid2.AccountDomainSid));
}
else
{
return false;
}
}
static internal Principal DirectoryEntryAsPrincipal(DirectoryEntry de, ADStoreCtx storeCtx)
{
if (ADUtils.IsOfObjectClass(de, "computer") ||
ADUtils.IsOfObjectClass(de, "user") ||
ADUtils.IsOfObjectClass(de, "group"))
{
return storeCtx.GetAsPrincipal(de, null);
}
else if (ADUtils.IsOfObjectClass(de, "foreignSecurityPrincipal"))
{
return storeCtx.ResolveCrossStoreRefToPrincipal(de);
}
else
{
return storeCtx.GetAsPrincipal(de, null);
}
}
static internal Principal SearchResultAsPrincipal(SearchResult sr, ADStoreCtx storeCtx, object discriminant)
{
if (ADUtils.IsOfObjectClass(sr, "computer") ||
ADUtils.IsOfObjectClass(sr, "user") ||
ADUtils.IsOfObjectClass(sr, "group"))
{
return storeCtx.GetAsPrincipal(sr, discriminant);
}
else if (ADUtils.IsOfObjectClass(sr, "foreignSecurityPrincipal"))
{
return storeCtx.ResolveCrossStoreRefToPrincipal(sr.GetDirectoryEntry());
}
else
{
return storeCtx.GetAsPrincipal(sr, discriminant);
}
}
// This function is used to check if we will be able to lookup a SID from the
// target domain by targeting the local computer. This is done by checking for either
// a outbound or bidirectional trust between the computers domain and the target
// domain or the current forest and the target domain's forest.
// target domain must be the full DNS domain name of the target domain to make the string
// compare below work properly.
static internal bool VerifyOutboundTrust(string targetDomain, string username, string password)
{
Domain currentDom = null;
try
{
currentDom = Domain.GetComputerDomain();
}
catch (ActiveDirectoryObjectNotFoundException)
{
// The computer is not domain joined so there cannot be a trust...
return false;
}
catch (System.Security.Authentication.AuthenticationException)
{
// The computer is domain joined but we are running with creds that can't access it. We can't determine trust.
return false;
}
// If this is the same domain then we have a trust.
// Domain.Name always returns full dns name.
// function is always supplied with a full DNS domain name.
if (String.Compare(currentDom.Name, targetDomain, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
try
{
TrustRelationshipInformation TRI = currentDom.GetTrustRelationship(targetDomain);
if (TrustDirection.Outbound == TRI.TrustDirection || TrustDirection.Bidirectional == TRI.TrustDirection)
{
return true;
}
}
catch (ActiveDirectoryObjectNotFoundException)
{
}
// Since we were able to retrive the computer domain above we should be able to access the current forest here.
Forest currentForest = Forest.GetCurrentForest();
Domain targetdom = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, targetDomain, username, password));
try
{
ForestTrustRelationshipInformation FTC = currentForest.GetTrustRelationship(targetdom.Forest.Name);
if (TrustDirection.Outbound == FTC.TrustDirection || TrustDirection.Bidirectional == FTC.TrustDirection)
{
return true;
}
}
catch (ActiveDirectoryObjectNotFoundException)
{
}
return false;
}
static internal string RetriveWkDn(DirectoryEntry deBase, string defaultNamingContext, string serverName, Byte[] wellKnownContainerGuid)
{
/*
bool w2k3Supported = false;
if ( w2k3Supported )
{
return @"LDAP://" + this.UserSuppliedServerName + @"/<WKGUID= " + Constants.GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_W + @"," + this.DefaultNamingContext + @">";
}
*/
PropertyValueCollection wellKnownObjectValues = deBase.Properties["wellKnownObjects"];
foreach (UnsafeNativeMethods.IADsDNWithBinary value in wellKnownObjectValues)
{
if (Utils.AreBytesEqual(wellKnownContainerGuid, (byte[])value.BinaryValue))
{
return ("LDAP://" + serverName + @"/" + value.DNString);
}
}
return null;
}
}
}
| |
//////////////////////////////////////////////////////////////////////
//
// WordXmlWriter.cs
//
// Provides a class to support writing Word 2003 XML files.
//
//////////////////////////////////////////////////////////////////////
namespace DocumentSerialization
{
#region Namespaces.
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Security.Policy;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows.Media;
#endregion Namespaces.
/// <summary>Encapsulates the operation of writing WordXML documents.</summary>
class WordXmlWriter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors.
/// <summary>Initializes a new WordXmlWriter instance.</summary>
internal WordXmlWriter()
{
_dir = LogicalDirection.Forward;
}
#endregion Constructors.
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal methods.
/// <summary>
/// Writes the container into the specified XmlWriter.
/// </summary>
internal void Write(TextPointer start, TextPointer end, XmlWriter writer)
{
System.Diagnostics.Debug.Assert(start != null);
System.Diagnostics.Debug.Assert(end != null);
System.Diagnostics.Debug.Assert(start.CompareTo(end) <= 0);
System.Diagnostics.Debug.Assert(writer != null);
WriteContainer(start, end, writer);
}
#endregion Internal methods.
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private methods.
/// <summary>
/// Checks whether the specified property is applicable to paragraphs.
/// </summary>
private bool IsParagraphProperty(DependencyProperty property)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
return false;
}
/// <summary>
/// Checks whether the specified property is applicable to ranges.
/// </summary>
private bool IsRangeProperty(DependencyProperty property)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
return
(property == TextBlock.FontWeightProperty) ||
(property == TextBlock.FontStyleProperty) ||
(property == TextBlock.ForegroundProperty) ||
(property == TextBlock.FontSizeProperty) ||
(property == TextBlock.FontFamilyProperty);
}
/// <summary>
/// Writes the container into the specified XmlWriter.
/// </summary>
private void WriteContainer(TextPointer start, TextPointer end, XmlWriter writer)
{
TextElement textElement;
System.Diagnostics.Debug.Assert(start != null);
System.Diagnostics.Debug.Assert(end != null);
System.Diagnostics.Debug.Assert(writer != null);
_writer = writer;
WriteWordXmlHead();
_cursor = start;
while (_cursor.CompareTo(end) < 0)
{
switch (_cursor.GetPointerContext(_dir))
{
case TextPointerContext.None:
System.Diagnostics.Debug.Assert(false,
"Next symbol should never be None if cursor < End.");
break;
case TextPointerContext.Text:
RequireOpenRange();
_writer.WriteStartElement(WordXmlSerializer.WordTextTag);
_writer.WriteString(_cursor.GetTextInRun(_dir));
_writer.WriteEndElement();
break;
case TextPointerContext.EmbeddedElement:
DependencyObject obj = _cursor.GetAdjacentElement(LogicalDirection.Forward);
if (obj is LineBreak)
{
RequireOpenRange();
_writer.WriteStartElement(WordXmlSerializer.WordBreakTag);
_writer.WriteEndElement();
}
// TODO: try to convert some known embedded objects.
break;
case TextPointerContext.ElementStart:
TextPointer position;
position = _cursor;
position = position.GetNextContextPosition(LogicalDirection.Forward);
textElement = position.Parent as TextElement;
if (textElement is Paragraph)
{
RequireClosedRange();
RequireOpenParagraph();
}
else if (textElement is Inline)
{
RequireClosedRange();
RequireOpenParagraph();
RequireOpenRange();
}
break;
case TextPointerContext.ElementEnd:
textElement = _cursor.Parent as TextElement;
if (textElement is Inline)
{
RequireClosedRange();
}
else if (textElement is Paragraph)
{
RequireClosedParagraph();
}
break;
}
_cursor = _cursor.GetNextContextPosition(_dir);
}
RequireClosedRange();
WriteWordXmlTail();
}
/// <summary>
/// Writes the given property to the output document.
/// </summary>
/// <param name="property">Property to write.</param>
/// <param name="value">Value of property to write.</param>
/// <remarks>
/// If the property is not supported, this method does nothing.
/// </remarks>
private void WriteProperty(DependencyProperty property, object value)
{
if (property == TextBlock.FontWeightProperty)
{
FontWeight weight;
weight = (FontWeight)value;
_writer.WriteStartElement(WordXmlSerializer.WordBoldTag);
_writer.WriteAttributeString(WordXmlSerializer.WordValue,
(weight > FontWeights.Medium)? WordXmlSerializer.WordOn : WordXmlSerializer.WordOff);
_writer.WriteEndElement();
}
else if (property == TextBlock.FontStyleProperty)
{
FontStyle style;
style = (FontStyle)value;
_writer.WriteStartElement(WordXmlSerializer.WordItalicTag);
_writer.WriteAttributeString(WordXmlSerializer.WordValue,
(style != FontStyles.Normal)? WordXmlSerializer.WordOn : WordXmlSerializer.WordOff);
_writer.WriteEndElement();
}
else if (property == TextBlock.ForegroundProperty)
{
SolidColorBrush brush;
Color color;
// Note: gradient and other brushes not supported.
brush = value as SolidColorBrush;
if (brush != null)
{
color = brush.Color;
_writer.WriteStartElement(WordXmlSerializer.WordColorTag);
_writer.WriteAttributeString(WordXmlSerializer.WordValue,
String.Format( "{0:x2}{1:x2}{2:x2}",
color.R, color.G, color.B));
_writer.WriteEndElement();
}
}
else if (property == TextBlock.FontSizeProperty)
{
double size;
// w:sz is specified in 1/144ths of an inch
size = (double)value;
_writer.WriteStartElement(WordXmlSerializer.WordFontSizeTag);
_writer.WriteAttributeString(WordXmlSerializer.WordValue,
((int)((size * 72.0 / 96.0) * 2)).ToString());
_writer.WriteEndElement();
}
else if (property == TextBlock.FontFamilyProperty)
{
string fontFamily;
fontFamily = value.ToString();
_writer.WriteStartElement("w:rFonts");
_writer.WriteAttributeString("w:ascii", fontFamily);
_writer.WriteAttributeString("w:h-ansi", fontFamily);
_writer.WriteAttributeString("w:cs", fontFamily);
_writer.WriteEndElement();
_writer.WriteStartElement("wx:font");
_writer.WriteAttributeString("wx:val", fontFamily);
_writer.WriteEndElement();
}
}
/// <summary>Writes the properties for a range of text (w:rPr).</summary>
private void WriteRangeProperties()
{
System.Diagnostics.Debug.Assert(_inRange);
System.Diagnostics.Debug.Assert(_dir == LogicalDirection.Forward);
WriteProperties(WordXmlSerializer.WordRangePropertiesTag,
RangeProperties);
}
/// <summary>Writes the properties for a range of text (w:pPr).</summary>
private void WriteParagraphProperties()
{
System.Diagnostics.Debug.Assert(_inParagraph);
System.Diagnostics.Debug.Assert(_dir == LogicalDirection.Forward);
WriteProperties(WordXmlSerializer.WordParagraphPropertiesTag,
ParagraphProperties);
}
/// <summary>Writes properties in the specified properties element.</summary>
/// <param name="tagName">Name of element to write properties in.</param>
/// <param name="properties">Properties to write.</param>
private void WriteProperties(string tagName, DependencyProperty[] properties)
{
DependencyObject parent;
TextPointer position;
position = _cursor;
position = position.GetNextContextPosition(LogicalDirection.Forward);
parent = position.Parent;
_writer.WriteStartElement(tagName);
foreach(DependencyProperty property in properties)
{
WriteProperty(property, parent.GetValue(property));
}
_writer.WriteEndElement();
}
/// <summary>
/// Writes the XML document header and all required WordXML
/// opening tags and namespace declarations.
/// </summary>
/// <remarks>This is symmetrical with WriteWordXmlTail.</remarks>
private void WriteWordXmlHead()
{
_writer.WriteStartDocument(true);
_writer.WriteProcessingInstruction(
"mso-application", "progid=\"Word.Document\"");
_writer.WriteStartElement("w", "wordDocument",
"http://schemas.microsoft.com/office/word/2003/wordml");
_writer.WriteAttributeString("xmlns", "wx", null, "http://schemas.microsoft.com/office/word/2003/auxHint");
// NOTE: this will be required for more advanced conversions.
// _writer.WriteAttributeString("xmlns", "v", null, "urn:schemas-microsoft-com:vml");
// _writer.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
// _writer.WriteAttributeString("xmlns", "w10", null, "urn:schemas-microsoft-com:office:word");
// _writer.WriteAttributeString("xmlns", "sl", null, "http://schemas.microsoft.com/schemaLibrary/2003/core");
// _writer.WriteAttributeString("xmlns", "aml", null, "http://schemas.microsoft.com/aml/2001/core");
// _writer.WriteAttributeString("xmlns", "dt", null, "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
_writer.WriteAttributeString("xml:space", "preserve");
_writer.WriteStartElement("w:body");
_writer.WriteStartElement("w:sect");
}
/// <summary>
/// Writes the tail of the WordXML file.
/// </summary>
/// <remarks>This is symmetrical with WriteWordXmlHead.</remarks>
private void WriteWordXmlTail()
{
_writer.WriteEndElement(); // Close w:sect.
_writer.WriteEndElement(); // Close w:body.
_writer.WriteEndElement(); // Close w:wordDocument.
}
/// <summary>Ensures that an open range is available.</summary>
private void RequireOpenRange()
{
RequireOpenParagraph();
if (!_inRange)
{
_writer.WriteStartElement(WordXmlSerializer.WordRangeTag);
_inRange = true;
WriteRangeProperties();
}
}
/// <summary>Ensures than an open paragraph is available.</summary>
private void RequireOpenParagraph()
{
if (!_inParagraph)
{
_writer.WriteStartElement(WordXmlSerializer.WordParagraphTag);
_inParagraph = true;
WriteParagraphProperties();
}
}
/// <summary>Ensures that there is no open range.</summary>
private void RequireClosedRange()
{
if (_inRange)
{
// Close w:r.
_writer.WriteEndElement();
_inRange = false;
}
}
/// <summary>Ensures that there is no open paragraph.</summary>
private void RequireClosedParagraph()
{
RequireClosedRange();
if (_inParagraph)
{
// Close w:p.
_writer.WriteEndElement();
_inParagraph = false;
}
}
#endregion Private methods.
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private properties.
/// <summary>Paragraph-level properties in Word object model.</summary>
private DependencyProperty[] ParagraphProperties
{
get
{
if (_paragraphProperties == null)
{
_paragraphProperties = new DependencyProperty[] {
Block.MarginProperty,
Block.TextAlignmentProperty
};
}
return _paragraphProperties;
}
}
/// <summary>Range-level properties in Word object model.</summary>
private DependencyProperty[] RangeProperties
{
get
{
if (_rangeProperties == null)
{
_rangeProperties = new DependencyProperty[] {
TextElement.FontFamilyProperty,
TextElement.FontSizeProperty,
TextElement.FontWeightProperty,
TextElement.FontStyleProperty,
TextElement.ForegroundProperty,
};
}
return _rangeProperties;
}
}
#endregion Private properties.
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private fields.
/// <summary>Cursor moving through document.</summary>
private TextPointer _cursor;
/// <summary>Direction in which the cursor moves.</summary>
/// <remarks>
/// For the current implementatino, the direction is always
/// forward. This may change for more complex implementations.
/// Until then, this acts as a constant (but constants cannot
/// refer to enumeration valueS).
/// </remarks>
private readonly LogicalDirection _dir;
/// <summary>Whether writer has opened a paragraph.</summary>
private bool _inParagraph;
/// <summary>Whether writer has opened a range.</summary>
private bool _inRange;
/// <summary>Paragraph-level properties in Word object model</summary>
private static DependencyProperty[] _paragraphProperties;
/// <summary>Range-level properties in Word object model</summary>
private static DependencyProperty[] _rangeProperties;
/// <summary>Writer used to output document.</summary>
private XmlWriter _writer;
#endregion Private fields.
}
}
| |
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators
{
public class MyTSIV4 : Indicator
{
private Series<double> PctgChangeHigher;
private Series<double> PctgChangePrimary;
private Series<double> PctgChangeLower;
private StdDev stdDevHigher;
private StdDev stdDevPrimary;
private StdDev stdDevLower;
private SUM sumHigher;
private SUM sumPrimary;
private SUM sumLower;
private PriceSeries close;
private Series<double> pctgChange;
private Series<double> plot;
private StdDev stdDev;
private SUM sum;
private double tsi;
private double tsiPrimary = double.MinValue;
private double tsiHigher = double.MinValue;
private double tsiLower = double.MinValue;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"";
Name = "MyTSIV4";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
DrawOnPricePanel = true;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
//Disable this property if your indicator requires custom values that cumulate with each new market data event.
//See Help Guide for additional information.
IsSuspendedWhileInactive = true;
Period = 200;
SignalThreshold = 0.65;
HigherTimeframe = string.Empty;
LowerTimeframe = string.Empty;
AddPlot(new Stroke(Brushes.Red), PlotStyle.Dot, "PlotHigher");
AddPlot(Brushes.Black, "PlotPrimary");
AddPlot(Brushes.Green, "PlotLower");
AddPlot(Brushes.Transparent, "PlotSignal");
}
else if (State == State.Configure)
{
Log(String.Format("HigherTimeframe: {0}, LowerTimeframe{1}", HigherTimeframe, LowerTimeframe), LogLevel.Information);
Data.BarsPeriodType type;
int period;
parseTimeframe(HigherTimeframe, out type, out period);
AddDataSeries(type, period);
Log(String.Format("DataSeries[1] type: {0}, period: {1}", type, period), LogLevel.Information);
parseTimeframe(LowerTimeframe, out type, out period);
AddDataSeries(type, period);
Log(String.Format("DataSeries[2] type: {0}, period: {1}", type, period), LogLevel.Information);
}
else if (State == State.DataLoaded)
{
PctgChangeHigher = new Series<double>(this);
PctgChangePrimary = new Series<double>(this);
PctgChangeLower = new Series<double>(this);
stdDevHigher = StdDev(PctgChangeHigher, Period);
stdDevPrimary = StdDev(PctgChangePrimary, Period);
stdDevLower = StdDev(PctgChangeLower, Period);
sumHigher = SUM(PctgChangeHigher, Period);
sumPrimary = SUM(PctgChangePrimary, Period);
sumLower = SUM(PctgChangeLower, Period);
}
}
protected override void OnBarUpdate()
{
if (CurrentBars[BarsInProgress] < 2)
{
return;
}
close = Closes[BarsInProgress];
getParts(BarsInProgress, out pctgChange, out stdDev, out sum, out plot, out tsi);
pctgChange[0] = (close[0] - close[1]) / close[1];
if (CurrentBars[BarsInProgress] - 2 < Period)
{
return;
}
// SMA will always return 0, have to calculate this way...
double avg0 = this.sum[0] / Period;
double stdDev0 = this.stdDev[0];
double tsi0 = (avg0 / stdDev0) * 10;
plot[0] = tsi0;
tsi = tsi0;
updateMarketAnalyzer();
updateText();
}
private void updateText()
{
if (isSignal())
{
Draw.TextFixed(this, "TSIMessage", String.Format("TSI signaled at {0}", Time[0].ToLongTimeString()), TextPosition.TopRight, Brushes.White, null, null, Brushes.Green, 60);
}
}
private void updateMarketAnalyzer()
{
PlotSignal[0] = isSignal() ? 1 : 0;
}
private void parseTimeframe(string frame, out Data.BarsPeriodType periodType, out int period)
{
if (frame.IsNullOrEmpty())
{
shout("Timeframe cannot be null or empty");
}
period = int.Parse(frame.Substring(0, frame.Length - 1));
string type = frame.Substring(frame.Length - 1).ToLower();
switch(type)
{
case "m":
periodType = Data.BarsPeriodType.Minute;
break;
case "h":
// There is no "Hour" type
periodType = Data.BarsPeriodType.Minute;
period *= 60;
break;
case "d":
periodType = Data.BarsPeriodType.Day;
break;
default:
periodType = Data.BarsPeriodType.Minute;
shout(String.Format("Error parsing timeframe, given {0}", type));
break;
}
}
private void shout(string errorMsg)
{
Log(errorMsg, LogLevel.Error);
throw new Exception(errorMsg);
}
private void getParts(int dataSeriesIndex, out Series<double> pctgChange, out StdDev stdDev, out SUM sum, out Series<double> plot, out double tsi)
{
switch(dataSeriesIndex)
{
case 0:
pctgChange = PctgChangePrimary;
stdDev = stdDevPrimary;
sum = sumPrimary;
plot = PlotPrimary;
tsi = tsiPrimary;
break;
case 1:
pctgChange = PctgChangeHigher;
stdDev = stdDevHigher;
sum = sumHigher;
plot = PlotHigher;
tsi = tsiHigher;
break;
case 2:
pctgChange = PctgChangeLower;
stdDev = stdDevLower;
sum = sumLower;
plot = PlotLower;
tsi = tsiLower;
break;
default:
pctgChange = PctgChangePrimary;
stdDev = stdDevPrimary;
sum = sumPrimary;
plot = PlotPrimary;
tsi = tsiPrimary;
shout(String.Format("Unrecognized index: {0}", dataSeriesIndex));
break;
}
}
private bool isSignal()
{
return tsiPrimary > SignalThreshold && tsiHigher > SignalThreshold && tsiLower > SignalThreshold;
}
#region Properties
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Period", Order=1, GroupName="Parameters")]
public int Period
{ get; set; }
[NinjaScriptProperty]
[Range(0, double.MaxValue)]
[Display(Name="SignalThreshold", Order=2, GroupName="Parameters")]
public double SignalThreshold
{ get; set; }
[NinjaScriptProperty]
[Display(Name="HigherTimeframe", Order=3, GroupName="Parameters")]
public string HigherTimeframe
{ get; set; }
[NinjaScriptProperty]
[Display(Name="LowerTimeframe", Order=4, GroupName="Parameters")]
public string LowerTimeframe
{ get; set; }
[Browsable(false)]
[XmlIgnore]
public Series<double> PlotHigher
{
get { return Values[0]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> PlotPrimary
{
get { return Values[1]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> PlotLower
{
get { return Values[2]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> PlotSignal
{
get { return Values[3]; }
}
#endregion
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private MyTSIV4[] cacheMyTSIV4;
public MyTSIV4 MyTSIV4(int period, double signalThreshold, string higherTimeframe, string lowerTimeframe)
{
return MyTSIV4(Input, period, signalThreshold, higherTimeframe, lowerTimeframe);
}
public MyTSIV4 MyTSIV4(ISeries<double> input, int period, double signalThreshold, string higherTimeframe, string lowerTimeframe)
{
if (cacheMyTSIV4 != null)
for (int idx = 0; idx < cacheMyTSIV4.Length; idx++)
if (cacheMyTSIV4[idx] != null && cacheMyTSIV4[idx].Period == period && cacheMyTSIV4[idx].SignalThreshold == signalThreshold && cacheMyTSIV4[idx].HigherTimeframe == higherTimeframe && cacheMyTSIV4[idx].LowerTimeframe == lowerTimeframe && cacheMyTSIV4[idx].EqualsInput(input))
return cacheMyTSIV4[idx];
return CacheIndicator<MyTSIV4>(new MyTSIV4(){ Period = period, SignalThreshold = signalThreshold, HigherTimeframe = higherTimeframe, LowerTimeframe = lowerTimeframe }, input, ref cacheMyTSIV4);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.MyTSIV4 MyTSIV4(int period, double signalThreshold, string higherTimeframe, string lowerTimeframe)
{
return indicator.MyTSIV4(Input, period, signalThreshold, higherTimeframe, lowerTimeframe);
}
public Indicators.MyTSIV4 MyTSIV4(ISeries<double> input , int period, double signalThreshold, string higherTimeframe, string lowerTimeframe)
{
return indicator.MyTSIV4(input, period, signalThreshold, higherTimeframe, lowerTimeframe);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.MyTSIV4 MyTSIV4(int period, double signalThreshold, string higherTimeframe, string lowerTimeframe)
{
return indicator.MyTSIV4(Input, period, signalThreshold, higherTimeframe, lowerTimeframe);
}
public Indicators.MyTSIV4 MyTSIV4(ISeries<double> input , int period, double signalThreshold, string higherTimeframe, string lowerTimeframe)
{
return indicator.MyTSIV4(input, period, signalThreshold, higherTimeframe, lowerTimeframe);
}
}
}
#endregion
| |
#region License
//
// Source.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml.Filter;
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using SimpleFramework.Xml;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
/// <summary>
/// The <c>Source</c> object acts as a contextual object that is
/// used to store all information regarding an instance of serialization
/// or deserialization. This maintains the <c>Strategy</c> as
/// well as the <c>Filter</c> used to replace template variables.
/// When serialization and deserialization are performed the source is
/// required as it acts as a factory for objects used in the process.
/// <p>
/// For serialization the source object is required as a factory for
/// <c>Schema</c> objects, which are used to visit each field
/// in the class that can be serialized. Also this can be used to get
/// any data entered into the session <c>Map</c> object.
/// <p>
/// When deserializing the source object provides the contextual data
/// used to replace template variables extracted from the XML source.
/// This is performed using the <c>Filter</c> object. Also, as
/// in serialization it acts as a factory for the <c>Schema</c>
/// objects used to examine the serializable fields of an object.
/// </summary>
class Source : Context {
/// <summary>
/// This is used to replace variables within the XML source.
/// </summary>
private TemplateEngine engine;
/// <summary>
/// This is the strategy used to resolve the element classes.
/// </summary>
private Strategy strategy;
/// <summary>
/// This support is used to convert the strings encountered.
/// </summary>
private Support support;
/// <summary>
/// This is used to store the source context attribute values.
/// </summary>
private Session session;
/// <summary>
/// This is the filter used by this object for templating.
/// </summary>
private Filter filter;
/// <summary>
/// This is the style that is used by this source instance.
/// </summary>
private Style style;
/// <summary>
/// This is used to determine whether the read should be strict.
/// </summary>
private bool strict;
/// <summary>
/// Constructor for the <c>Source</c> object. This is used to
/// maintain a context during the serialization process. It holds
/// the <c>Strategy</c> and <c>Context</c> used in the
/// serialization process. The same source instance is used for
/// each XML element evaluated in a the serialization process.
/// </summary>
/// <param name="strategy">
/// this is used to resolve the classes used
/// </param>
/// <param name="support">
/// this is the context used to process strings
/// </param>
/// <param name="style">
/// this is the style used for the serialization
/// </param>
public Source(Strategy strategy, Support support, Style style) {
this(strategy, support, style, true);
}
/// <summary>
/// Constructor for the <c>Source</c> object. This is used to
/// maintain a context during the serialization process. It holds
/// the <c>Strategy</c> and <c>Context</c> used in the
/// serialization process. The same source instance is used for
/// each XML element evaluated in a the serialization process.
/// </summary>
/// <param name="strategy">
/// this is used to resolve the classes used
/// </param>
/// <param name="support">
/// this is the context used to process strings
/// </param>
/// <param name="style">
/// this is the style used for the serialization
/// </param>
/// <param name="strict">
/// this determines whether to read in strict mode
/// </param>
public Source(Strategy strategy, Support support, Style style, bool strict) {
this.filter = new TemplateFilter(this, support);
this.engine = new TemplateEngine(filter);
this.session = new Session();
this.strategy = strategy;
this.support = support;
this.strict = strict;
this.style = style;
}
/// <summary>
/// This is used to determine if the deserialization mode is strict
/// or not. If this is not strict then deserialization will be done
/// in such a way that additional elements and attributes can be
/// ignored. This allows external XML formats to be used without
/// having to match the object structure to the XML fully.
/// </summary>
/// <returns>
/// this returns true if the deserialization is strict
/// </returns>
public bool IsStrict() {
return strict;
}
/// <summary>
/// This is used to acquire the <c>Session</c> object that
/// is used to store the values used within the serialization
/// process. This provides the internal map that is passed to all
/// of the call back methods so that is can be populated.
/// </summary>
/// <returns>
/// this returns the session that is used by this source
/// </returns>
public Session Session {
get {
return session;
}
}
//public Session GetSession() {
// return session;
//}
/// This is used to acquire the <c>Support</c> object.
/// The support object is used to translate strings to and from
/// their object representations and is also used to convert the
/// strings to their template values. This is the single source
/// of translation for all of the strings encountered.
/// </summary>
/// <returns>
/// this returns the support used by the context
/// </returns>
public Support Support {
get {
return support;
}
}
//public Support GetSupport() {
// return support;
//}
/// This is used to acquire the <c>Style</c> for the format.
/// If no style has been set a default style is used, which does
/// not modify the attributes and elements that are used to build
/// the resulting XML document.
/// </summary>
/// <returns>
/// this returns the style used for this format object
/// </returns>
public Style Style {
get {
if(style == null) {
style = new DefaultStyle();
}
return style;
}
}
//public Style GetStyle() {
// if(style == null) {
// style = new DefaultStyle();
// }
// return style;
//}
/// This is used to determine if the type specified is a floating
/// point type. Types that are floating point are the double and
/// float primitives as well as the java types for this primitives.
/// </summary>
/// <param name="type">
/// this is the type to determine if it is a float
/// </param>
/// <returns>
/// this returns true if the type is a floating point
/// </returns>
public bool IsFloat(Class type) {
return support.IsFloat(type);
}
/// <summary>
/// This is used to determine if the type specified is a floating
/// point type. Types that are floating point are the double and
/// float primitives as well as the java types for this primitives.
/// </summary>
/// <param name="type">
/// this is the type to determine if it is a float
/// </param>
/// <returns>
/// this returns true if the type is a floating point
/// </returns>
public bool IsFloat(Type type) {
return IsFloat(type.getType());
}
/// <summary>
/// This is used to determine whether the scanned class represents
/// a primitive type. A primitive type is a type that contains no
/// XML annotations and so cannot be serialized with an XML form.
/// Instead primitives a serialized using transformations.
/// </summary>
/// <param name="type">
/// this is the type to determine if it is primitive
/// </param>
/// <returns>
/// this returns true if no XML annotations were found
/// </returns>
public bool IsPrimitive(Class type) {
return support.IsPrimitive(type);
}
/// <summary>
/// This is used to determine whether the scanned type represents
/// a primitive type. A primitive type is a type that contains no
/// XML annotations and so cannot be serialized with an XML form.
/// Instead primitives a serialized using transformations.
/// </summary>
/// <param name="type">
/// this is the type to determine if it is primitive
/// </param>
/// <returns>
/// this returns true if no XML annotations were found
/// </returns>
public bool IsPrimitive(Type type) {
return IsPrimitive(type.getType());
}
/// <summary>
/// This will create an <c>Instance</c> that can be used
/// to instantiate objects of the specified class. This leverages
/// an internal constructor cache to ensure creation is quicker.
/// </summary>
/// <param name="type">
/// this is the type that is to be instantiated
/// </param>
/// <returns>
/// this will return an object for instantiating objects
/// </returns>
public Instance GetInstance(Class type) {
return support.GetInstance(type);
}
/// <summary>
/// This will create an <c>Instance</c> that can be used
/// to instantiate objects of the specified class. This leverages
/// an internal constructor cache to ensure creation is quicker.
/// </summary>
/// <param name="value">
/// this contains information on the object instance
/// </param>
/// <returns>
/// this will return an object for instantiating objects
/// </returns>
public Instance GetInstance(Value value) {
return support.GetInstance(value);
}
/// <summary>
/// This is used to acquire the name of the specified type using
/// the <c>Root</c> annotation for the class. This will
/// use either the name explicitly provided by the annotation or
/// it will use the name of the class that the annotation was
/// placed on if there is no explicit name for the root.
/// </summary>
/// <param name="type">
/// this is the type to acquire the root name for
/// </param>
/// <returns>
/// this returns the name of the type from the root
/// </returns>
public String GetName(Class type) {
return support.GetName(type);
}
/// <summary>
/// This returns the version for the type specified. The version is
/// used to determine how the deserialization process is performed.
/// If the version of the type is different from the version for
/// the XML document, then deserialization is done in a best effort.
/// </summary>
/// <param name="type">
/// this is the type to acquire the version for
/// </param>
/// <returns>
/// the version that has been set for this XML schema class
/// </returns>
public Version GetVersion(Class type) {
return GetScanner(type).getRevision();
}
/// <summary>
/// This creates a <c>Scanner</c> object that can be used to
/// examine the fields within the XML class schema. The scanner
/// maintains information when a field from within the scanner is
/// visited, this allows the serialization and deserialization
/// process to determine if all required XML annotations are used.
/// </summary>
/// <param name="type">
/// the schema class the scanner is created for
/// </param>
/// <returns>
/// a scanner that can maintains information on the type
/// </returns>
public Scanner GetScanner(Class type) {
return support.GetScanner(type);
}
/// <summary>
/// This will acquire the <c>Decorator</c> for the type.
/// A decorator is an object that adds various details to the
/// node without changing the overall structure of the node. For
/// example comments and namespaces can be added to the node with
/// a decorator as they do not affect the deserialization.
/// </summary>
/// <param name="type">
/// this is the type to acquire the decorator for
/// </param>
/// <returns>
/// this returns the decorator associated with this
/// </returns>
public Decorator GetDecorator(Class type) {
return GetScanner(type).GetDecorator();
}
/// <summary>
/// This is used to acquire the <c>Caller</c> object. This
/// is used to call the callback methods within the object. If the
/// object contains no callback methods then this will return an
/// object that does not invoke any methods that are invoked.
/// </summary>
/// <param name="type">
/// this is the type to acquire the caller for
/// </param>
/// <returns>
/// this returns the caller for the specified type
/// </returns>
public Caller GetCaller(Class type) {
return GetScanner(type).GetCaller(this);
}
/// <summary>
/// This creates a <c>Schema</c> object that can be used to
/// examine the fields within the XML class schema. The schema
/// maintains information when a field from within the schema is
/// visited, this allows the serialization and deserialization
/// process to determine if all required XML annotations are used.
/// </summary>
/// <param name="type">
/// the schema class the schema is created for
/// </param>
/// <returns>
/// a new schema that can track visits within the schema
/// </returns>
public Schema GetSchema(Class type) {
Scanner schema = GetScanner(type);
if(schema == null) {
throw new PersistenceException("Invalid schema class %s", type);
}
return new ClassSchema(schema, this);
}
/// <summary>
/// This is used to acquire the attribute mapped to the specified
/// key. In order for this to return a value it must have been
/// previously placed into the context as it is empty by default.
/// </summary>
/// <param name="key">
/// this is the name of the attribute to retrieve
/// </param>
/// <returns>
/// this returns the value mapped to the specified key
/// </returns>
public Object GetAttribute(Object key) {
return session.Get(key);
}
/// <summary>
/// This is used to resolve and load a class for the given element.
/// The class should be of the same type or a subclass of the class
/// specified. It can be resolved using the details within the
/// provided XML element, if the details used do not represent any
/// serializable values they should be removed so as not to disrupt
/// the deserialization process. For example the default strategy
/// removes all "class" attributes from the given elements.
/// </summary>
/// <param name="type">
/// this is the type of the root element expected
/// </param>
/// <param name="node">
/// this is the element used to resolve an override
/// </param>
/// <returns>
/// returns the type that should be used for the object
/// </returns>
public Value GetOverride(Type type, InputNode node) {
NodeMap<InputNode> map = node.getAttributes();
if(map == null) {
throw new PersistenceException("No attributes for %s", node);
}
return strategy.Read(type, map, session);
}
/// <summary>
/// This is used to attach elements or attributes to the given
/// element during the serialization process. This method allows
/// the strategy to augment the XML document so that it can be
/// deserialized using a similar strategy. For example the
/// default strategy adds a "class" attribute to the element.
/// </summary>
/// <param name="type">
/// this is the field type for the associated value
/// </param>
/// <param name="value">
/// this is the instance variable being serialized
/// </param>
/// <param name="node">
/// this is the element used to represent the value
/// </param>
/// <returns>
/// this returns true if serialization has complete
/// </returns>
public bool SetOverride(Type type, Object value, OutputNode node) {
NodeMap<OutputNode> map = node.getAttributes();
if(map == null) {
throw new PersistenceException("No attributes for %s", node);
}
return strategy.Write(type, value, map, session);
}
/// <summary>
/// Replaces any template variables within the provided string.
/// This is used in the deserialization process to replace
/// variables with system properties, environment variables, or
/// used specified mappings. If a template variable does not have
/// a mapping from the <c>Filter</c> is is left unchanged.
/// </summary>
/// <param name="text">
/// this is processed by the template engine object
/// </param>
/// <returns>
/// this returns the text will all variables replaced
/// </returns>
public String GetProperty(String text) {
return engine.Process(text);
}
}
}
| |
using System;
using System.Linq.Expressions;
using AutoMapper;
using Moq;
using FizzWare.NBuilder;
using NUnit.Framework;
using ReMi.Common.Utils.Repository;
using ReMi.TestUtils.UnitTests;
using ReMi.DataAccess.AutoMapper;
using ReMi.DataAccess.BusinessEntityGateways.Auth;
using ReMi.DataAccess.Exceptions;
using ReMi.DataEntities.BusinessRules;
using BusinessAccount = ReMi.BusinessEntities.Auth.Account;
using DataAccount = ReMi.DataEntities.Auth.Account;
using Role = ReMi.DataEntities.Auth.Role;
namespace ReMi.DataAccess.Tests.Auth
{
[TestFixture]
public class RoleGatewayTests : TestClassFor<RoleGateway>
{
private Mock<IRepository<DataAccount>> _accountRepositoryMock;
private Mock<IRepository<Role>> _roleRepositoryMock;
private Mock<IMappingEngine> _mappingEngineMock;
protected override RoleGateway ConstructSystemUnderTest()
{
_accountRepositoryMock = new Mock<IRepository<DataAccount>>();
_roleRepositoryMock = new Mock<IRepository<Role>>(MockBehavior.Strict);
_mappingEngineMock = new Mock<IMappingEngine>();
return new RoleGateway
{
AccountRepository = _accountRepositoryMock.Object,
RoleRepository = _roleRepositoryMock.Object,
Mapper = _mappingEngineMock.Object
};
}
[TestFixtureSetUp]
public static void AutoMapperInitialize()
{
Mapper.Initialize(
c =>
{
c.AddProfile<BusinessEntityToDataEntityMappingProfile>();
c.AddProfile(new DataEntityToBusinessEntityMappingProfile());
});
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void CreateRole_ShouldRaiseException_WhenRoleIsNull()
{
_roleRepositoryMock.SetupEntities(new Role[0]);
Sut.CreateRole(null);
}
[Test]
[ExpectedException(typeof(RoleAlreadyExistsException))]
public void CreateRole_ShouldRaiseException_WhenExternalIdAlreadyExists()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.Build();
_roleRepositoryMock.SetupEntities(new[] { new Role { ExternalId = role.ExternalId } });
Sut.CreateRole(role);
}
[Test]
[ExpectedException(typeof(RoleAlreadyExistsException))]
public void CreateRole_ShouldRaiseException_WhenNameAlreadyExists()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.Build();
_roleRepositoryMock.SetupEntities(new[] { new Role { Name = role.Name } });
Sut.CreateRole(role);
}
[Test]
[ExpectedException(typeof(RoleAlreadyExistsException))]
public void CreateRole_ShouldRaiseException_WhenDescriptionAlreadyExists()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.Build();
_roleRepositoryMock.SetupEntities(new[] { new Role { Description = role.Description } });
Sut.CreateRole(role);
}
[Test]
public void CreateRole_ShouldInsertIntoRepository_WhenInvoked()
{
_roleRepositoryMock.SetupEntities(new Role[0]);
_roleRepositoryMock.Setup(o => o.Insert(It.IsAny<Role>()));
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.Build();
var dataRole = Builder<Role>.CreateNew()
.With(o => o.ExternalId, role.ExternalId)
.With(o => o.Name, role.Name)
.With(o => o.Description, role.Description)
.Build();
_mappingEngineMock.Setup(o => o.Map<BusinessEntities.Auth.Role, Role>(role))
.Returns(dataRole);
Sut.CreateRole(role);
_roleRepositoryMock.Verify(
o => o.Insert(It.Is<Role>(
row => row.ExternalId == role.ExternalId
&& row.Description == role.Description
&& row.Name == role.Name
)));
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void UpdateRole_ShouldRaiseException_WhenRoleIsNull()
{
_roleRepositoryMock.SetupEntities(new Role[0]);
Sut.UpdateRole(null);
}
[Test]
[ExpectedException(typeof(RoleNotFoundException))]
public void UpdateRole_ShouldRaiseException_WhenExternalIdNotFound()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.Build();
_roleRepositoryMock.SetupEntities(new Role[0]);
Sut.UpdateRole(role);
}
[Test]
[ExpectedException(typeof(RoleAlreadyExistsException))]
public void UpdateRole_ShouldRaiseException_WhenRoleWithTheSimilarNameExists()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, RandomData.RandomString(20))
.Build();
var dataRole1 = Builder<Role>.CreateNew()
.With(o => o.Id, 9)
.With(o => o.ExternalId, role.ExternalId)
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, RandomData.RandomString(20))
.Build();
var dataRole2 = Builder<Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.Name, role.Name)
.With(o => o.Description, RandomData.RandomString(20))
.Build();
_roleRepositoryMock.SetupEntities(new[] { dataRole1, dataRole2 });
Sut.UpdateRole(role);
}
[Test]
[ExpectedException(typeof(RoleAlreadyExistsException))]
public void UpdateRole_ShouldRaiseException_WhenRoleWithTheSimilarDescriptionExists()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, RandomData.RandomString(20))
.Build();
var dataRole1 = Builder<Role>.CreateNew()
.With(o => o.Id, 9)
.With(o => o.ExternalId, role.ExternalId)
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, RandomData.RandomString(20))
.Build();
var dataRole2 = Builder<Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, role.Description)
.Build();
_roleRepositoryMock.SetupEntities(new[] { dataRole1, dataRole2 });
Sut.UpdateRole(role);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Can't update role when attached accounts exists")]
public void UpdateRole_ShouldRaiseException_WhenAttachedAccountsExists()
{
var dataAccount = SetupDataAccount();
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, dataAccount.Role.ExternalId)
.With(o => o.Name, dataAccount.Role.Name)
.With(o => o.Description, dataAccount.Role.Description)
.Build();
var dataRole = Builder<Role>.CreateNew()
.With(o => o.ExternalId, role.ExternalId)
.With(o => o.Name, role.Name)
.With(o => o.Description, role.Description)
.Build();
_roleRepositoryMock.SetupEntities(new[] { dataRole });
_accountRepositoryMock.SetupEntities(new[] { dataAccount });
Sut.UpdateRole(role);
}
[Test]
public void UpdateRole_ShouldUpdateRepository_WhenInvoked()
{
var role = Builder<BusinessEntities.Auth.Role>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, RandomData.RandomString(20))
.Build();
var dataRole = Builder<Role>.CreateNew()
.With(o => o.Id, 9)
.With(o => o.ExternalId, role.ExternalId)
.With(o => o.Name, RandomData.RandomString(20))
.With(o => o.Description, RandomData.RandomString(20))
.Build();
_roleRepositoryMock.SetupEntities(new[] { dataRole });
var checkExternalId = false;
_roleRepositoryMock.Setup(o => o.Update(It.IsAny<Expression<Func<Role, bool>>>(), It.IsAny<Action<Role>>()))
.Returns(new ChangedFields<Role>())
.Callback<Expression<Func<Role, bool>>, Action<Role>>((exp, act) =>
{
checkExternalId = exp.Compile()(dataRole);
act(dataRole);
});
_accountRepositoryMock.SetupEntities(new DataAccount[0]);
Sut.UpdateRole(role);
_roleRepositoryMock.Verify(o => o.Update(It.IsAny<Expression<Func<Role, bool>>>(), It.IsAny<Action<Role>>()));
Assert.IsTrue(checkExternalId);
Assert.AreEqual(role.ExternalId, dataRole.ExternalId);
Assert.AreEqual(role.Name, dataRole.Name);
Assert.AreEqual(role.Description, dataRole.Description);
}
#region Helpers
private DataAccount SetupDataAccount()
{
return SetupDataAccount(Guid.NewGuid());
}
private DataAccount SetupDataAccount(Guid accountId)
{
var dataAccount = Builder<DataAccount>.CreateNew()
.With(o => o.ExternalId, accountId)
.With(o => o.AccountId, RandomData.RandomInt(1, int.MaxValue))
.With(o => o.Role, new Role
{
ExternalId = Guid.NewGuid(),
Name = RandomData.RandomString(30),
Description = RandomData.RandomString(50),
})
.Build();
_accountRepositoryMock.SetupEntities(new[] { dataAccount });
return dataAccount;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//=============================================================================================
// IpsEditor.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function IpsEditor::createUndo( %this, %class, %desc ) {
pushInstantGroup();
%action = new UndoScriptAction() {
class = %class;
superClass = BaseIpsEdAction;
actionName = %desc;
};
popInstantGroup();
return %action;
}
//---------------------------------------------------------------------------------------------
function IpsEditor::submitUndo( %this, %action ) {
%action.addToManager( Editor.getUndoManager() );
}
//=============================================================================================
// BaseIpsEdAction.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function BaseIpsEdAction::sync( %this ) {
// Sync particle state.
if( isObject( %this.particle ) ) {
%this.particle.reload();
IPSP_Editor.guiSync();
if( %this.particle.getId() == IPSP_Editor.currParticle.getId() )
IPSP_Editor.setParticleDirty();
}
// Sync emitter state.
if( isObject( %this.emitter ) ) {
%this.emitter.reload();
IPSE_Editor.guiSync();
if( %this.emitter.getId() == IPSE_Editor.currEmitter.getId() )
IPSE_Editor.setEmitterDirty();
}
}
//---------------------------------------------------------------------------------------------
function BaseIpsEdAction::redo( %this ) {
%this.sync();
}
//---------------------------------------------------------------------------------------------
function BaseIpsEdAction::undo( %this ) {
%this.sync();
}
//=============================================================================================
// ActionRenameEmitter.
//=============================================================================================
//---------------------------------------------------------------------------------------------
//TODO
//=============================================================================================
// ActionCreateNewEmitter.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionCreateNewEmitter::redo( %this ) {
%emitter = %this.emitter;
// Assign name.
%emitter.name = %this.emitterName;
// Remove from unlisted.
IPS_UnlistedEmitters.remove( %emitter );
// Drop it in the dropdown and select it.
%popup = IPSE_Selector;
%popup.add( %emitter.getName(), %emitter.getId() );
%popup.sort();
%popup.setSelected( %emitter.getId() );
// Sync up.
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionCreateNewEmitter::undo( %this ) {
%emitter = %this.emitter;
// Prevent a save dialog coming up on the emitter.
if( %emitter == IPSE_Editor.currEmitter )
IPSE_Editor.setEmitterNotDirty();
// Add to unlisted.
IPS_UnlistedEmitters.add( %emitter );
// Remove it from in the dropdown and select prev emitter.
%popup = IPSE_Selector;
if( isObject( %this.prevEmitter ) )
%popup.setSelected( %this.prevEmitter.getId() );
else
%popup.setFirstSelected();
%popup.clearEntry( %emitter.getId() );
// Unassign name.
%this.emitterName = %emitter.name;
%emitter.name = "";
// Sync up.
Parent::undo( %this );
}
//=============================================================================================
// ActionDeleteEmitter.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionDeleteEmitter::redo( %this ) {
%emitter = %this.emitter;
// Unassign name.
%this.emitterName = %emitter.name;
%emitter.name = "";
// Add to unlisted.
IPS_UnlistedEmitters.add( %emitter );
// Remove from file.
if( %emitter.getFileName() !$= ""
&& %emitter.getFilename() !$= "tlab/IpsEditor/particleEmitterEditor.ed.cs" )
IPS_EmitterSaver.removeObjectFromFile( %emitter );
// Select DefaultEmitter or first in list.
%popup = IPSE_Selector_Control-->PopUpMenu;
%popup.setFirstSelected();
// Remove from dropdown.
%popup.clearEntry( %emitter );
// Sync up.
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionDeleteEmitter::undo( %this ) {
%emitter = %this.emitter;
// Re-assign name.
%emitter.name = %this.emitterName;
// Remove from unlisted.
IPS_UnlistedEmitters.remove( %emitter );
// Resave to file.
if( %this.emitterFname !$= ""
&& %this.emitterFname !$= "tlab/IpsEditor/particleEmitterEditor.ed.gui" ) {
IPS_EmitterSaver.setDirty( %emitter, %this.emitterFname );
IPS_EmitterSaver.saveDirty();
}
// Add it to the dropdown and selet it.
%popup = IPSE_Selector_Control-->PopUpMenu;
%popup.add( %emitter.getName(), %emitter.getId() );
%popup.sort();
%popup.setSelected( %emitter.getId() );
// Sync up.
Parent::undo( %this );
}
//=============================================================================================
// ActionUpdateActiveEmitter.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitter::redo( %this ) {
%emitter = %this.emitter;
%emitter.setFieldValue( %this.field, %this.newValue );
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitter::undo( %this ) {
%emitter = %this.emitter;
%emitter.setFieldValue( %this.field, %this.oldValue );
Parent::undo( %this );
}
//=============================================================================================
// ActionUpdateActiveEmitterLifeFields.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitterLifeFields::redo( %this ) {
%emitter = %this.emitter;
%emitter.lifetimeMS = %this.newValueLifetimeMS;
%emitter.lifetimeVarianceMS = %this.newValueLifetimeVarianceMS;
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitterLifeFields::undo( %this ) {
%emitter = %this.emitter;
%emitter.lifetimeMS = %this.oldValueLifetimeMS;
%emitter.lifetimeVarianceMS = %this.oldValueLifetimeVarianceMS;
Parent::undo( %this );
}
//=============================================================================================
// ActionUpdateActiveEmitterAmountFields.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitterAmountFields::redo( %this ) {
%emitter = %this.emitter;
%emitter.ejectionPeriodMS = %this.newValueEjectionPeriodMS;
%emitter.periodVarianceMS = %this.newValuePeriodVarianceMS;
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitterAmountFields::undo( %this ) {
%emitter = %this.emitter;
%emitter.ejectionPeriodMS = %this.oldValueEjectionPeriodMS;
%emitter.periodVarianceMS = %this.oldValuePeriodVarianceMS;
Parent::undo( %this );
}
//=============================================================================================
// ActionUpdateActiveEmitterSpeedFields.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitterSpeedFields::redo( %this ) {
%emitter = %this.emitter;
%emitter.ejectionVelocity = %this.newValueEjectionVelocity;
%emitter.velocityVariance = %this.newValueVelocityVariance;
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveEmitterSpeedFields::undo( %this ) {
%emitter = %this.emitter;
%emitter.ejectionVelocity = %this.oldValueEjectionVelocity;
%emitter.velocityVariance = %this.oldValueVelocityVariance;
Parent::undo( %this );
}
//=============================================================================================
// ActionCreateNewParticle.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionCreateNewParticle::redo( %this ) {
%particle = %this.particle.getName();
%particleId = %this.particle.getId();
%particleIndex = %this.particleIndex;
%emitter = %this.emitter;
// Remove from unlisted.
IPS_UnlistedParticles.remove( %particleId );
// Add it to the dropdown.
IPSP_Selector.add( %particle, %particleId );
IPSP_Selector.sort();
IPSP_Selector.setSelected( %particleId, false );
// Add particle to dropdowns in the emitter editor.
for( %i = 1; %i < 5; %i ++ ) {
%emitterParticle = "IPSE_EmitterParticle" @ %i;
%popup = %emitterParticle-->PopupMenu;
%popup.add( %particle, %particleId );
%popup.sort();
if( %i == %particleIndex + 1 )
%popup.setSelected( %particleId );
}
// Sync up.
IPSP_Editor.loadNewParticle();
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionCreateNewParticle::undo( %this ) {
%particle = %this.particle.getName();
%particleId = %this.particle.getId();
%emitter = %this.emitter;
// Add to unlisted.
IPS_UnlistedParticles.add( %particleId );
// Remove from dropdown.
IPSP_Selector.clearEntry( %particleId );
IPSP_Selector.setFirstSelected( false );
// Remove from particle dropdowns in emitter editor.
for( %i = 1; %i < 5; %i ++ ) {
%emitterParticle = "IPSE_EmitterParticle" @ %i;
%popup = %emitterParticle-->PopUpMenu;
if( %popup.getSelected() == %particleId )
%popup.setSelected( %this.prevParticle );
%popup.clearEntry( %particleId );
}
// Sync up.
IPSP_Editor.loadNewParticle();
Parent::undo( %this );
}
//=============================================================================================
// ActionDeleteParticle.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionDeleteParticle::redo( %this ) {
%particle = %this.particle.getName();
%particleId = %this.particle.getId();
%emitter = %this.emitter;
// Add to unlisted.
IPS_UnlistedParticles.add( %particleId );
// Remove from file.
if( %particle.getFileName() !$= ""
&& %particle.getFilename() !$= "tlab/IpsEditor/particleIpsEditor.ed.cs" )
IPS_ParticleSaver.removeObjectFromFile( %particleId );
// Remove from dropdown.
IPSP_Selector.clearEntry( %particleId );
IPSP_Selector.setFirstSelected();
// Remove from particle selectors in emitter.
for( %i = 1; %i < 5; %i ++ ) {
%emitterParticle = "IPSE_EmitterParticle" @ %i;
%popup = %emitterParticle-->PopUpMenu;
if( %popup.getSelected() == %particleId ) {
%this.particleIndex = %i - 1;
%popup.setSelected( 0 ); // Select "None".
}
%popup.clearEntry( %particleId );
}
// Sync up.
IPSP_Editor.loadNewParticle();
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionDeleteParticle::undo( %this ) {
%particle = %this.particle.getName();
%particleId = %this.particle.getId();
%particleIndex = %this.particleIndex;
%emitter = %this.emitter;
// Remove from unlisted.
IPS_UnlistedParticles.remove( %particleId );
// Resave to file.
if( %particle.getFilename() !$= ""
&& %particle.getFilename() !$= "tlab/IpsEditor/particleIpsEditor.ed.gui" ) {
IPS_ParticleSaver.setDirty( %particle );
IPS_ParticleSaver.saveDirty();
}
// Add to dropdown.
IPSP_Selector.add( %particle, %particleId );
IPSP_Selector.sort();
IPSP_Selector.setSelected( %particleId );
// Add particle to dropdowns in the emitter editor.
for( %i = 1; %i < 5; %i ++ ) {
%emitterParticle = "IPSE_EmitterParticle" @ %i;
%popup = %emitterParticle-->PopUpMenu;
%popup.add( %particle, %particleId );
%popup.sort();
if( %i == %particleIndex + 1 )
%popup.setSelected( %particleId );
}
// Sync up.
IPSP_Editor.loadNewParticle();
Parent::undo( %This );
}
//=============================================================================================
// ActionUpdateActiveParticle.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveParticle::redo( %this ) {
%particle = %this.particle;
%particle.setFieldValue( %this.field, %this.newValue );
Parent::redo( %this );
}
function ActionUpdateActiveParticle::undo( %this ) {
%particle = %this.particle;
%particle.setFieldValue( %this.field, %this.oldValue );
Parent::undo( %this );
}
//=============================================================================================
// ActionUpdateActiveParticleLifeFields.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveParticleLifeFields::redo( %this ) {
%particle = %this.particle;
%particle.lifetimeMS = %this.newValueLifetimeMS;
%particle.lifetimeVarianceMS = %this.newValueLifetimeVarianceMS;
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveParticleLifeFields::undo( %this ) {
%particle = %this.particle;
%particle.lifetimeMS = %this.oldValueLifetimeMS;
%particle.lifetimeVarianceMS = %this.oldValueLifetimeVarianceMS;
Parent::undo( %this );
}
//=============================================================================================
// ActionUpdateActiveParticleSpinFields.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveParticleSpinFields::redo( %this ) {
%particle = %this.particle;
%particle.spinRandomMax = %this.newValueSpinRandomMax;
%particle.spinRandomMin = %this.newValueSpinRandomMin;
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionUpdateActiveParticleSpinFields::undo( %this ) {
%particle = %this.particle;
%particle.spinRandomMax = %this.oldValueSpinRandomMax;
%particle.spinRandomMin = %this.oldValueSpinRandomMin;
Parent::undo( %this );
}
//=============================================================================================
// ActionCreateNewEmitter.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function ActionCreateNewComposite::redo( %this ) {
%composite = %this.composite;
// Assign name.
%composite.name = %this.compositeName;
// Remove from unlisted.
IPS_UnlistedComposites.remove( %composite );
// Drop it in the dropdown and select it.
%popup = IPSC_Selector;
%popup.add( %composite.getName(), %composite.getId() );
%popup.sort();
%popup.setSelected( %composite.getId() );
// Sync up.
Parent::redo( %this );
}
//---------------------------------------------------------------------------------------------
function ActionCreateNewComposite::undo( %this ) {
%composite = %this.composite;
// Prevent a save dialog coming up on the emitter.
if( %composite == IPSC_Editor.currComposite )
IPSC_Editor.setCompositeNotDirty();
// Add to unlisted.
IPS_UnlistedComposites.add( %composite );
// Remove it from in the dropdown and select prev emitter.
%popup = IPSC_Selector;
if( isObject( %this.prevComposite ) )
%popup.setSelected( %this.prevComposite.getId() );
else
%popup.setFirstSelected();
%popup.clearEntry( %composite.getId() );
// Unassign name.
%this.compositeName = %composite.name;
%composite.name = "";
// Sync up.
Parent::undo( %this );
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest
{
internal abstract IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(TestWorkspace workspace, string fixAllActionEquivalenceKey);
internal abstract IEnumerable<Diagnostic> GetDiagnostics(TestWorkspace workspace);
protected override IList<CodeAction> GetCodeActions(TestWorkspace workspace, string fixAllActionEquivalenceKey)
{
var diagnostics = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey);
return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList();
}
internal Tuple<Diagnostic, CodeFixCollection> GetDiagnosticAndFix(TestWorkspace workspace, string fixAllActionEquivalenceKey = null)
{
return GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceKey).FirstOrDefault();
}
protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
span = hostDocument.SelectedSpans.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span)
{
var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any());
if (hostDocument == null)
{
document = null;
span = default(TextSpan);
return false;
}
span = hostDocument.SelectedSpans.Single();
document = workspace.CurrentSolution.GetDocument(hostDocument.Id);
return true;
}
protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any());
var annotatedSpan = hostDocument.AnnotatedSpans.Single();
annotation = annotatedSpan.Key;
span = annotatedSpan.Value.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected FixAllScope GetFixAllScope(string annotation)
{
switch (annotation)
{
case "FixAllInDocument":
return FixAllScope.Document;
case "FixAllInProject":
return FixAllScope.Project;
case "FixAllInSolution":
return FixAllScope.Solution;
}
throw new InvalidProgramException("Incorrect FixAll annotation in test");
}
internal IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
string annotation,
string fixAllActionId)
{
foreach (var diagnostic in diagnostics)
{
if (annotation == null)
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(a, d)), CancellationToken.None);
fixer.RegisterCodeFixesAsync(context).Wait();
if (fixes.Any())
{
var codeFix = new CodeFixCollection(fixer, diagnostic.Location.SourceSpan, fixes);
yield return Tuple.Create(diagnostic, codeFix);
}
}
else
{
var fixAllProvider = fixer.GetFixAllProvider();
Assert.NotNull(fixAllProvider);
FixAllScope scope = GetFixAllScope(annotation);
Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync =
(d, diagIds, c) =>
{
var root = d.GetSyntaxRootAsync().Result;
var diags = testDriver.GetDocumentDiagnostics(provider, d, root.FullSpan);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return Task.FromResult(diags);
};
Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync =
(p, includeAllDocumentDiagnostics, diagIds, c) =>
{
var diags = includeAllDocumentDiagnostics ?
testDriver.GetAllDiagnostics(provider, p) :
testDriver.GetProjectDiagnostics(provider, p);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return Task.FromResult(diags);
};
var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id);
var fixAllDiagnosticProvider = new FixAllCodeActionContext.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);
var fixAllContext = new FixAllContext(document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None);
var fixAllFix = fixAllProvider.GetFixAsync(fixAllContext).WaitAndGetResult(CancellationToken.None);
if (fixAllFix != null)
{
var codeFix = new CodeFixCollection(fixAllProvider, diagnostic.Location.SourceSpan, ImmutableArray.Create(new CodeFix(fixAllFix, diagnostic)));
yield return Tuple.Create(diagnostic, codeFix);
}
}
}
}
protected void TestEquivalenceKey(string initialMarkup, string equivalenceKey)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions: null, compilationOptions: null))
{
var diagnosticAndFix = GetDiagnosticAndFix(workspace);
Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey);
}
}
protected void TestActionCountInAllFixes(
string initialMarkup,
int count,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var diagnosticAndFix = GetDiagnosticAndFixes(workspace, null);
var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum();
Assert.Equal(count, diagnosticCount);
}
}
protected void TestSpans(
string initialMarkup, string expectedMarkup,
int index = 0,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null,
string diagnosticId = null, string fixAllActionEquivalenceId = null)
{
IList<TextSpan> spansList;
string unused;
MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList);
var expectedTextSpans = spansList.ToSet();
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
ISet<TextSpan> actualTextSpans;
if (diagnosticId == null)
{
var diagnosticsAndFixes = GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceId);
var diagnostics = diagnosticsAndFixes.Select(t => t.Item1);
actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet();
}
else
{
var diagnostics = GetDiagnostics(workspace);
actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet();
}
Assert.True(expectedTextSpans.SetEquals(actualTextSpans));
}
}
protected void TestAddDocument(
string initialMarkup, string expectedMarkup,
IList<string> expectedContainers,
string expectedDocumentName,
int index = 0,
bool compareTokens = true, bool isLine = true)
{
TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine);
TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine);
}
private void TestAddDocument(
string initialMarkup, string expectedMarkup,
int index,
IList<string> expectedContainers,
string expectedDocumentName,
ParseOptions parseOptions, CompilationOptions compilationOptions,
bool compareTokens, bool isLine)
{
using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup))
{
var diagnosticAndFix = GetDiagnosticAndFix(workspace);
TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
diagnosticAndFix.Item2.Fixes.Select(f => f.Action).ToList(), compareTokens);
}
}
private void TestAddDocument(
TestWorkspace workspace,
string expectedMarkup,
int index,
IList<string> expectedFolders,
string expectedDocumentName,
IList<CodeAction> actions,
bool compareTokens)
{
var operations = VerifyInputsAndGetOperations(index, actions);
TestAddDocument(
workspace,
expectedMarkup,
operations,
hasProjectChange: false,
modifiedProjectId: null,
expectedFolders: expectedFolders,
expectedDocumentName: expectedDocumentName,
compareTokens: compareTokens);
}
private Tuple<Solution, Solution> TestAddDocument(
TestWorkspace workspace,
string expected,
IEnumerable<CodeActionOperation> operations,
bool hasProjectChange,
ProjectId modifiedProjectId,
IList<string> expectedFolders,
string expectedDocumentName,
bool compareTokens)
{
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1;
var newSolution = appliedChanges.Item2;
Document addedDocument = null;
if (!hasProjectChange)
{
addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
}
else
{
Assert.NotNull(modifiedProjectId);
addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
}
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(
expected, addedDocument.GetTextAsync().Result.ToString(), GetLanguage());
}
else
{
Assert.Equal(expected, addedDocument.GetTextAsync().Result.ToString());
}
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
if (!hasProjectChange)
{
// If there is just one document change then we expect the preview to be a WpfTextView
var content = editHandler.GetPreviews(workspace, operations, CancellationToken.None).TakeNextPreviewAsync().PumpingWaitResult();
var diffView = content as IWpfDifferenceViewer;
Assert.NotNull(diffView);
diffView.Close();
}
else
{
// If there are more changes than just the document we need to browse all the changes and get the document change
var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None);
bool hasPreview = false;
object preview;
while ((preview = contents.TakeNextPreviewAsync().PumpingWaitResult()) != null)
{
var diffView = preview as IWpfDifferenceViewer;
if (diffView != null)
{
hasPreview = true;
diffView.Close();
break;
}
}
Assert.True(hasPreview);
}
return Tuple.Create(oldSolution, newSolution);
}
internal void TestWithMockedGenerateTypeDialog(
string initial,
string languageName,
string typeName,
string expected = null,
bool isLine = true,
bool isMissing = false,
Accessibility accessibility = Accessibility.NotApplicable,
TypeKind typeKind = TypeKind.Class,
string projectName = null,
bool isNewFile = false,
string existingFilename = null,
IList<string> newFileFolderContainers = null,
string fullFilePath = null,
string newFileName = null,
string assertClassName = null,
bool checkIfUsingsIncluded = false,
bool checkIfUsingsNotIncluded = false,
string expectedTextWithUsings = null,
string defaultNamespace = "",
bool areFoldersValidIdentifiers = true,
GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null,
IList<TypeKindOptions> assertTypeKindPresent = null,
IList<TypeKindOptions> assertTypeKindAbsent = null,
bool isCancelled = false)
{
using (var testState = new GenerateTypeTestState(initial, isLine, projectName, typeName, existingFilename, languageName))
{
// Initialize the viewModel values
testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions(
accessibility: accessibility,
typeKind: typeKind,
typeName: testState.TypeName,
project: testState.ProjectToBeModified,
isNewFile: isNewFile,
newFileName: newFileName,
folders: newFileFolderContainers,
fullFilePath: fullFilePath,
existingDocument: testState.ExistingDocument,
areFoldersValidIdentifiers: areFoldersValidIdentifiers,
isCancelled: isCancelled);
testState.TestProjectManagementService.SetDefaultNamespace(
defaultNamespace: defaultNamespace);
var diagnosticsAndFixes = GetDiagnosticAndFixes(testState.Workspace, null);
var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id));
if (isMissing)
{
Assert.Null(generateTypeDiagFixes);
return;
}
var fixes = generateTypeDiagFixes.Item2.Fixes;
Assert.NotNull(fixes);
var fixActions = fixes.Select(f => f.Action);
Assert.NotNull(fixActions);
// Since the dialog option is always fed as the last CodeAction
var index = fixActions.Count() - 1;
var action = fixActions.ElementAt(index);
Assert.Equal(action.Title, FeaturesResources.GenerateNewType);
var operations = action.GetOperationsAsync(CancellationToken.None).Result;
Tuple<Solution, Solution> oldSolutionAndNewSolution = null;
if (!isNewFile)
{
oldSolutionAndNewSolution = TestOperations(
testState.Workspace, expected, operations,
conflictSpans: null, renameSpans: null, warningSpans: null,
compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id);
}
else
{
oldSolutionAndNewSolution = TestAddDocument(
testState.Workspace,
expected,
operations,
projectName != null,
testState.ProjectToBeModified.Id,
newFileFolderContainers,
newFileName,
compareTokens: false);
}
if (checkIfUsingsIncluded)
{
Assert.NotNull(expectedTextWithUsings);
TestOperations(testState.Workspace, expectedTextWithUsings, operations,
conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false,
expectedChangedDocumentId: testState.InvocationDocument.Id);
}
if (checkIfUsingsNotIncluded)
{
var oldSolution = oldSolutionAndNewSolution.Item1;
var newSolution = oldSolutionAndNewSolution.Item2;
var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution);
Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id));
}
// Added into a different project than the triggering project
if (projectName != null)
{
var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations);
var newSolution = appliedChanges.Item2;
var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id);
// Make sure the Project reference is present
Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id));
}
// Assert Option Calculation
if (assertClassName != null)
{
Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName);
}
if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null)
{
var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions;
if (assertGenerateTypeDialogOptions != null)
{
Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility);
Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions);
Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute);
}
if (assertTypeKindPresent != null)
{
foreach (var typeKindPresentEach in assertTypeKindPresent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0);
}
}
if (assertTypeKindAbsent != null)
{
foreach (var typeKindPresentEach in assertTypeKindAbsent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0);
}
}
}
}
}
}
}
| |
/**********************************************************************
*
* Update Controls .NET
* Copyright 2010 Michael L Perry
* MIT License
*
* http://updatecontrols.net
* http://www.codeplex.com/updatecontrols/
*
**********************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Assisticant
{
/// <summary>
/// Base class for <see cref="Observable"/> and <see cref="Computed"/> sentries.
/// </summary>
/// <threadsafety static="true" instance="true"/>
/// <remarks>
/// This class is for internal use only.
/// </remarks>
public abstract class Precedent
{
const int _maxArraySize = 16;
WeakReference[] _computedArray;
WeakHashSet<Computed> _computedHash;
/// <summary>
/// Method called when the first dependent references this field. This event only
/// fires when HasDependents goes from false to true. If the field already
/// has dependents, then this event does not fire.
/// </summary>
protected virtual void GainDependent()
{
}
/// <summary>
/// Method called when the last dependent goes out-of-date. This event
/// only fires when HasDependents goes from true to false. If the field has
/// other dependents, then this event does not fire. If the dependent is
/// currently updating and it still depends upon this field, then the
/// GainComputed event will be fired immediately.
/// </summary>
protected virtual void LoseDependent()
{
}
/// <summary>
/// Establishes a relationship between this precedent and the currently
/// updating dependent.
/// </summary>
internal void RecordDependent()
{
// Get the current dependent.
Computed update = Computed.GetCurrentUpdate();
if (update != null && !Contains(update) && update.AddPrecedent(this))
{
if (Insert(update))
GainDependent();
}
else if (!Any())
{
// Though there is no lasting dependency, someone
// has shown interest.
GainDependent();
LoseDependent();
}
}
/// <summary>
/// Makes all direct and indirect dependents out of date.
/// </summary>
internal void MakeDependentsOutOfDate()
{
if (_computedArray != null)
{
foreach (var computed in WeakArray.Enumerate<Computed>(_computedArray).ToList())
computed.MakeOutOfDate();
}
else if (_computedHash != null)
{
foreach (var computed in _computedHash.ToList())
computed.MakeOutOfDate();
}
}
internal void RemoveDependent(Computed dependent)
{
if (Delete(dependent))
LoseDependent();
}
/// <summary>
/// True if any other fields depend upon this one.
/// </summary>
/// <remarks>
/// If any dependent field has used this observable field while updating,
/// then HasDependents is true. When that dependent becomes out-of-date,
/// however, it no longer depends upon this field.
/// <para/>
/// This property is useful for caching. When all dependents are up-to-date,
/// check this property for cached fields. If it is false, then nothing
/// depends upon the field, and it can be unloaded. Be careful not to
/// unload the cache while dependents are still out-of-date, since
/// those dependents may in fact need the field when they update.
/// </remarks>
public bool HasDependents
{
get { return Any(); }
}
private bool Insert(Computed update)
{
lock (this)
{
if (_computedHash != null)
{
_computedHash.Add(update);
return false;
}
if (WeakArray.Contains(ref _computedArray, update))
return false;
bool first = _computedArray == null;
if (WeakArray.GetCount(ref _computedArray) >= _maxArraySize)
{
_computedHash = new WeakHashSet<Computed>();
foreach (var item in WeakArray.Enumerate<Computed>(_computedArray))
_computedHash.Add(item);
_computedArray = null;
_computedHash.Add(update);
return false;
}
WeakArray.Add(ref _computedArray, update);
return first;
}
}
private bool Delete(Computed dependent)
{
lock (this)
{
if (_computedArray != null)
{
WeakArray.Remove(ref _computedArray, dependent);
return _computedArray == null;
}
else if (_computedHash != null)
{
_computedHash.Remove(dependent);
if (_computedHash.Count == 0)
{
_computedHash = null;
return true;
}
return false;
}
else
return false;
}
}
private bool Contains(Computed update)
{
lock (this)
{
if (_computedArray != null)
return WeakArray.Contains(ref _computedArray, update);
else if (_computedHash != null)
return _computedHash.Contains(update);
else
return false;
}
}
private bool Any()
{
lock (this)
{
return _computedArray != null || _computedHash != null;
}
}
public override string ToString()
{
return VisualizerName(true);
}
#region Debugger Visualization
/// <summary>Gets or sets a flag that allows extra debug features.</summary>
/// <remarks>
/// This flag currently just controls automatic name detection for untitled
/// NamedObservables, and other precedents that were created without a name
/// by calling <see cref="Observable.New"/>() or <see cref="Computed.New"/>(),
/// including dependents created implicitly by <see cref="GuiUpdateHelper"/>.
/// <para/>
/// DebugMode should be enabled before creating any Assisticant sentries,
/// otherwise some of them may never get a name. For example, if
/// Indepedent.New() is called (without arguments) when DebugMode is false,
/// a "regular" <see cref="Observable"/> is created that is incapable of
/// having a name.
/// <para/>
/// DebugMode may slow down your program. In particular, if you use named
/// observables (or <see cref="Observable{T}"/>) but do not explicitly
/// specify a name, DebugMode will cause them to compute their names based
/// on a stack trace the first time OnGet() is called; this process is
/// expensive if it is repeated for a large number of Observables.
/// </remarks>
public static bool DebugMode { get; set; }
public virtual string VisualizerName(bool withValue)
{
return VisNameWithOptionalHash(GetType().Name, withValue);
}
protected string VisNameWithOptionalHash(string name, bool withHash)
{
if (withHash) {
// Unless VisualizerName has been overridden, we have no idea what
// value is associated with the Precedent. Include an ID code so
// that the user has a chance to detect duplicates (that is, when
// he sees two Observables with the same code, they are probably
// the same Observable.)
return string.Format("{0} #{1:X5}", name, GetHashCode() & 0xFFFFF);
} else
return name;
}
protected class DependentVisualizer
{
Precedent _self;
public DependentVisualizer(Precedent self) { _self = self; }
public override string ToString() { return _self.VisualizerName(true); }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public DependentVisualizer[] Items
{
get {
var list = new List<DependentVisualizer>();
lock (_self)
{
if (_self._computedArray != null)
{
foreach (var item in WeakArray.Enumerate<Computed>(_self._computedArray))
list.Add(new DependentVisualizer(item));
}
else if (_self._computedHash != null)
{
foreach (var item in _self._computedHash)
list.Add(new DependentVisualizer(item));
}
list.Sort((a, b) => a.ToString().CompareTo(b.ToString()));
// Return as array so that the debugger doesn't offer a useless "Raw View"
return list.ToArray();
}
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Windows.Forms;
using System.Text;
using DAQ.Environment;
using DAQ.HAL;
using Data;
using Data.Scans;
using ScanMaster.GUI;
using ScanMaster.Acquire;
using ScanMaster.Acquire.Test;
using ScanMaster.Acquire.Plugin;
using ScanMaster.Analyze;
namespace ScanMaster
{
/// <summary>
/// The controller is the heart of ScanMaster. The application is built around this
/// controller, which gets the execution thread early on in application startup (look
/// at the Main method in Runner).
///
/// The controller is a singleton (there is only ever one controller). And I really mean
/// only one - as in there is only ever one running on the machine. There are two ways to
/// get hold of a reference to the controller object. If you are in the same (local) context
/// that the Controller was instantiated in (which means, almost certainly, that you are writing
/// code that is part of ScanMaster) then you should use the static factory method
/// Controller.GetController(). If you are outside the Controller's context (which means you are
/// probably writing another application that wants to use ScanMaster's services) then you should
/// get hold of an object reference through the remoting system. You might well do this by
/// registering the Controller type as well known within your application and then using new to
/// to get a reference, but you shouldn't forget that you're actually dealing with a singleton !
///
/// The controller is published at "tcp://localhost:1170/controller.rem".
///
/// The controller inherits from MarshalByRefObject so that references to it can be passed
/// around by the remoting system.
/// </summary>
public class Controller : MarshalByRefObject
{
#region Class members
public enum AppState {stopped, running};
private ControllerWindow controllerWindow;
private Acquisitor acquisitor;
public Acquisitor Acquisitor
{
get { return acquisitor; }
}
public ScanSerializer serializer = new ScanSerializer();
private ProfileManager profileManager = new ProfileManager();
public ProfileManager ProfileManager
{
get { return profileManager; }
}
private ViewerManager viewerManager = new ViewerManager();
public ViewerManager ViewerManager
{
get { return viewerManager; }
}
private DataStore dataStore = new DataStore();
public DataStore DataStore
{
get { return dataStore; }
}
private ParameterHelper parameterHelper = new ParameterHelper();
public ParameterHelper ParameterHelper
{
get { return parameterHelper;}
}
private static Controller controllerInstance;
public AppState appState = AppState.stopped;
#endregion
#region Initialisation
// This is the right way to get a reference to the controller. You shouldn't create a
// controller yourself.
public static Controller GetController()
{
if (controllerInstance == null)
{
controllerInstance = new Controller();
}
return controllerInstance;
}
// without this method, any remote connections to this object will time out after
// five minutes of inactivity.
// It just overrides the lifetime lease system completely.
public override Object InitializeLifetimeService()
{
return null;
}
// This function is called at the very start of application execution.
public void StartApplication()
{
// make an acquisitor and connect ourself to its events
acquisitor = new Acquisitor();
acquisitor.Data += new DataEventHandler(DataHandler);
acquisitor.ScanFinished += new ScanFinishedEventHandler(ScanFinishedHandler);
controllerWindow = new ControllerWindow(this);
controllerWindow.Show();
// initialise the profile manager
profileManager.Window = controllerWindow;
profileManager.Start();
// try to load in the last profile set
// first deserialize the profile set path
//try
//{
// BinaryFormatter bf = new BinaryFormatter();
// String settingsPath = (string)Environs.FileSystem.Paths["settingsPath"];
// String filePath = settingsPath + "\\ScanMaster\\profilePath.bin";
// FileStream fs = File.Open(filePath, FileMode.Open);
// lastProfileSetPath = (string)bf.Deserialize(fs);
// fs.Close();
//}
//catch (Exception)
//{
// Console.Error.WriteLine("Couldn't find saved profile path");
//}
//try
//{
// if (lastProfileSetPath != null) LoadProfileSet(lastProfileSetPath);
//}
//catch (Exception e)
//{
// Console.Error.WriteLine("Couldn't load last profile set");
// Console.Error.WriteLine(e.Message);
//}
// initialise the parameter helper
parameterHelper = new ParameterHelper();
parameterHelper.Initialise();
// connect the acquisitor to the profile manager, which will send it events when the
// user is in tweak mode.
profileManager.Tweak +=new TweakEventHandler(acquisitor.HandleTweak);
// Get access to any other applications required
Environs.Hardware.ConnectApplications();
// run the main event loop
Application.Run(controllerWindow);
}
// When the main window gets told to shut, it calls this function.
// In here things that need to be done before the application stops
// are sorted out.
public void StopApplication()
{
AcquireStop();
profileManager.Exit();
// serialize the lastProfileSet path
if (lastProfileSetPath != null)
{
BinaryFormatter bf = new BinaryFormatter();
String settingsPath = (string)Environs.FileSystem.Paths["settingsPath"];
String filePath = settingsPath + "\\ScanMaster\\profilePath.bin";
FileStream fs = File.Open(filePath, FileMode.Create);
bf.Serialize(fs, lastProfileSetPath);
fs.Close();
}
parameterHelper.Exit();
}
#endregion
#region Local functions - these should only be called locally
// Main window File->Save
public void SaveData()
{
// saves a zip file containing each scan, plus the average
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "zipped xml data file|*.zip";
saveFileDialog1.Title = "Save scan data";
saveFileDialog1.InitialDirectory = Environs.FileSystem.GetDataDirectory(
(String)Environs.FileSystem.Paths["scanMasterDataPath"]);
saveFileDialog1.FileName = Environs.FileSystem.GenerateNextDataFileName();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != "")
{
SaveData(saveFileDialog1.FileName);
}
}
}
// Main window File->Save Average
public void SaveAverageData()
{
// serialize the average scan as zipped xml
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "zipped xml data file|*.zip";
saveFileDialog1.Title = "Save averaged scan data";
saveFileDialog1.InitialDirectory = Environs.FileSystem.GetDataDirectory(
(String)Environs.FileSystem.Paths["scanMasterDataPath"]);
saveFileDialog1.FileName = Environs.FileSystem.GenerateNextDataFileName();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != "")
{
SaveAverageData((System.IO.FileStream)saveFileDialog1.OpenFile());
}
}
}
// Main window File->Load Average
public void LoadData()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "zipped xml data|*.zip";
dialog.Title = "Open profile set";
dialog.InitialDirectory = Environs.FileSystem.GetDataDirectory(
(String)Environs.FileSystem.Paths["scanMasterDataPath"]);
dialog.ShowDialog();
if(dialog.FileName != "") LoadData(dialog.FileName);
}
private String lastProfileSetPath;
public void LoadProfileSet()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "xml profile set|*.xml";
dialog.Title = "Open profile set";
dialog.InitialDirectory = Environs.FileSystem.Paths["settingsPath"] + "ScanMaster";
dialog.ShowDialog();
if(dialog.FileName != "")
{
System.IO.FileStream fs =
(System.IO.FileStream)dialog.OpenFile();
profileManager.LoadProfileSetFromXml(fs);
fs.Close();
lastProfileSetPath = dialog.FileName;
UpdateWindowTitle(dialog.FileName);
}
}
private void LoadProfileSet(string path)
{
System.IO.FileStream fs = File.Open(path, FileMode.Open);
profileManager.LoadProfileSetFromXml(fs);
fs.Close();
lastProfileSetPath = path;
UpdateWindowTitle(path);
}
public void SaveProfileSet()
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "xml profile set|*.xml";
dialog.Title = "Save profile set";
dialog.InitialDirectory = Environs.FileSystem.Paths["settingsPath"] + "ScanMaster";
dialog.ShowDialog();
if(dialog.FileName != "")
{
System.IO.FileStream fs =
(System.IO.FileStream)dialog.OpenFile();
profileManager.SaveProfileSetAsXml(fs);
fs.Close();
UpdateWindowTitle(dialog.FileName);
}
}
// puts the current profile's filename in the window title
private void UpdateWindowTitle(string path)
{
string[] pathBits = path.Split(new char[] { '\\' });
string profileName = pathBits[pathBits.Length - 1];
controllerWindow.SetWindowTitle("ScanMaster 2k8 - " + profileName);
}
#endregion
#region Remote functions - these functions can be called remotely
// this method prepares the application for remote control
public void CaptureRemote()
{
controllerWindow.DisableMenus();
}
// remote clients call this to release control
public void ReleaseRemote()
{
controllerWindow.EnableMenus();
}
// Selecting Acquire->Start on the main window will result in this function being called.
// If numberOfScans == -1, the acquisitor will scan forever.
public void AcquireStart(int numberOfScans)
{
if (appState != AppState.running)
{
if (profileManager.CurrentProfile == null)
{
MessageBox.Show("No profile selected !", "Profile error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}
Profile currentProfile = profileManager.GetCloneOfCurrentProfile();
// clear stored data
dataStore.ClearAll();
// delete any temporary files
string tempPath = Environment.GetEnvironmentVariable("TEMP") + "\\ScanMasterTemp";
if (Directory.Exists(tempPath))
{
string[] tempFiles = Directory.GetFiles(tempPath);
foreach (string file in tempFiles) File.Delete(file);
}
// tell the viewers that acquisition is starting
viewerManager.AcquireStart();
// start the acquisition
acquisitor.Configuration = currentProfile.AcquisitorConfig;
WriteScanSettings(DataStore.TotalScan);
acquisitor.AcquireStart(numberOfScans);
appState = AppState.running;
}
}
// Selecting Acquire->Stop on the front panel will result in this function being called.
public void AcquireStop()
{
if (appState == AppState.running)
{
acquisitor.AcquireStop();
appState = AppState.stopped;
// tell the viewers acquisition has stopped
viewerManager.AcquireStop();
}
}
public void AcquireAndWait(int numberOfScans)
{
Monitor.Enter(acquisitor.AcquisitorMonitorLock);
AcquireStart(numberOfScans);
// check that acquisition is underway. Provided it is, release the lock
if (appState == AppState.running) Monitor.Wait(acquisitor.AcquisitorMonitorLock);
Monitor.Exit(acquisitor.AcquisitorMonitorLock);
AcquireStop();
}
bool patternRunning = false;
// outputs the pattern from the currently selected profile - used by BlockHead
public void OutputPattern()
{
if (!patternRunning)
{
PatternPlugin pgPlugin = profileManager.CurrentProfile.AcquisitorConfig.pgPlugin;
YAGPlugin yagPlugin = profileManager.CurrentProfile.AcquisitorConfig.yagPlugin;
pgPlugin.AcquisitionStarting();
yagPlugin.AcquisitionStarting();
pgPlugin.ScanStarting();
yagPlugin.ScanStarting();
patternRunning = true;
}
}
// stop outputting the pattern started above
public void StopPatternOutput()
{
if (patternRunning)
{
PatternPlugin pgPlugin = profileManager.CurrentProfile.AcquisitorConfig.pgPlugin;
YAGPlugin yagPlugin = profileManager.CurrentProfile.AcquisitorConfig.yagPlugin;
yagPlugin.AcquisitionFinished();
pgPlugin.AcquisitionFinished();
controllerWindow.EnableMenus();
patternRunning = false;
}
}
// select a profile by name
public void SelectProfile(String profile)
{
profileManager.SelectProfile(profile);
}
// change a parameter in the current profile. The way that the plugin is selected is a cheesy hack -
// clearly the commandProcessor/pluginManager/settingsReflector design is inadequate
// The group mode flag is also a cheesy hack, but might be quite useful
public void AdjustProfileParameter(String plugin, String parameter, String newValue, bool groupMode)
{
SettingsReflector sr = new SettingsReflector();
if (!groupMode)
{
sr.SetField(profileManager.Processor.PluginForString(profileManager.CurrentProfile, plugin),
parameter, newValue);
}
else
{
ArrayList profiles = profileManager.ProfilesInGroup(profileManager.CurrentProfile.Group);
foreach (Profile p in profiles)
sr.SetField(profileManager.Processor.PluginForString(p, plugin), parameter, newValue);
}
}
// this is a bit unclean ! It lets you pull out a setting from the PG plugin. Mainly a hack
// to get BlockHead working
public object GetPGSetting(String key)
{
return profileManager.CurrentProfile.AcquisitorConfig.pgPlugin.Settings[key];
}
public PluginSettings GetPGSettings()
{
return profileManager.CurrentProfile.AcquisitorConfig.pgPlugin.Settings;
}
// this is even more cheesy !
public object GetShotSetting(String key)
{
return profileManager.CurrentProfile.AcquisitorConfig.shotGathererPlugin.Settings[key];
}
public object GetOutputSetting(String key)
{
return profileManager.CurrentProfile.AcquisitorConfig.outputPlugin.Settings[key];
}
// Saves the scan data to the specified file
public void SaveData(string filename)
{
System.IO.FileStream fs = new FileStream(filename, FileMode.Create);
serializer.PrepareZip(fs);
string tempPath = Environment.GetEnvironmentVariable("TEMP") + "\\ScanMasterTemp";
for (int k = 1; k <= DataStore.NumberOfScans; k++)
{
Scan sc = serializer.DeserializeScanAsBinary(tempPath + "\\scan_" + k.ToString());
serializer.AppendToZip(sc, "scan_" + k.ToString() + ".xml");
}
serializer.AppendToZip(DataStore.AverageScan, "average.xml");
serializer.CloseZip();
fs.Close();
Console.WriteLine(((int)(DataStore.AverageScan.GetSetting("out", "pointsPerScan"))).ToString());
}
// Saves the latest average scan in the datastore to the given filestream
public void SaveAverageData( System.IO.FileStream fs )
{
serializer.SerializeScanAsZippedXML(fs, dataStore.AverageScan, "average.xml");
fs.Close();
}
public void SaveAverageData( String filePath )
{
SaveAverageData( File.Create(filePath) );
}
public void LoadData( String path )
{
Scan scan = serializer.DeserializeScanFromZippedXML(path, "average.xml");
dataStore.AverageScan = scan;
viewerManager.NewScanLoaded();
}
#endregion
#region Private functions
// This function is registered to handle data events from the acquisitor.
// Whenever the acquisitor has new data it will call this function.
// Note well that this will be called on the acquisitor thread (meaning
// no direct GUI manipulation in this function).
private void DataHandler(object sender, DataEventArgs e)
{
lock (this)
{
// grab the settings
GUIConfiguration guiConfig = profileManager.CurrentProfile.GUIConfig;
// store the datapoint
dataStore.AddScanPoint(e.point);
// tell the viewers to handle the data point
viewerManager.HandleDataPoint(e);
}
}
// a method for saving the acquisitior settings into the scan
private void WriteScanSettings(Scan scan)
{
PluginSettings st;
ICollection keys;
scan.ScanSettings.Add("out:pluginName", acquisitor.Configuration.outputPlugin.GetType().ToString());
scan.ScanSettings.Add("switch:pluginName", acquisitor.Configuration.switchPlugin.GetType().ToString());
scan.ScanSettings.Add("shot:pluginName", acquisitor.Configuration.shotGathererPlugin.GetType().ToString());
scan.ScanSettings.Add("pg:pluginName", acquisitor.Configuration.pgPlugin.GetType().ToString());
scan.ScanSettings.Add("yag:pluginName", acquisitor.Configuration.yagPlugin.GetType().ToString());
scan.ScanSettings.Add("analog:pluginName", acquisitor.Configuration.analogPlugin.GetType().ToString());
// settings from the output plugin
st = acquisitor.Configuration.outputPlugin.Settings;
keys = st.Keys;
foreach (String key in keys) scan.ScanSettings.Add("out:" + key, st[key]);
// settings from the switch plugin
st = acquisitor.Configuration.switchPlugin.Settings;
keys = st.Keys;
foreach (String key in keys) scan.ScanSettings.Add("switch:" + key, st[key]);
// settings from the shot gatherer plugin
st = acquisitor.Configuration.shotGathererPlugin.Settings;
keys = st.Keys;
foreach (String key in keys) scan.ScanSettings.Add("shot:" + key, st[key]);
// settings from the pattern plugin
st = acquisitor.Configuration.pgPlugin.Settings;
keys = st.Keys;
foreach (String key in keys) scan.ScanSettings.Add("pg:" + key, st[key]);
// settings from the yag plugin
st = acquisitor.Configuration.yagPlugin.Settings;
keys = st.Keys;
foreach (String key in keys) scan.ScanSettings.Add("yag:" + key, st[key]);
// settings from the analog plugin
st = acquisitor.Configuration.analogPlugin.Settings;
keys = st.Keys;
foreach (String key in keys) scan.ScanSettings.Add("analog:" + key, st[key]);
}
// This function is registered with the acquisitor to handle
// scan finished events.
// Note well that this will be called on the acquisitor thread (meaning
// no direct GUI manipulation in this function).
private void ScanFinishedHandler(object sender, EventArgs e)
{
lock (this)
{
// update the datastore
dataStore.UpdateTotal();
// save the acquisitior settings in the scan
WriteScanSettings(DataStore.CurrentScan);
// serialize the last scan
string tempPath = Environment.GetEnvironmentVariable("TEMP") + "\\ScanMasterTemp";
if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
serializer.SerializeScanAsBinary(tempPath + "\\scan_" +
dataStore.NumberOfScans.ToString(), dataStore.CurrentScan);
dataStore.ClearCurrentScan();
// tell the viewers that the scan is finished
viewerManager.ScanFinished();
// hint to the GC that now might be a good time
GC.Collect();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security;
#if FEATURE_SECURITY_PERMISSIONS
using System.Security.Permissions;
#endif
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Collections;
namespace Microsoft.Build.Utilities
{
/// <summary>
/// This class represents a single item of the project, as it is passed into a task. TaskItems do not exactly correspond to
/// item elements in project files, because then tasks would have access to data that wasn't explicitly passed into the task
/// via the project file. It's not a security issue, but more just an issue with project file clarity and transparency.
///
/// Note: This class has to be sealed. It has to be sealed because the engine instantiates it's own copy of this type and
/// thus if someone were to extend it, they would not get the desired behavior from the engine.
/// </summary>
/// <comment>
/// Surprisingly few of these Utilities TaskItems are created: typically several orders of magnitude fewer than the number of engine TaskItems.
/// </comment>
public sealed class TaskItem :
#if FEATURE_APPDOMAIN
MarshalByRefObject,
#endif
ITaskItem2,
IMetadataContainer // expose direct underlying metadata for fast access in binary logger
{
#region Member Data
// This is the final evaluated item specification. Stored in escaped form.
private string _itemSpec;
// These are the user-defined metadata on the item, specified in the
// project file via XML child elements of the item element. These have
// no meaning to MSBuild, but tasks may use them.
// Values are stored in escaped form.
private CopyOnWriteDictionary<string> _metadata;
// cache of the fullpath value
private string _fullPath;
/// <summary>
/// May be defined if we're copying this item from a pre-existing one. Otherwise,
/// we simply don't know enough to set it properly, so it will stay null.
/// </summary>
private readonly string _definingProject;
#endregion
#region Constructors
/// <summary>
/// Default constructor -- we need it so this type is COM-createable.
/// </summary>
public TaskItem()
{
_itemSpec = string.Empty;
}
/// <summary>
/// This constructor creates a new task item, given the item spec.
/// </summary>
/// <comments>Assumes the itemspec passed in is escaped.</comments>
/// <param name="itemSpec">The item-spec string.</param>
public TaskItem
(
string itemSpec
)
{
ErrorUtilities.VerifyThrowArgumentNull(itemSpec, nameof(itemSpec));
_itemSpec = FileUtilities.FixFilePath(itemSpec);
}
/// <summary>
/// This constructor creates a new TaskItem, using the given item spec and metadata.
/// </summary>
/// <comments>
/// Assumes the itemspec passed in is escaped, and also that any escapable metadata values
/// are passed in escaped form.
/// </comments>
/// <param name="itemSpec">The item-spec string.</param>
/// <param name="itemMetadata">Custom metadata on the item.</param>
public TaskItem
(
string itemSpec,
IDictionary itemMetadata
) :
this(itemSpec)
{
ErrorUtilities.VerifyThrowArgumentNull(itemMetadata, nameof(itemMetadata));
if (itemMetadata.Count > 0)
{
_metadata = new CopyOnWriteDictionary<string>(MSBuildNameIgnoreCaseComparer.Default);
foreach (DictionaryEntry singleMetadata in itemMetadata)
{
// don't import metadata whose names clash with the names of reserved metadata
string key = (string)singleMetadata.Key;
if (!FileUtilities.ItemSpecModifiers.IsDerivableItemSpecModifier(key))
{
_metadata[key] = (string)singleMetadata.Value ?? string.Empty;
}
}
}
}
/// <summary>
/// This constructor creates a new TaskItem, using the given ITaskItem.
/// </summary>
/// <param name="sourceItem">The item to copy.</param>
public TaskItem
(
ITaskItem sourceItem
)
{
ErrorUtilities.VerifyThrowArgumentNull(sourceItem, nameof(sourceItem));
// Attempt to preserve escaped state
if (!(sourceItem is ITaskItem2 sourceItemAsITaskItem2))
{
_itemSpec = EscapingUtilities.Escape(sourceItem.ItemSpec);
_definingProject = EscapingUtilities.EscapeWithCaching(sourceItem.GetMetadata(FileUtilities.ItemSpecModifiers.DefiningProjectFullPath));
}
else
{
_itemSpec = sourceItemAsITaskItem2.EvaluatedIncludeEscaped;
_definingProject = sourceItemAsITaskItem2.GetMetadataValueEscaped(FileUtilities.ItemSpecModifiers.DefiningProjectFullPath);
}
sourceItem.CopyMetadataTo(this);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the item-spec.
/// </summary>
/// <comments>
/// This one is a bit tricky. Orcas assumed that the value being set was escaped, but
/// that the value being returned was unescaped. Maintain that behaviour here. To get
/// the escaped value, use ITaskItem2.EvaluatedIncludeEscaped.
/// </comments>
/// <value>The item-spec string.</value>
public string ItemSpec
{
get => _itemSpec == null ? string.Empty : EscapingUtilities.UnescapeAll(_itemSpec);
set
{
ErrorUtilities.VerifyThrowArgumentNull(value, nameof(ItemSpec));
_itemSpec = FileUtilities.FixFilePath(value);
_fullPath = null;
}
}
/// <summary>
/// Gets or sets the escaped include, or "name", for the item.
/// </summary>
/// <remarks>
/// Taking the opportunity to fix the property name, although this doesn't
/// make it obvious it's an improvement on ItemSpec.
/// </remarks>
string ITaskItem2.EvaluatedIncludeEscaped
{
// It's already escaped
get => _itemSpec;
set
{
_itemSpec = FileUtilities.FixFilePath(value);
_fullPath = null;
}
}
/// <summary>
/// Gets the names of all the item's metadata.
/// </summary>
/// <value>List of metadata names.</value>
public ICollection MetadataNames
{
get
{
var metadataNames = new List<string>(_metadata?.Keys ?? Array.Empty<string>());
metadataNames.AddRange(FileUtilities.ItemSpecModifiers.All);
return metadataNames;
}
}
/// <summary>
/// Gets the number of metadata set on the item.
/// </summary>
/// <value>Count of metadata.</value>
public int MetadataCount => (_metadata?.Count ?? 0) + FileUtilities.ItemSpecModifiers.All.Length;
/// <summary>
/// Gets the metadata dictionary
/// Property is required so that we can access the metadata dictionary in an item from
/// another appdomain, as the CLR has implemented remoting policies that disallow accessing
/// private fields in remoted items.
/// </summary>
private CopyOnWriteDictionary<string> Metadata
{
get
{
return _metadata;
}
set
{
_metadata = value;
}
}
#endregion
#region Methods
/// <summary>
/// Removes one of the arbitrary metadata on the item.
/// </summary>
/// <param name="metadataName">Name of metadata to remove.</param>
public void RemoveMetadata(string metadataName)
{
ErrorUtilities.VerifyThrowArgumentNull(metadataName, nameof(metadataName));
ErrorUtilities.VerifyThrowArgument(!FileUtilities.ItemSpecModifiers.IsItemSpecModifier(metadataName),
"Shared.CannotChangeItemSpecModifiers", metadataName);
_metadata?.Remove(metadataName);
}
/// <summary>
/// Sets one of the arbitrary metadata on the item.
/// </summary>
/// <comments>
/// Assumes that the value being passed in is in its escaped form.
/// </comments>
/// <param name="metadataName">Name of metadata to set or change.</param>
/// <param name="metadataValue">Value of metadata.</param>
public void SetMetadata
(
string metadataName,
string metadataValue
)
{
ErrorUtilities.VerifyThrowArgumentLength(metadataName, nameof(metadataName));
// Non-derivable metadata can only be set at construction time.
// That's why this is IsItemSpecModifier and not IsDerivableItemSpecModifier.
ErrorUtilities.VerifyThrowArgument(!FileUtilities.ItemSpecModifiers.IsDerivableItemSpecModifier(metadataName),
"Shared.CannotChangeItemSpecModifiers", metadataName);
_metadata ??= new CopyOnWriteDictionary<string>(MSBuildNameIgnoreCaseComparer.Default);
_metadata[metadataName] = metadataValue ?? string.Empty;
}
/// <summary>
/// Retrieves one of the arbitrary metadata on the item.
/// If not found, returns empty string.
/// </summary>
/// <comments>
/// Returns the unescaped value of the metadata requested.
/// </comments>
/// <param name="metadataName">The name of the metadata to retrieve.</param>
/// <returns>The metadata value.</returns>
public string GetMetadata(string metadataName)
{
string metadataValue = (this as ITaskItem2).GetMetadataValueEscaped(metadataName);
return EscapingUtilities.UnescapeAll(metadataValue);
}
/// <summary>
/// Copy the metadata (but not the ItemSpec) to destinationItem. If a particular metadata already exists on the
/// destination item, then it is not overwritten -- the original value wins.
/// </summary>
/// <param name="destinationItem">The item to copy metadata to.</param>
public void CopyMetadataTo(ITaskItem destinationItem)
{
ErrorUtilities.VerifyThrowArgumentNull(destinationItem, nameof(destinationItem));
// also copy the original item-spec under a "magic" metadata -- this is useful for tasks that forward metadata
// between items, and need to know the source item where the metadata came from
string originalItemSpec = destinationItem.GetMetadata("OriginalItemSpec");
ITaskItem2 destinationAsITaskItem2 = destinationItem as ITaskItem2;
if (_metadata != null)
{
if (destinationItem is TaskItem destinationAsTaskItem)
{
CopyOnWriteDictionary<string> copiedMetadata;
// Avoid a copy if we can, and if not, minimize the number of items we have to set.
if (destinationAsTaskItem.Metadata == null)
{
copiedMetadata = _metadata.Clone(); // Copy on write!
}
else if (destinationAsTaskItem.Metadata.Count < _metadata.Count)
{
copiedMetadata = _metadata.Clone(); // Copy on write!
copiedMetadata.SetItems(destinationAsTaskItem.Metadata.Where(entry => !String.IsNullOrEmpty(entry.Value)));
}
else
{
copiedMetadata = destinationAsTaskItem.Metadata.Clone();
copiedMetadata.SetItems(_metadata.Where(entry => !destinationAsTaskItem.Metadata.TryGetValue(entry.Key, out string val) || String.IsNullOrEmpty(val)));
}
destinationAsTaskItem.Metadata = copiedMetadata;
}
else
{
foreach (KeyValuePair<string, string> entry in _metadata)
{
string value;
if (destinationAsITaskItem2 != null)
{
value = destinationAsITaskItem2.GetMetadataValueEscaped(entry.Key);
if (string.IsNullOrEmpty(value))
{
destinationAsITaskItem2.SetMetadata(entry.Key, entry.Value);
}
}
else
{
value = destinationItem.GetMetadata(entry.Key);
if (string.IsNullOrEmpty(value))
{
destinationItem.SetMetadata(entry.Key, EscapingUtilities.Escape(entry.Value));
}
}
}
}
}
if (string.IsNullOrEmpty(originalItemSpec))
{
if (destinationAsITaskItem2 != null)
{
destinationAsITaskItem2.SetMetadata("OriginalItemSpec", ((ITaskItem2)this).EvaluatedIncludeEscaped);
}
else
{
destinationItem.SetMetadata("OriginalItemSpec", EscapingUtilities.Escape(ItemSpec));
}
}
}
/// <summary>
/// Get the collection of custom metadata. This does not include built-in metadata.
/// </summary>
/// <remarks>
/// RECOMMENDED GUIDELINES FOR METHOD IMPLEMENTATIONS:
/// 1) this method should return a clone of the metadata
/// 2) writing to this dictionary should not be reflected in the underlying item.
/// </remarks>
/// <comments>
/// Returns an UNESCAPED version of the custom metadata. For the escaped version (which
/// is how it is stored internally), call ITaskItem2.CloneCustomMetadataEscaped.
/// </comments>
public IDictionary CloneCustomMetadata()
{
var dictionary = new CopyOnWriteDictionary<string>(MSBuildNameIgnoreCaseComparer.Default);
if (_metadata != null)
{
foreach (KeyValuePair<string, string> entry in _metadata)
{
dictionary.Add(entry.Key, EscapingUtilities.UnescapeAll(entry.Value));
}
}
return dictionary;
}
/// <summary>
/// Gets the item-spec.
/// </summary>
/// <returns>The item-spec string.</returns>
public override string ToString() => _itemSpec;
#if FEATURE_APPDOMAIN
/// <summary>
/// Overridden to give this class infinite lease time. Otherwise we end up with a limited
/// lease (5 minutes I think) and instances can expire if they take long time processing.
/// </summary>
[SecurityCritical]
public override object InitializeLifetimeService() => null; // null means infinite lease time
#endif
#endregion
#region Operators
/// <summary>
/// This allows an explicit typecast from a "TaskItem" to a "string", returning the escaped ItemSpec for this item.
/// </summary>
/// <param name="taskItemToCast">The item to operate on.</param>
/// <returns>The item-spec of the item.</returns>
public static explicit operator string(TaskItem taskItemToCast)
{
ErrorUtilities.VerifyThrowArgumentNull(taskItemToCast, nameof(taskItemToCast));
return taskItemToCast.ItemSpec;
}
#endregion
#region ITaskItem2 implementation
/// <summary>
/// Returns the escaped value of the metadata with the specified key.
/// </summary>
string ITaskItem2.GetMetadataValueEscaped(string metadataName)
{
ErrorUtilities.VerifyThrowArgumentNull(metadataName, nameof(metadataName));
string metadataValue = null;
if (FileUtilities.ItemSpecModifiers.IsDerivableItemSpecModifier(metadataName))
{
// FileUtilities.GetItemSpecModifier is expecting escaped data, which we assume we already are.
// Passing in a null for currentDirectory indicates we are already in the correct current directory
metadataValue = FileUtilities.ItemSpecModifiers.GetItemSpecModifier(null, _itemSpec, _definingProject, metadataName, ref _fullPath);
}
else
{
_metadata?.TryGetValue(metadataName, out metadataValue);
}
return metadataValue ?? string.Empty;
}
/// <summary>
/// Sets the escaped value of the metadata with the specified name.
/// </summary>
/// <comments>
/// Assumes the value is passed in unescaped.
/// </comments>
void ITaskItem2.SetMetadataValueLiteral(string metadataName, string metadataValue) => SetMetadata(metadataName, EscapingUtilities.Escape(metadataValue));
/// <summary>
/// ITaskItem2 implementation which returns a clone of the metadata on this object.
/// Values returned are in their original escaped form.
/// </summary>
/// <returns>The cloned metadata.</returns>
IDictionary ITaskItem2.CloneCustomMetadataEscaped() => _metadata == null
? new CopyOnWriteDictionary<string>(MSBuildNameIgnoreCaseComparer.Default)
: _metadata.Clone();
#endregion
IEnumerable<KeyValuePair<string, string>> IMetadataContainer.EnumerateMetadata()
{
#if FEATURE_APPDOMAIN
// Can't send a yield-return iterator across AppDomain boundaries
// so have to allocate
if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
{
return EnumerateMetadataEager();
}
#endif
// In general case we want to return an iterator without allocating a collection
// to hold the result, so we can stream the items directly to the consumer.
return EnumerateMetadataLazy();
}
private IEnumerable<KeyValuePair<string, string>> EnumerateMetadataEager()
{
if (_metadata == null)
{
return Array.Empty<KeyValuePair<string, string>>();
}
int count = _metadata.Count;
int index = 0;
var result = new KeyValuePair<string, string>[count];
foreach (var kvp in _metadata)
{
var unescaped = new KeyValuePair<string, string>(kvp.Key, EscapingUtilities.UnescapeAll(kvp.Value));
result[index++] = unescaped;
}
return result;
}
private IEnumerable<KeyValuePair<string, string>> EnumerateMetadataLazy()
{
if (_metadata == null)
{
yield break;
}
foreach (var kvp in _metadata)
{
var unescaped = new KeyValuePair<string, string>(kvp.Key, EscapingUtilities.UnescapeAll(kvp.Value));
yield return unescaped;
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Services.Description;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Globalization;
using FxMessage = System.Web.Services.Description.Message;
using FxOperation = System.Web.Services.Description.Operation;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Binding = System.Web.Services.Description.Binding;
namespace Thinktecture.Tools.Web.Services.ServiceDescription
{
#region ServiceDescriptionEngine class
/// <summary>
/// Provides static methods for WSDL generation.
/// </summary>
/// <remarks>This class could not be inherited.</remarks>
public sealed class ServiceDescriptionEngine
{
#region Constructors
/// <summary>
/// Initializes a new instance of ServiceDescriptionEngine class.
/// </summary>
private ServiceDescriptionEngine()
{ }
#endregion
#region Public static methods.
/// <summary>
/// Generates the WSDL file for specified <see cref="InterfaceContract"/>.
/// </summary>
/// <param name="serviceInterfaceContract">
/// <see cref="InterfaceContract"/> to use for the WSDL generation.
/// </param>
/// <param name="wsdlSaveLocation">Location to save the generated WSDL file.</param>
/// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param>
/// <returns>The path of the WSDL file generated.</returns>
public static string GenerateWsdl(InterfaceContract serviceInterfaceContract,
string wsdlSaveLocation, string xmlComment)
{
return GenerateWsdl(serviceInterfaceContract, wsdlSaveLocation, xmlComment, null);
}
/// <summary>
/// Generates the WSDL file for a specified <see cref="InterfaceContract"/>.
/// </summary>
/// <param name="serviceInterfaceContract">
/// <see cref="InterfaceContract"/> to use for the WSDL generation.
/// </param>
/// <param name="wsdlSaveLocation">Location to save the generated WSDL file.</param>
/// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param>
/// <param name="wsdlLocation">Path of an existing WSDL file to overwrite with the generated
/// WSDL file.</param>
/// <returns>The path of the WSDL file generated.</returns>
/// <remarks>
/// This methods loads the information, it receive in a <see cref="InterfaceContract"/> to
/// a <see cref="System.Web.Services.Description.ServiceDescription"/> class, which is later
/// used to generate the WSDL file. The loading process takes place in several steps. <br></br>
/// 1. Load the basic meta data from <see cref="InterfaceContract"/>.<br></br>
/// 2. Load the schema imports in the <see cref="SchemaImports"/> collection.<br></br>
/// 3. Load the messages in <see cref="OperationsCollection"/>.<br></br>
/// 4. Create the WSDL Port Type.<br></br>
/// 5. Add each operation and it's corresponding in/out messages to the Port Type.<br></br>
/// 6. Create a WSDL Binding section and add OperationBinding for each operation.<br></br>
/// 7. Generate the WSDL 'service' tags if required.<br></br>
/// 8. Finally write the file to the output stream.<br></br>
///
/// This method generates <see cref="WsdlGenerationException"/> exception, if it fails to create the WSDL file.
/// If a file is specified to overwrite with the new file, the original file is restored in case of
/// a failure.
/// </remarks>
public static string GenerateWsdl(InterfaceContract serviceInterfaceContract,
string wsdlSaveLocation, string xmlComment, string wsdlLocation)
{
System.Web.Services.Description.ServiceDescription desc = null;
string serviceAttributeName = "";
string bindingName = "";
string serviceName = "";
string portTypeName = "";
// Load the existing WSDL if one specified.
if (wsdlLocation != null)
{
#region Round-tripping
desc = System.Web.Services.Description.ServiceDescription.Read(wsdlLocation);
// Read the existing name values.
serviceAttributeName = desc.Name;
bindingName = desc.Bindings[0].Name;
portTypeName = desc.PortTypes[0].Name;
// Check whether we have a service element and save it's name for the
// future use.
if (desc.Services.Count > 0)
{
serviceName = desc.Services[0].Name;
}
else
{
serviceName = serviceInterfaceContract.ServiceName + "Port"; ;
}
// Check for the place which has the Service name and assign the new value
// appropriatly.
if (serviceAttributeName != null && serviceAttributeName != "")
{
serviceAttributeName = serviceInterfaceContract.ServiceName;
}
else if (serviceName != null && serviceName != "")
{
// If the user has selected to remove the service element,
// use the service name in the attribute by default.
if (serviceInterfaceContract.NeedsServiceElement)
{
serviceName = serviceInterfaceContract.ServiceName;
}
else
{
serviceAttributeName = serviceInterfaceContract.ServiceName;
}
}
else if (bindingName != null && bindingName != "")
{
bindingName = serviceInterfaceContract.ServiceName;
}
// Clear the service description. But do not clear the types definitions.
desc.Extensions.Clear();
desc.Bindings.Clear();
desc.Documentation = "";
desc.Imports.Clear();
desc.Messages.Clear();
desc.PortTypes.Clear();
desc.RetrievalUrl = "";
if (desc.ServiceDescriptions != null)
{
desc.ServiceDescriptions.Clear();
}
if (!serviceInterfaceContract.NeedsServiceElement)
{
desc.Services.Clear();
}
#endregion
}
else
{
#region New WSDL
desc = new System.Web.Services.Description.ServiceDescription();
// Create the default names.
serviceAttributeName = serviceInterfaceContract.ServiceName;
bindingName = serviceInterfaceContract.ServiceName;
portTypeName = serviceInterfaceContract.ServiceName + "Interface";
serviceName = serviceInterfaceContract.ServiceName + "Port";
#endregion
}
#region Load the basic meta data.
if (serviceAttributeName != null && serviceAttributeName != "")
{
desc.Name = serviceAttributeName;
}
desc.TargetNamespace = serviceInterfaceContract.ServiceNamespace;
desc.Documentation = serviceInterfaceContract.ServiceDocumentation;
#endregion
#region Load the schema imports.
XmlSchema typesSchema = null;
// Are we round-tripping? Then we have to access the existing types
// section.
// Otherwise we just initialize a new XmlSchema for types.
if (wsdlLocation != null)
{
typesSchema = desc.Types.Schemas[desc.TargetNamespace];
// if we don't have a types section belonging to the same namespace as service description
// we take the first types section available.
if (typesSchema == null)
{
typesSchema = desc.Types.Schemas[0];
}
// Remove the includes. We gonna re-add them later in this operation.
typesSchema.Includes.Clear();
}
else
{
typesSchema = new XmlSchema();
}
// Add imports to the types section resolved above.
foreach (SchemaImport import in serviceInterfaceContract.Imports)
{
XmlSchemaExternal importedSchema = null;
if (import.SchemaNamespace == null || import.SchemaNamespace == "")
{
importedSchema = new XmlSchemaInclude();
}
else
{
importedSchema = new XmlSchemaImport();
((XmlSchemaImport)importedSchema).Namespace = import.SchemaNamespace;
}
if (serviceInterfaceContract.UseAlternateLocationForImports)
{
importedSchema.SchemaLocation = import.AlternateLocation;
}
else
{
importedSchema.SchemaLocation = import.SchemaLocation;
}
typesSchema.Includes.Add(importedSchema);
}
// If we are not round-tripping we have to link the types schema we just created to
// the service description.
if (wsdlLocation == null)
{
// Finally add the type schema to the ServiceDescription.Types.Schemas collection.
desc.Types.Schemas.Add(typesSchema);
}
#endregion
#region Load the messages in all the operations
MessageCollection msgs = desc.Messages;
foreach (Operation op in serviceInterfaceContract.OperationsCollection)
{
foreach (Message msg in op.MessagesCollection)
{
FxMessage tempMsg = new FxMessage();
tempMsg.Name = msg.Name;
tempMsg.Documentation = msg.Documentation;
MessagePart msgPart = new MessagePart();
msgPart.Name = Constants.DefaultMessagePartName;
msgPart.Element = new XmlQualifiedName(msg.Element.ElementName,
msg.Element.ElementNamespace);
tempMsg.Parts.Add(msgPart);
msgs.Add(tempMsg);
}
foreach (Message msg in op.Faults)
{
Message messageName = msg;
if (msgs.OfType<FxMessage>().Any(m => m.Name == messageName.Name)) continue;
FxMessage tempMsg = new FxMessage();
tempMsg.Name = msg.Name;
tempMsg.Documentation = msg.Documentation;
MessagePart msgPart = new MessagePart();
msgPart.Name = Constants.FaultMessagePartName;
msgPart.Element = new XmlQualifiedName(msg.Element.ElementName, msg.Element.ElementNamespace);
tempMsg.Parts.Add(msgPart);
msgs.Add(tempMsg);
}
}
#endregion
#region Create the Port Type
PortTypeCollection portTypes = desc.PortTypes;
PortType portType = new PortType();
portType.Name = portTypeName;
portType.Documentation = serviceInterfaceContract.ServiceDocumentation;
// Add each operation and it's corresponding in/out messages to the WSDL Port Type.
foreach (Operation op in serviceInterfaceContract.OperationsCollection)
{
FxOperation tempOperation = new FxOperation();
tempOperation.Name = op.Name;
tempOperation.Documentation = op.Documentation;
int i = 0;
OperationInput operationInput = new OperationInput();
operationInput.Message = new XmlQualifiedName(op.MessagesCollection[i].Name, desc.TargetNamespace);
tempOperation.Messages.Add(operationInput);
if (op.Mep == Mep.RequestResponse)
{
OperationOutput operationOutput = new OperationOutput();
operationOutput.Message = new XmlQualifiedName(op.MessagesCollection[i + 1].Name, desc.TargetNamespace);
tempOperation.Messages.Add(operationOutput);
}
foreach (Message fault in op.Faults)
{
OperationFault operationFault = new OperationFault();
operationFault.Name = fault.Name;
operationFault.Message = new XmlQualifiedName(fault.Name, desc.TargetNamespace);
tempOperation.Faults.Add(operationFault);
}
portType.Operations.Add(tempOperation);
i++;
}
portTypes.Add(portType);
#endregion
// Here we have a list of WCF endpoints.
// Currently we populate this list with only two endpoints that has default
// BasicHttpBinding and default NetTcpBinding.
List<ServiceEndpoint> endpoints = new List<ServiceEndpoint>();
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(basicHttpBinding));
// BDS (10/22/2007): Commented out the TCP binding generation as we are not going to support this feature
// in this version.
//NetTcpBinding netTcpBinding = new NetTcpBinding();
//endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(netTcpBinding));
// Now, for each endpoint we have to create a binding in our service description.
foreach (ServiceEndpoint endpoint in endpoints)
{
// Create a WSDL BindingCollection.
BindingCollection bindings = desc.Bindings;
System.Web.Services.Description.Binding binding = new System.Web.Services.Description.Binding();
binding.Name = endpoint.Name.Replace(Constants.InternalContractName, portTypeName);
binding.Type = new XmlQualifiedName(portType.Name, desc.TargetNamespace);
// Create Operation binding for each operation and add it the the BindingCollection.
foreach (Operation op in serviceInterfaceContract.OperationsCollection)
{
// SOAP 1.1 Operation bindings.
OperationBinding operationBinding1 = new OperationBinding();
operationBinding1.Name = op.Name;
InputBinding inputBinding1 = new InputBinding();
object bodyBindingExtension = GetSoapBodyBinding(endpoint.Binding);
if (bodyBindingExtension != null)
{
inputBinding1.Extensions.Add(bodyBindingExtension);
}
operationBinding1.Input = inputBinding1;
// Faults.
foreach (Message fault in op.Faults)
{
FaultBinding faultBinding = new FaultBinding();
faultBinding.Name = fault.Name;
SoapFaultBinding faultBindingExtension = GetFaultBodyBinding(endpoint.Binding);
if (faultBindingExtension != null)
{
faultBindingExtension.Name = fault.Name;
faultBinding.Extensions.Add(faultBindingExtension);
}
operationBinding1.Faults.Add(faultBinding);
}
// Input message.
// Look up the message headers for each Message and add them to the current binding.
foreach (MessageHeader inHeader in op.Input.HeadersCollection)
{
object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, inHeader.Message, desc.TargetNamespace);
if (headerBindingExtension != null)
{
inputBinding1.Extensions.Add(headerBindingExtension);
}
}
if (op.Mep == Mep.RequestResponse)
{
// Output message.
OutputBinding outputBinding1 = new OutputBinding();
object responseBodyBindingExtension = GetSoapBodyBinding(endpoint.Binding);
if (responseBodyBindingExtension != null)
{
outputBinding1.Extensions.Add(responseBodyBindingExtension);
}
operationBinding1.Output = outputBinding1;
// Look up the message headers for each Message and add them to the current binding.
foreach (MessageHeader outHeader in op.Output.HeadersCollection)
{
object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, outHeader.Message, desc.TargetNamespace);
if (headerBindingExtension != null)
{
outputBinding1.Extensions.Add(headerBindingExtension);
}
}
}
string action = desc.TargetNamespace + ":" + op.Input.Name;
object operationBindingExtension = GetSoapOperationBinding(endpoint.Binding, action);
if (operationBindingExtension != null)
{
operationBinding1.Extensions.Add(operationBindingExtension);
}
binding.Operations.Add(operationBinding1);
// End of SOAP 1.1 operation bindings.
}
object soapBindingExtension = GetSoapBinding(endpoint.Binding);
if (soapBindingExtension != null)
{
binding.Extensions.Add(soapBindingExtension);
}
bindings.Add(binding);
}
// Generate <service> element optionally - sometimes necessary for interop reasons
if (serviceInterfaceContract.NeedsServiceElement)
{
Service defaultService = null;
if (wsdlLocation == null || desc.Services.Count == 0)
{
// Create a new service element.
defaultService = new Service();
defaultService.Name = serviceName;
foreach (ServiceEndpoint endpoint in endpoints)
{
if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
{
Port defaultPort = new Port();
defaultPort.Name = serviceInterfaceContract.ServiceName + "Port";
defaultPort.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace);
SoapAddressBinding defaultSoapAddressBinding = new SoapAddressBinding();
defaultSoapAddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName);
defaultPort.Extensions.Add(defaultSoapAddressBinding);
defaultService.Ports.Add(defaultPort);
}
else if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
{
Port soap12Port = new Port();
soap12Port.Name = serviceInterfaceContract.ServiceName + "SOAP12Port";
soap12Port.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace);
Soap12AddressBinding soap12AddressBinding = new Soap12AddressBinding();
soap12AddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName);
soap12Port.Extensions.Add(soap12AddressBinding);
defaultService.Ports.Add(soap12Port);
}
}
desc.Services.Add(defaultService);
}
else
{
defaultService = desc.Services[0];
defaultService.Name = serviceName;
}
}
// Generate the WSDL file.
string fileName = string.Empty;
string bkFileName = string.Empty;
// Overwrite the existing file if one specified.
if (wsdlLocation == null)
{
fileName = wsdlSaveLocation + @"\" + serviceInterfaceContract.ServiceName + ".wsdl";
}
else
{
fileName = wsdlLocation;
}
// Backup existing file before proceeding.
if (File.Exists(fileName))
{
int index = 1;
// Create the backup file name.
// See whether the generated backup file name is already taken by an existing file and
// generate a new file name.
while (File.Exists(fileName + "." + index.ToString()))
{
index++;
}
bkFileName = fileName + "." + index.ToString();
// Backup the file.
try
{
File.Copy(fileName, bkFileName);
}
catch (Exception ex)
{
throw new WsdlGenerationException("An error occured while trying to generate a WSDL. Failed to backup the existing WSDL file.", ex);
}
}
StreamWriter writer1 = new StreamWriter(fileName);
try
{
XmlTextWriter writer11 = new XmlTextWriter(writer1);
writer11.Formatting = Formatting.Indented;
writer11.Indentation = 2;
writer11.WriteComment(xmlComment);
// BDS: Added a new comment line with the date time of WSDL file.
CultureInfo ci = new CultureInfo("en-US");
writer11.WriteComment(DateTime.Now.ToString("dddd", ci) + ", " + DateTime.Now.ToString("dd-MM-yyyy - hh:mm tt", ci));
XmlSerializer serializer1 = System.Web.Services.Description.ServiceDescription.Serializer;
XmlSerializerNamespaces nsSer = new XmlSerializerNamespaces();
nsSer.Add("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
nsSer.Add("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/");
nsSer.Add("xsd", "http://www.w3.org/2001/XMLSchema");
nsSer.Add("tns", desc.TargetNamespace);
// Add the imported namespaces to the WSDL <description> element.
for (int importIndex = 0; importIndex < serviceInterfaceContract.Imports.Count;
importIndex++)
{
if (serviceInterfaceContract.Imports[importIndex].SchemaNamespace != null &&
serviceInterfaceContract.Imports[importIndex].SchemaNamespace != "")
{
nsSer.Add("import" + importIndex.ToString(),
serviceInterfaceContract.Imports[importIndex].SchemaNamespace);
}
}
//
// Finally write the file to the output stram.
serializer1.Serialize(writer11, desc, nsSer);
// Close the stream and delete the backupfile.
writer1.Close();
if (bkFileName != string.Empty)
{
File.Delete(bkFileName);
}
WsdlWorkshop workshop = new WsdlWorkshop(endpoints, fileName, portTypeName);
workshop.BuildWsdl();
return fileName;
}
catch (Exception ex)
{
writer1.Close();
string message = ex.Message;
if (ex.InnerException != null)
{
message += ex.InnerException.Message;
}
// Restore the original file.
if (bkFileName != string.Empty)
{
try
{
File.Copy(bkFileName, fileName, true);
File.Delete(bkFileName);
}
catch
{
throw new WsdlGenerationException(
message + "\nFailed to restore the original file.");
}
}
else if (File.Exists(fileName))
{
File.Delete(fileName);
}
throw new WsdlGenerationException(
message, ex);
}
}
private static object GetSoapBinding(System.ServiceModel.Channels.Binding binding)
{
if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
{
SoapBinding soapBinding = new SoapBinding();
soapBinding.Transport = GetTransport(binding);
soapBinding.Style = SoapBindingStyle.Document;
return soapBinding;
}
else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
{
Soap12Binding soapBinding = new Soap12Binding();
soapBinding.Transport = GetTransport(binding);
soapBinding.Style = SoapBindingStyle.Document;
return soapBinding;
}
return null;
}
private static object GetSoapOperationBinding(System.ServiceModel.Channels.Binding binding, string action)
{
if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
{
SoapOperationBinding soapOperationBinding = new SoapOperationBinding();
soapOperationBinding.SoapAction = action;
soapOperationBinding.Style = SoapBindingStyle.Document;
return soapOperationBinding;
}
else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
{
Soap12OperationBinding soapOperationBinding = new Soap12OperationBinding();
soapOperationBinding.SoapAction = action;
soapOperationBinding.Style = SoapBindingStyle.Document;
return soapOperationBinding;
}
return null;
}
private static object GetSoapHeaderBinding(System.ServiceModel.Channels.Binding binding, string message, string ns)
{
if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
{
SoapHeaderBinding headerBinding = new SoapHeaderBinding();
headerBinding.Use = SoapBindingUse.Literal;
headerBinding.Message = new XmlQualifiedName(message, ns);
headerBinding.Part = Constants.DefaultMessagePartName;
return headerBinding;
}
else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
{
Soap12HeaderBinding headerBinding = new Soap12HeaderBinding();
headerBinding.Use = SoapBindingUse.Literal;
headerBinding.Message = new XmlQualifiedName(message, ns);
headerBinding.Part = Constants.DefaultMessagePartName;
return headerBinding;
}
return null;
}
private static object GetSoapBodyBinding(System.ServiceModel.Channels.Binding binding)
{
if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
{
SoapBodyBinding soapBinding = new SoapBodyBinding();
soapBinding.Use = SoapBindingUse.Literal;
return soapBinding;
}
else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
{
Soap12BodyBinding soap12Binding = new Soap12BodyBinding();
soap12Binding.Use = SoapBindingUse.Literal;
return soap12Binding;
}
return null;
}
private static SoapFaultBinding GetFaultBodyBinding(System.ServiceModel.Channels.Binding binding)
{
if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
{
return new SoapFaultBinding {Use = SoapBindingUse.Literal};
}
if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
{
return new Soap12FaultBinding {Use = SoapBindingUse.Literal};
}
return null;
}
private static string GetTransport(System.ServiceModel.Channels.Binding binding)
{
TransportBindingElement transport = binding.CreateBindingElements().Find<TransportBindingElement>();
if (transport != null)
{
if (typeof(HttpTransportBindingElement) == transport.GetType())
{
return "http://schemas.xmlsoap.org/soap/http";
}
if (typeof(HttpsTransportBindingElement) == transport.GetType())
{
return "http://schemas.xmlsoap.org/soap/https";
}
if (typeof(TcpTransportBindingElement) == transport.GetType())
{
return "http://schemas.microsoft.com/soap/tcp";
}
if (typeof(NamedPipeTransportBindingElement) == transport.GetType())
{
return "http://schemas.microsoft.com/soap/named-pipe";
}
if (typeof(MsmqTransportBindingElement) == transport.GetType())
{
return "http://schemas.microsoft.com/soap/msmq";
}
}
return "";
}
private static string GetDefaultEndpoint(System.ServiceModel.Channels.Binding binding, string serviceName)
{
TransportBindingElement transport = binding.CreateBindingElements().Find<TransportBindingElement>();
if (transport != null)
{
if (typeof(HttpTransportBindingElement) == transport.GetType())
{
UriBuilder ub = new UriBuilder(transport.Scheme, "localhost");
ub.Path = serviceName;
return ub.Uri.ToString();
}
if (typeof(HttpsTransportBindingElement) == transport.GetType())
{
UriBuilder ub = new UriBuilder(transport.Scheme, "localhost");
ub.Path = serviceName;
return ub.Uri.ToString();
}
if (typeof(TcpTransportBindingElement) == transport.GetType())
{
UriBuilder ub = new UriBuilder(transport.Scheme, "localhost");
ub.Path = serviceName;
return ub.Uri.ToString();
}
if (typeof(NamedPipeTransportBindingElement) == transport.GetType())
{
return "tbd";
}
if (typeof(MsmqTransportBindingElement) == transport.GetType())
{
return "tbd";
}
}
return "";
}
/// <summary>
/// Reads a XML schema file and returns the information found in that.
/// </summary>
/// <param name="schemaFile">The XML schema file to read information from.</param>
/// <param name="schemaNamespace">Ouput parameter which returns the namespace of the specified XML schema file.</param>
/// <returns>
/// An <see cref="ArrayList"/> with three items.
/// 1. Contains an <see cref="ArrayList"/> of <see cref="XmlSchemaElement"/> objects.
/// 2. Contains an <see cref="ArrayList"/> of schema element names.
/// 3. Contains a <see cref="SchemaElements"/> object.
/// </returns>
public static ArrayList GetSchemasFromXsd(string schemaFile, out string schemaNamespace)
{
XmlTextReader reader = null;
ArrayList schemas;
ArrayList schemaNames;
SchemaElements sElements;
try
{
reader = new XmlTextReader(schemaFile);
XmlSchema schema = XmlSchema.Read(reader, null);
string schemaTargetNamesapce = schema.TargetNamespace;
schemaNamespace = schemaTargetNamesapce;
ArrayList xmlSchemaElements = new ArrayList();
schemas = new ArrayList();
schemaNames = new ArrayList();
sElements = new SchemaElements();
foreach (XmlSchemaObject xmlObj in schema.Items)
{
if (xmlObj is XmlSchemaAnnotated) xmlSchemaElements.Add(xmlObj);
}
foreach (XmlSchemaAnnotated obj in xmlSchemaElements)
{
if (obj is XmlSchemaElement)
{
XmlSchemaElement xse = (XmlSchemaElement)obj;
schemas.Add(xse);
schemaNames.Add(xse.Name);
sElements.Add(new SchemaElement(schemaTargetNamesapce, xse.Name));
}
}
reader.Close();
ArrayList result = new ArrayList();
result.Add(schemas);
result.Add(sElements);
result.Add(schemaNames);
return result;
}
catch (Exception ex)
{
throw new InvalidOperationException("Error occurred while reading the schema file.", ex);
}
finally
{
if (reader != null && reader.ReadState != ReadState.Closed)
{
reader.Close();
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static ArrayList GetIntrinsicSimpleTypesNames()
{
ArrayList primitiveNames = new ArrayList();
Assembly ass = Assembly.GetAssembly(typeof(XmlSchema));
Type type = ass.GetType("System.Xml.Schema.DatatypeImplementation");
FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
foreach (FieldInfo fi in fields)
{
int index = fi.Name.IndexOf("c_");
if (index > -1)
{
string fieldName = fi.Name.Substring(index + 2);
primitiveNames.Add("xsd:" + fieldName);
}
}
return primitiveNames;
}
/// <summary>
/// Creates an <see cref="InterfaceContract"/> object by loading the contents in a specified
/// WSDL file.
/// </summary>
/// <param name="wsdlFileName">Path of the WSDL file to load the information from.</param>
/// <returns>An instance of <see cref="InterfaceContract"/> with the information loaded from the WSDL file.</returns>
/// <remarks>
/// This method first loads the content of the WSDL file to an instance of
/// <see cref="System.Web.Services.Description.ServiceDescription"/> class. Then it creates an
/// instance of <see cref="InterfaceContract"/> class by loading the data from that.
/// This method throws <see cref="WsdlLoadException"/> in case of a failure to load the WSDL file.
/// </remarks>
public static InterfaceContract GetInterfaceContract(string wsdlFileName)
{
// Try to load the service description from the specified file.
System.Web.Services.Description.ServiceDescription srvDesc = null;
try
{
srvDesc = System.Web.Services.Description.ServiceDescription.Read(
wsdlFileName);
}
catch (Exception ex)
{
throw new WsdlLoadException(
"Could not load service description from the specified file.",
ex);
}
// Validate the WSDL before proceeding.
bool isHttpBinding = false;
if (!ValidateWsdl(srvDesc, ref isHttpBinding))
{
throw new WsdlNotCompatibleForRoundTrippingException("Not a valid file for round tripping");
}
// Start building the simplified InterfaceContract object from the
// .Net Fx ServiceDescription we created.
InterfaceContract simpleContract = new InterfaceContract();
// Initialize the basic meta data.
simpleContract.ServiceNamespace = srvDesc.TargetNamespace;
simpleContract.ServiceDocumentation = srvDesc.Documentation;
// Try to get the service namespace from the service description.
simpleContract.ServiceName = srvDesc.Name;
// If it was not found in the service description. Then try to get it from the
// service. If it is not found their either, then try to get it from binding.
if (simpleContract.ServiceName == null || simpleContract.ServiceName == "")
{
if (srvDesc.Services.Count > 0 && srvDesc.Services[0].Name != null &&
srvDesc.Services[0].Name != "")
{
simpleContract.ServiceName = srvDesc.Services[0].Name;
}
else
{
simpleContract.ServiceName = srvDesc.Bindings[0].Name;
}
}
// Set the http binding property.
simpleContract.IsHttpBinding = isHttpBinding;
// Initialize the imports.
foreach (XmlSchema typeSchema in srvDesc.Types.Schemas)
{
foreach (XmlSchemaObject schemaObject in typeSchema.Includes)
{
XmlSchemaImport import = schemaObject as XmlSchemaImport;
if (import != null && import.SchemaLocation != null)
{
SchemaImport simpleImport = new SchemaImport();
simpleImport.SchemaNamespace = import.Namespace;
simpleImport.SchemaLocation = import.SchemaLocation;
simpleContract.Imports.Add(simpleImport);
}
}
}
// Initialize the types embedded to the WSDL.
simpleContract.SetTypes(GetSchemaElements(srvDesc.Types.Schemas, srvDesc.TargetNamespace));
// Initialize the operations and in/out messages.
PortType ptype = srvDesc.PortTypes[0];
if (ptype != null)
{
foreach (FxOperation op in ptype.Operations)
{
// Create the Operation.
Operation simpleOp = new Operation();
simpleOp.Name = op.Name;
simpleOp.Documentation = op.Documentation;
if (op.Faults != null)
{
foreach (OperationFault fault in op.Faults)
{
FxMessage faultMessage = srvDesc.Messages[fault.Message.Name];
if (faultMessage == null)
{
// WSDL modified.
string message = string.Format("Could not find the fault message '{0}'", fault.Message.Name);
throw new WsdlModifiedException(message);
}
MessagePart part = faultMessage.Parts[0];
if (part != null)
{
Message message = new Message();
message.Name = faultMessage.Name;
message.Element.ElementName = part.Element.Name;
message.Element.ElementNamespace = part.Element.Namespace;
message.Documentation = faultMessage.Documentation;
simpleOp.MessagesCollection.Add(message);
simpleOp.Faults.Add(message);
}
}
}
if (op.Messages.Input != null)
{
FxMessage inMessage = srvDesc.Messages[op.Messages.Input.Message.Name];
if (inMessage == null)
{
// WSDL modified.
throw new WsdlModifiedException("Could not find the message");
}
MessagePart part = inMessage.Parts[0];
if (part != null)
{
// Create the input message.
Message simpleInMessage = new Message();
simpleInMessage.Name = inMessage.Name;
simpleInMessage.Element.ElementName = part.Element.Name;
simpleInMessage.Element.ElementNamespace = part.Element.Namespace;
simpleInMessage.Documentation = inMessage.Documentation;
simpleOp.MessagesCollection.Add(simpleInMessage);
simpleOp.Input = simpleInMessage;
}
else
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the message part");
}
}
if (op.Messages.Output != null)
{
FxMessage outMessage = srvDesc.Messages[op.Messages.Output.Message.Name];
if (outMessage == null)
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the message");
}
MessagePart part = outMessage.Parts[0];
if (part != null)
{
// Create the output message.
Message simpleOutMessage = new Message();
simpleOutMessage.Name = outMessage.Name;
simpleOutMessage.Element.ElementName = part.Element.Name;
simpleOutMessage.Element.ElementNamespace = part.Element.Namespace;
simpleOutMessage.Documentation = outMessage.Documentation;
simpleOp.MessagesCollection.Add(simpleOutMessage);
simpleOp.Output = simpleOutMessage;
}
else
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the message part");
}
// Set the message direction.
simpleOp.Mep = Mep.RequestResponse;
}
else
{
simpleOp.Mep = Mep.OneWay;
}
// Finally add the Operation to Operations collection.
simpleContract.OperationsCollection.Add(simpleOp);
}
}
else
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the portType");
}
// Initialize the message headers and header messages.
System.Web.Services.Description.Binding binding1 = srvDesc.Bindings[0];
if (binding1 != null)
{
// Find the corresponding Operation in the InterfaceContract, for each OperationBinding
// in the binding1.Operations collection.
foreach (OperationBinding opBinding in binding1.Operations)
{
foreach (Operation simpleOp in simpleContract.OperationsCollection)
{
if (simpleOp.Name == opBinding.Name)
{
if (opBinding.Input != null)
{
// Enumerate the message headers for the input message.
foreach (ServiceDescriptionFormatExtension extension in opBinding.Input.Extensions)
{
SoapHeaderBinding inHeader = extension as SoapHeaderBinding;
if (inHeader != null)
{
// Create the in header and add it to the headers collection.
MessageHeader simpleInHeader = new MessageHeader();
FxMessage inHeaderMessage = srvDesc.Messages[inHeader.Message.Name];
if (inHeaderMessage == null)
{
// WSDL modified.
throw new WsdlModifiedException("Could not find the message");
}
simpleInHeader.Name = inHeaderMessage.Name;
simpleInHeader.Message = inHeaderMessage.Name;
simpleOp.Input.HeadersCollection.Add(simpleInHeader);
// Create the in header message and put it to the Operation's messeages collection.
MessagePart part = inHeaderMessage.Parts[0];
if (part != null)
{
Message simpleInHeaderMessage = new Message();
simpleInHeaderMessage.Name = inHeaderMessage.Name;
simpleInHeaderMessage.Element.ElementName = part.Element.Name;
simpleInHeaderMessage.Element.ElementNamespace = part.Element.Namespace;
simpleOp.MessagesCollection.Add(simpleInHeaderMessage);
}
else
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the message part");
}
}
}
}
else
{
// WSDL modified.
throw new WsdlModifiedException("Could not find the operation binding");
}
if (simpleOp.Mep == Mep.RequestResponse && opBinding.Output != null)
{
// Enumerate the message headers for the output message.
foreach (ServiceDescriptionFormatExtension extension in opBinding.Output.Extensions)
{
SoapHeaderBinding outHeader = extension as SoapHeaderBinding;
if (outHeader != null)
{
// Create the in header and add it to the headers collection.
MessageHeader simpleOutHeader = new MessageHeader();
FxMessage outHeaderMessage = srvDesc.Messages[outHeader.Message.Name];
if (outHeaderMessage == null)
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the message");
}
simpleOutHeader.Name = outHeaderMessage.Name;
simpleOutHeader.Message = outHeaderMessage.Name;
simpleOp.Output.HeadersCollection.Add(simpleOutHeader);
// Create the out header message and put it to the Operation's messeages collection.
MessagePart part = outHeaderMessage.Parts[0];
if (part != null)
{
Message simpleOutHeaderMessage = new Message();
simpleOutHeaderMessage.Name = outHeaderMessage.Name;
simpleOutHeaderMessage.Element.ElementName = part.Element.Name;
simpleOutHeaderMessage.Element.ElementNamespace = part.Element.Namespace;
simpleOp.MessagesCollection.Add(simpleOutHeaderMessage);
}
else
{
// WSDL is modified.
throw new WsdlModifiedException("Could not find the message part");
}
}
}
}
else if (simpleOp.Mep == Mep.RequestResponse)
{
// WSDL modified.
throw new WsdlModifiedException("Could not find the operation binding");
}
}
}
}
}
// Check for the "Generate service tags" option.
if (srvDesc.Services.Count == 1)
{
simpleContract.NeedsServiceElement = true;
}
// Turn on the SOAP 1.2 binding if available.
foreach (System.Web.Services.Description.Binding binding in srvDesc.Bindings)
{
if (binding.Extensions.Find(typeof(Soap12Binding)) != null)
{
simpleContract.Bindings |= InterfaceContract.SoapBindings.Soap12;
}
}
return simpleContract;
}
#endregion
#region Private static methods.
/// <summary>
/// Validates a specified instance of <see cref="ServiceDescription"/> class for the round tripping feature.
/// </summary>
/// <param name="serviceDescription">
/// An instance of <see cref="ServiceDescription"/> class to
/// validate.
/// </param>
/// <param name="isHttpBinding">A reference to a Boolean variable. Value is this variable is set to true if the service description has Http binding.</param>
/// <returns>
/// A value indicating whether the specified instance of <see cref="ServiceDescription"/>
/// class is valid for the round tripping feature.
/// </returns>
private static bool ValidateWsdl(
System.Web.Services.Description.ServiceDescription serviceDescription,
ref bool isHttpBinding)
{
// Rule No 1: Service description must have atleast one schema in the types definitions.
if (serviceDescription.Types.Schemas.Count == 0)
{
return false;
}
// Rule No 2: Service description must have only one <porttype>.
if (serviceDescription.PortTypes.Count != 1)
{
return false;
}
// Rule No 3: Service description must have only SOAP 1.1 and/or SOAP 1.2 binding(s).
if (!((serviceDescription.Bindings.Count == 1 && serviceDescription.Bindings[0].Extensions.Find(typeof(SoapBinding)) != null) ||
(serviceDescription.Bindings.Count == 2 && serviceDescription.Bindings[0].Extensions.Find(typeof(SoapBinding)) != null &&
serviceDescription.Bindings[1].Extensions.Find(typeof(Soap12Binding)) != null)))
{
return false;
}
// Rule No 4: Service description can not have more than one <service>. But it is possible
// not to have a <service>.
if (serviceDescription.Services.Count > 1)
{
return false;
}
// Rule No 5: Each message must have only one <part>.
foreach (FxMessage message in serviceDescription.Messages)
{
if (message.Parts.Count > 1)
{
return false;
}
}
// Rule No 6: For soap bindings the binding style must be 'Document' and encoding must be 'Literal'.
// Obtain a reference to the one and only binding we have.
System.Web.Services.Description.Binding binding = serviceDescription.Bindings[0];
// Search for the soap binding style and return false if it is not 'Document'
foreach (ServiceDescriptionFormatExtension extension in binding.Extensions)
{
SoapBinding soapBinding = extension as SoapBinding;
if (soapBinding != null)
{
if (soapBinding.Style != SoapBindingStyle.Document)
{
return false;
}
}
else if (extension is HttpBinding)
{
isHttpBinding = true;
}
}
// Validate the operation bindings.
foreach (OperationBinding operationBinding in binding.Operations)
{
// Validate the soap binding style in soap operation binding extension.
foreach (ServiceDescriptionFormatExtension extension in operationBinding.Extensions)
{
SoapOperationBinding soapOperationBinding = extension as SoapOperationBinding;
if (soapOperationBinding != null)
{
if (soapOperationBinding.Style != SoapBindingStyle.Document)
{
return false;
}
}
}
// Validate the 'use' element in input message body and the headers.
foreach (ServiceDescriptionFormatExtension extension in operationBinding.Input.Extensions)
{
// Check for a header.
SoapHeaderBinding headerBinding = extension as SoapHeaderBinding;
if (headerBinding != null)
{
if (headerBinding.Use != SoapBindingUse.Literal)
{
return false;
}
continue;
}
// Check for the body.
SoapBodyBinding bodyBinding = extension as SoapBodyBinding;
if (bodyBinding != null)
{
if (bodyBinding.Use != SoapBindingUse.Literal)
{
return false;
}
continue;
}
}
// Validate the 'use' element in output message body and the headers.
if (operationBinding.Output != null)
{
foreach (ServiceDescriptionFormatExtension extension in operationBinding.Output.Extensions)
{
// Check for the header.
SoapHeaderBinding headerBinding = extension as SoapHeaderBinding;
if (headerBinding != null)
{
if (headerBinding.Use != SoapBindingUse.Literal)
{
return false;
}
continue;
}
// Check for the body.
SoapBodyBinding bodyBinding = extension as SoapBodyBinding;
if (bodyBinding != null)
{
if (bodyBinding.Use != SoapBindingUse.Literal)
{
return false;
}
continue;
}
}
}
}
return true;
}
/// <summary>
/// Extracts the elements from a given schemas.
/// </summary>
/// <param name="schemas">Schemas to extract the elements from.</param>
/// <param name="tns">String specifying the target namespace of the <see cref="schemas" />.</param>
/// <returns>An instance of <see cref="SchemaElements" /> class which contains the extracted elements.</returns>
private static SchemaElements GetSchemaElements(XmlSchemas schemas, string tns)
{
ArrayList xmlSchemaElements = new ArrayList();
SchemaElements sElements = new SchemaElements();
foreach (XmlSchema schema in schemas)
{
foreach (XmlSchemaObject xmlObj in schema.Items)
{
if (xmlObj is XmlSchemaAnnotated)
{
if (xmlObj is XmlSchemaElement)
{
XmlSchemaElement xse = (XmlSchemaElement)xmlObj;
sElements.Add(new SchemaElement(tns, xse.Name));
}
}
}
}
return sElements;
}
#endregion
}
#endregion
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
namespace Controls
{
/// <summary>
/// Summary description for NumberEdit.
/// </summary>
public class NumberEdit : System.Windows.Forms.UserControl
{
public event EventHandler ValueChanged;
private const int upDownColumnWidth = 10;
private int intValue = 0;
private int maxValue = 100;
private int minValue = 0;
private bool antiAlias = true;
private int columnWidth = 0;
private int selectedColumn = -1;
private Color selectedColumnColor = Color.LightSteelBlue;
private bool upButton = false;
private bool downButton = false;
private StringFormat stringFormat;
private System.Windows.Forms.Panel pnlButtons;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public NumberEdit()
{
this.SetStyle(ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.Selectable, true);
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
CalculateColumnWidth();
}
public Color SelectionColor
{
get
{
return selectedColumnColor;
}
set
{
selectedColumnColor = value;
Redraw();
}
}
public int MaxValue
{
get
{
return maxValue;
}
set
{
maxValue = value;
}
}
public int MinValue
{
get
{
return minValue;
}
set
{
minValue = value;
}
}
public int Value
{
get
{
return intValue;
}
set
{
if(value > maxValue)
intValue = maxValue;
else if(value < minValue)
intValue = minValue;
else
intValue = value;
Redraw();
}
}
private void SetValue(int newValue)
{
this.Value = newValue;
if(ValueChanged != null)
ValueChanged(this, new EventArgs());
}
public bool AntiAliasText
{
get
{
return antiAlias;
}
set
{
antiAlias = value;
Redraw();
}
}
private void Redraw()
{
this.Invalidate();
}
private void CalculateColumnWidth()
{
using(Graphics g = this.CreateGraphics())
{
columnWidth = (int)g.MeasureString("0", this.Font).Width;
}
}
protected override void OnPaint(PaintEventArgs e)
{
string valueString = intValue.ToString();
if(antiAlias)
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
if(selectedColumn >= 0 && this.Focused)
{
using(SolidBrush selectionBrush = new SolidBrush(selectedColumnColor))
{
Rectangle selectRect = new Rectangle(selectedColumn * columnWidth, 0, columnWidth, this.Height);
e.Graphics.FillRectangle(selectionBrush, selectRect);
}
}
using(SolidBrush stringBrush = new SolidBrush(this.ForeColor))
{
for(int index = 0; index < valueString.Length; index++)
{
Rectangle stringRect = new Rectangle(index * columnWidth, 0, columnWidth, this.Height);
e.Graphics.DrawString(valueString[index].ToString(), this.Font, stringBrush, stringRect, stringFormat);
}
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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.pnlButtons = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// pnlButtons
//
this.pnlButtons.Dock = System.Windows.Forms.DockStyle.Right;
this.pnlButtons.Location = new System.Drawing.Point(264, 0);
this.pnlButtons.Name = "pnlButtons";
this.pnlButtons.Size = new System.Drawing.Size(16, 16);
this.pnlButtons.TabIndex = 0;
this.pnlButtons.Resize += new System.EventHandler(this.pnlButtons_Resize);
this.pnlButtons.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlButtons_MouseUp);
this.pnlButtons.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlButtons_Paint);
this.pnlButtons.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlButtons_MouseDown);
//
// NumberEdit
//
this.Controls.Add(this.pnlButtons);
this.Name = "NumberEdit";
this.Size = new System.Drawing.Size(280, 16);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.NumberEdit_KeyPress);
this.Enter += new System.EventHandler(this.NumberEdit_Enter);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.NumberEdit_KeyDown);
this.Leave += new System.EventHandler(this.NumberEdit_Leave);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.NumberEdit_MouseDown);
this.ResumeLayout(false);
}
#endregion
private void NumberEdit_Enter(object sender, System.EventArgs e)
{
Redraw();
}
private void NumberEdit_Leave(object sender, System.EventArgs e)
{
Redraw();
}
private void SetStringValue(string strValue)
{
try
{
if(strValue.Length == 0)
SetValue(0);
else
SetValue(Convert.ToInt32(strValue));
}
catch
{
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(keyData == Keys.Left)
{
if(selectedColumn > 0)
selectedColumn--;
Redraw();
return true;
}
else if(keyData == Keys.Right)
{
if(selectedColumn < intValue.ToString().Length)
selectedColumn++;
Redraw();
return true;
}
else if(keyData == Keys.Up || keyData == Keys.Down)
{
string numberString = intValue.ToString();
if(selectedColumn >= 0)
{
char columnChar = '0';
if(selectedColumn < numberString.Length)
columnChar = numberString[selectedColumn];
else
{
numberString += "0";
}
if(Char.IsNumber(columnChar))
{
int newValue = Convert.ToInt32(columnChar.ToString());
if(keyData == Keys.Up)
newValue++;
else
newValue--;
if(newValue > 9)
newValue = 0;
else if(newValue < 0)
newValue = 9;
numberString = numberString.Remove(selectedColumn, 1);
numberString = numberString.Insert(selectedColumn, newValue.ToString());
SetStringValue(numberString);
}
}
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
private void NumberEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(Char.IsNumber(e.KeyChar) || e.KeyChar == '-')
{
string numberString = intValue.ToString();
if(selectedColumn >= 0)
{
if(selectedColumn > numberString.Length - 1)
numberString += e.KeyChar;
else
{
numberString = numberString.Remove(selectedColumn, 1);
numberString = numberString.Insert(selectedColumn, e.KeyChar.ToString());
}
}
SetStringValue(numberString);
if(numberString[0] != '0' && selectedColumn + 1 <= intValue.ToString().Length)
selectedColumn++;
}
// Backspace key
else if(e.KeyChar == 8)
{
if(selectedColumn >= 1)
{
string numberString = intValue.ToString();
if(selectedColumn == 0)
numberString = numberString.Remove(0, 1);
else
numberString = numberString.Remove(selectedColumn - 1, 1);
SetStringValue(numberString);
selectedColumn--;
Redraw();
}
}
}
protected override void OnFontChanged(EventArgs e)
{
CalculateColumnWidth();
base.OnFontChanged (e);
}
private void NumberEdit_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Find the right column
int column = e.X / columnWidth;
string numberString = intValue.ToString();
if(column > numberString.Length - 1)
column = numberString.Length;
selectedColumn = column;
Redraw();
}
private void NumberEdit_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.Delete)
{
string numberString = intValue.ToString();
if(selectedColumn >= 0 && selectedColumn < numberString.Length)
{
numberString = numberString.Remove(selectedColumn, 1);
SetStringValue(numberString);
}
}
}
private void pnlButtons_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.Clear(this.BackColor);
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
if(upButton)
ControlPaint.DrawScrollButton(e.Graphics, 0, 0, pnlButtons.Width, pnlButtons.Height / 2, ScrollButton.Up, ButtonState.Pushed);
else
ControlPaint.DrawScrollButton(e.Graphics, 0, 0, pnlButtons.Width, pnlButtons.Height / 2, ScrollButton.Up, ButtonState.Normal);
if(downButton)
ControlPaint.DrawScrollButton(e.Graphics, 0, pnlButtons.Height / 2, pnlButtons.Width, pnlButtons.Height / 2, ScrollButton.Down, ButtonState.Pushed);
else
ControlPaint.DrawScrollButton(e.Graphics, 0, pnlButtons.Height / 2, pnlButtons.Width, pnlButtons.Height / 2, ScrollButton.Down, ButtonState.Normal);
}
private void pnlButtons_Resize(object sender, System.EventArgs e)
{
pnlButtons.Invalidate();
}
private void pnlButtons_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
selectedColumn = -1;
if(e.Y <= this.Height / 2)
{
upButton = true;
SetValue(this.Value + 1);
}
else
{
downButton = true;
SetValue(this.Value - 1);
}
pnlButtons.Invalidate();
}
private void pnlButtons_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
upButton = false;
downButton = false;
pnlButtons.Invalidate();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.HttpSys.Listener
{
public class RequestBodyTests
{
[ConditionalFact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/27399")]
public async Task RequestBody_SyncReadDisabledByDefault_WorksWhenEnabled()
{
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
Task<string> responseTask = SendRequestAsync(address, "Hello World");
Assert.False(server.Options.AllowSynchronousIO);
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[100];
Assert.Throws<InvalidOperationException>(() => context.Request.Body.Read(input, 0, input.Length));
context.AllowSynchronousIO = true;
Assert.True(context.AllowSynchronousIO);
var read = context.Request.Body.Read(input, 0, input.Length);
context.Response.ContentLength = read;
context.Response.Body.Write(input, 0, read);
string response = await responseTask;
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsyncAlreadyCanceled_ReturnsCanceledTask()
{
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
Task<string> responseTask = SendRequestAsync(address, "Hello World");
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[10];
var cts = new CancellationTokenSource();
cts.Cancel();
Task<int> task = context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.True(task.IsCanceled);
context.Dispose();
string response = await responseTask;
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsyncPartialBodyWithCancellationToken_Success()
{
StaggardContent content = new StaggardContent();
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
Task<string> responseTask = SendRequestAsync(address, content);
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[10];
var cts = new CancellationTokenSource();
int read = await context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.Equal(5, read);
content.Block.Release();
read = await context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.Equal(5, read);
context.Dispose();
string response = await responseTask;
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsyncPartialBodyWithTimeout_Success()
{
StaggardContent content = new StaggardContent();
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
Task<string> responseTask = SendRequestAsync(address, content);
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[10];
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(5));
int read = await context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.Equal(5, read);
content.Block.Release();
read = await context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.Equal(5, read);
context.Dispose();
string response = await responseTask;
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsyncPartialBodyAndCancel_Canceled()
{
StaggardContent content = new StaggardContent();
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
Task<string> responseTask = SendRequestAsync(address, content);
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[10];
var cts = new CancellationTokenSource();
int read = await context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.Equal(5, read);
var readTask = context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.False(readTask.IsCanceled);
cts.Cancel();
await Assert.ThrowsAsync<IOException>(async () => await readTask);
content.Block.Release();
context.Dispose();
await Assert.ThrowsAsync<HttpRequestException>(async () => await responseTask);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsyncPartialBodyAndExpiredTimeout_Canceled()
{
StaggardContent content = new StaggardContent();
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
Task<string> responseTask = SendRequestAsync(address, content);
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[10];
var cts = new CancellationTokenSource();
int read = await context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.Equal(5, read);
cts.CancelAfter(TimeSpan.FromMilliseconds(100));
var readTask = context.Request.Body.ReadAsync(input, 0, input.Length, cts.Token);
Assert.False(readTask.IsCanceled);
await Assert.ThrowsAsync<IOException>(async () => await readTask);
content.Block.Release();
context.Dispose();
await Assert.ThrowsAsync<HttpRequestException>(async () => await responseTask);
}
}
// Make sure that using our own disconnect token as a read cancellation token doesn't
// cause recursion problems when it fires and calls Abort.
[ConditionalFact]
public async Task RequestBody_ReadAsyncPartialBodyAndDisconnectedClient_Canceled()
{
StaggardContent content = new StaggardContent();
string address;
using (var server = Utilities.CreateHttpServer(out address))
{
var client = new HttpClient();
var responseTask = client.PostAsync(address, content);
var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask);
byte[] input = new byte[10];
int read = await context.Request.Body.ReadAsync(input, 0, input.Length, context.DisconnectToken);
Assert.False(context.DisconnectToken.IsCancellationRequested);
// The client should timeout and disconnect, making this read fail.
var assertTask = Assert.ThrowsAsync<IOException>(async () => await context.Request.Body.ReadAsync(input, 0, input.Length, context.DisconnectToken));
client.CancelPendingRequests();
await assertTask;
content.Block.Release();
context.Dispose();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await responseTask);
}
}
private Task<string> SendRequestAsync(string uri, string upload)
{
return SendRequestAsync(uri, new StringContent(upload));
}
private async Task<string> SendRequestAsync(string uri, HttpContent content)
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(10);
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
private class StaggardContent : HttpContent
{
public StaggardContent()
{
Block = new SemaphoreSlim(0, 1);
}
public SemaphoreSlim Block { get; private set; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await stream.WriteAsync(new byte[5], 0, 5);
await stream.FlushAsync();
await Block.WaitAsync();
await stream.WriteAsync(new byte[5], 0, 5);
}
protected override bool TryComputeLength(out long length)
{
length = 10;
return true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Routable
{
public abstract class RoutableOptions<TContext, TRequest, TResponse>
where TContext : RoutableContext<TContext, TRequest, TResponse>
where TRequest : RoutableRequest<TContext, TRequest, TResponse>
where TResponse : RoutableResponse<TContext, TRequest, TResponse>
{
/// <summary>
/// String encoding to use around the routable framework. (default is UTF-8)
/// </summary>
public virtual Encoding StringEncoding { get; set; } = Encoding.UTF8;
private IDictionary<string, string> MimeTypes = new Dictionary<string, string>();
/// <summary>
/// Handlers for responses of various types.
/// </summary>
public virtual ResponseTypeHandlerCollection<TContext, TRequest, TResponse> ResponseTypeHandlers { get; } = new ResponseTypeHandlerCollection<TContext, TRequest, TResponse>();
/// <summary>
/// Handles empty responses.
/// </summary>
public virtual ResponseTypeHandler<TContext, TRequest, TResponse> EmptyResponseHandler { get; } = DefaultResponseTypeHandlers.EmptyResponseTypeHandler;
/// <summary>
/// Handles any response type not handled by a configured response type handler.
/// </summary>
public virtual ResponseTypeHandler<TContext, TRequest, TResponse> DefaultResponseHandler { get; } = DefaultResponseTypeHandlers.StringResponseTypeHandler;
private Dictionary<RoutableEventPipelines, IList<Routing<TContext, TRequest, TResponse>>> Routing = new Dictionary<RoutableEventPipelines, IList<Routing<TContext, TRequest, TResponse>>>();
/// <summary>
/// Factory used to create routes when routes are authored.
/// </summary>
public virtual RouteFactory<TContext, TRequest, TResponse> RouteFactory { get; set; } = new RouteFactory<TContext, TRequest, TResponse>();
private Dictionary<Type, object> FeatureOptions = new Dictionary<Type, object>();
public IRoutableLogger Logger { get; protected set; } = new DefaultConsoleLogger();
protected RoutableOptions()
{
AddDefaultMimeTypes();
AddDefaultResponseTypeHandlers();
}
private async Task<bool> InvokeRouting(RoutableEventPipelines eventPipeline, TContext context, bool ignoreCompletion)
{
// obtain list of routing objects.
IList<Routing<TContext, TRequest, TResponse>> routing;
lock(Routing) {
if(Routing.TryGetValue(eventPipeline, out routing) == false) {
return false;
}
}
// obtain a snapshot of the routes.
var routeCollections = new List<List<Route<TContext, TRequest, TResponse>>>();
lock(routing) {
foreach(var r in routing) {
routeCollections.Add(r.Routes.Where(_ => _.IsMatch(context)).ToList());
}
}
// invoke each route until one succeeds (unless ignoreCompletion).
bool wasCompletedSuccessfully = false;
foreach(var routeCollection in routeCollections) {
foreach(var route in routeCollection) {
if(await route.Invoke(context) == true) {
if(ignoreCompletion == true) {
wasCompletedSuccessfully = true;
break;
} else {
return true;
}
}
}
}
return wasCompletedSuccessfully;
}
protected async Task<bool> InvokeRouting(TContext context)
{
try {
bool wasRequestHandled = false;
do {
// invoke initialize routes.
if(await InvokeRouting(RoutableEventPipelines.RouteEventInitialize, context, false) == true) {
wasRequestHandled = true;
break;
}
// invoke main routes.
if(await InvokeRouting(RoutableEventPipelines.RouteEventMain, context, false) == true) {
wasRequestHandled = true;
break;
}
} while(false);
if(wasRequestHandled == true) {
// invoke finalize routes.
await InvokeRouting(RoutableEventPipelines.RouteEventFinalize, context, true);
await context.Response.Finalize();
return true;
} else {
// invoke unhandled route finalizer.
if(await InvokeRouting(RoutableEventPipelines.RouteEventFinalizeUnhandledRequests, context, false) == true) {
// in that case, invoke finalize routes.
await InvokeRouting(RoutableEventPipelines.RouteEventFinalize, context, true);
await context.Response.Finalize();
return true;
}
}
} catch(Exception ex) {
// invoke error handling routes.
context.Error = ex;
context.Response.ClearPendingWrites();
if(await InvokeRouting(RoutableEventPipelines.RouteEventError, context, true) == true) {
await context.Response.Finalize();
return true;
}
}
return false;
}
private IList<Routing<TContext, TRequest, TResponse>> GetEventPipelineRouting(RoutableEventPipelines eventPipeline)
{
lock(Routing) {
if(Routing.TryGetValue(eventPipeline, out var list) == false) {
list = new List<Routing<TContext, TRequest, TResponse>>();
Routing.Add(eventPipeline, list);
return list;
} else {
return list;
}
}
}
/// <summary>
/// Add a routing instance to handle requests.
/// </summary>
public RoutableOptions<TContext, TRequest, TResponse> AddRouting(Routing<TContext, TRequest, TResponse> routing)
{
var list = GetEventPipelineRouting(RoutableEventPipelines.RouteEventMain);
lock(list) {
list.Add(routing);
}
return this;
}
/// <summary>
/// Synonym for AppendRoutingToEventPipeline.
/// </summary>
public RoutableOptions<TContext, TRequest, TResponse> AddRouting(RoutableEventPipelines eventPipeline, Routing<TContext, TRequest, TResponse> routing) => AppendRoutingToEventPipeline(eventPipeline, routing);
/// <summary>
/// Append a routing instance to handle requests to the specified pipeline.
/// </summary>
/// <seealso cref="RoutableEventPipelines"/>
public RoutableOptions<TContext, TRequest, TResponse> AppendRoutingToEventPipeline(RoutableEventPipelines eventPipeline, Routing<TContext, TRequest, TResponse> routing)
{
var list = GetEventPipelineRouting(eventPipeline);
lock(list) {
list.Add(routing);
}
return this;
}
/// <summary>
/// Prepend a routing instance to handle requests to the specified pipeline.
/// </summary>
/// <seealso cref="RoutableEventPipelines"/>
public RoutableOptions<TContext, TRequest, TResponse> PrependRoutingToEventPipeline(RoutableEventPipelines eventPipeline, Routing<TContext, TRequest, TResponse> routing)
{
var list = GetEventPipelineRouting(eventPipeline);
lock(list) {
list.Insert(0, routing);
}
return this;
}
/// <summary>
/// Set handler for unhandled errors.
/// </summary>
public RoutableOptions<TContext, TRequest, TResponse> OnError(Routing<TContext, TRequest, TResponse> routing)
{
AppendRoutingToEventPipeline(RoutableEventPipelines.RouteEventError, routing);
return this;
}
/// <summary>
/// Set a different logger than the default.
/// </summary>
public RoutableOptions<TContext, TRequest, TResponse> UseLogger(IRoutableLogger logger)
{
Logger = logger;
return this;
}
/// <summary>
/// Get detailed options of an arbitrary type to make available to routable requests and components.
/// </summary>
/// <typeparam name="TFeatureOptions">A plain old class</typeparam>
/// <param name="details">A plain old class representing configuration items</param>
/// <returns>Indicates whether or not the details exist</returns>
public bool TryGetFeatureOptions<TFeatureOptions>(out TFeatureOptions details)
where TFeatureOptions : class
{
if(FeatureOptions.TryGetValue(typeof(TFeatureOptions), out var value) == false) {
details = null;
return false;
} else {
details = value as TFeatureOptions;
return true;
}
}
/// <summary>
/// Set detailed options of an arbitrary type to make available to routable requests and components.
/// </summary>
/// <typeparam name="TFeatureOptions">A plain old class</typeparam>
/// <param name="details">A plain old class representing configuration items</param>
public void SetFeatureOptions<TFeatureOptions>(TFeatureOptions details) => FeatureOptions[typeof(TFeatureOptions)] = details;
/// <summary>
/// Add mime type for a given file extension.
/// </summary>
/// <param name="extension">File extension (should start with a period, otherwise one will be added)</param>
/// <param name="mimeType">MIME type (eg. text/html)</param>
public void AddMimeType(string extension, string mimeType) => MimeTypes[extension?.StartsWith(".") == true ? extension : $".{extension}"] = mimeType;
/// <summary>
/// Try to get a mime type for a file.
/// </summary>
/// <param name="extension">File extension for the inquery</param>
/// <param name="mimeType">Variable to write the mime type to if it is found</param>
/// <returns>True or false, indicating if the mime type was found</returns>
public bool TryGetMimeType(string extension, out string mimeType) => MimeTypes.TryGetValue(extension, out mimeType);
/// <summary>
/// Remove mime type for a given file extension.
/// </summary>
/// <param name="extension">File extension to remove mime type for</param>
public void RemoveMimeType(string extension) => MimeTypes.Remove(extension);
/// <summary>
/// Remove all mime types.
/// </summary>
public void ClearMimeTypes() => MimeTypes.Clear();
private void AddDefaultResponseTypeHandlers()
{
ResponseTypeHandlers.Add(typeof(object), DefaultResponseTypeHandlers.StringResponseTypeHandler);
ResponseTypeHandlers.Add(typeof(string), DefaultResponseTypeHandlers.StringResponseTypeHandler);
ResponseTypeHandlers.Add(typeof(byte[]), DefaultResponseTypeHandlers.ByteArrayResponseTypeHandler);
}
private void AddDefaultMimeTypes()
{
AddMimeType(".323", "text/h323");
AddMimeType(".aaf", "application/octet-stream");
AddMimeType(".aca", "application/octet-stream");
AddMimeType(".accdb", "application/msaccess");
AddMimeType(".accde", "application/msaccess");
AddMimeType(".accdt", "application/msaccess");
AddMimeType(".acx", "application/internet-property-stream");
AddMimeType(".afm", "application/octet-stream");
AddMimeType(".ai", "application/postscript");
AddMimeType(".aif", "audio/x-aiff");
AddMimeType(".aifc", "audio/aiff");
AddMimeType(".aiff", "audio/aiff");
AddMimeType(".application", "application/x-ms-application");
AddMimeType(".art", "image/x-jg");
AddMimeType(".asd", "application/octet-stream");
AddMimeType(".asf", "video/x-ms-asf");
AddMimeType(".asi", "application/octet-stream");
AddMimeType(".asm", "text/plain");
AddMimeType(".asr", "video/x-ms-asf");
AddMimeType(".asx", "video/x-ms-asf");
AddMimeType(".atom", "application/atom+xml");
AddMimeType(".au", "audio/basic");
AddMimeType(".avi", "video/x-msvideo");
AddMimeType(".axs", "application/olescript");
AddMimeType(".bas", "text/plain");
AddMimeType(".bcpio", "application/x-bcpio");
AddMimeType(".bin", "application/octet-stream");
AddMimeType(".bmp", "image/bmp");
AddMimeType(".c", "text/plain");
AddMimeType(".cab", "application/octet-stream");
AddMimeType(".calx", "application/vnd.ms-office.calx");
AddMimeType(".cat", "application/vnd.ms-pki.seccat");
AddMimeType(".cdf", "application/x-cdf");
AddMimeType(".chm", "application/octet-stream");
AddMimeType(".class", "application/x-java-applet");
AddMimeType(".clp", "application/x-msclip");
AddMimeType(".cmx", "image/x-cmx");
AddMimeType(".cnf", "text/plain");
AddMimeType(".cod", "image/cis-cod");
AddMimeType(".cpio", "application/x-cpio");
AddMimeType(".cpp", "text/plain");
AddMimeType(".crd", "application/x-mscardfile");
AddMimeType(".crl", "application/pkix-crl");
AddMimeType(".crt", "application/x-x509-ca-cert");
AddMimeType(".csh", "application/x-csh");
AddMimeType(".css", "text/css");
AddMimeType(".csv", "application/octet-stream");
AddMimeType(".cur", "application/octet-stream");
AddMimeType(".dcr", "application/x-director");
AddMimeType(".deploy", "application/octet-stream");
AddMimeType(".der", "application/x-x509-ca-cert");
AddMimeType(".dib", "image/bmp");
AddMimeType(".dir", "application/x-director");
AddMimeType(".disco", "text/xml");
AddMimeType(".dll", "application/x-msdownload");
AddMimeType(".dll.config", "text/xml");
AddMimeType(".dlm", "text/dlm");
AddMimeType(".doc", "application/msword");
AddMimeType(".docm", "application/vnd.ms-word.document.macroEnabled.12");
AddMimeType(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
AddMimeType(".dot", "application/msword");
AddMimeType(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
AddMimeType(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
AddMimeType(".dsp", "application/octet-stream");
AddMimeType(".dtd", "text/xml");
AddMimeType(".dvi", "application/x-dvi");
AddMimeType(".dwf", "drawing/x-dwf");
AddMimeType(".dwp", "application/octet-stream");
AddMimeType(".dxr", "application/x-director");
AddMimeType(".eml", "message/rfc822");
AddMimeType(".emz", "application/octet-stream");
AddMimeType(".eot", "application/octet-stream");
AddMimeType(".eps", "application/postscript");
AddMimeType(".etx", "text/x-setext");
AddMimeType(".evy", "application/envoy");
AddMimeType(".exe", "application/octet-stream");
AddMimeType(".exe.config", "text/xml");
AddMimeType(".fdf", "application/vnd.fdf");
AddMimeType(".fif", "application/fractals");
AddMimeType(".fla", "application/octet-stream");
AddMimeType(".flr", "x-world/x-vrml");
AddMimeType(".flv", "video/x-flv");
AddMimeType(".gif", "image/gif");
AddMimeType(".gtar", "application/x-gtar");
AddMimeType(".gz", "application/x-gzip");
AddMimeType(".h", "text/plain");
AddMimeType(".hdf", "application/x-hdf");
AddMimeType(".hdml", "text/x-hdml");
AddMimeType(".hhc", "application/x-oleobject");
AddMimeType(".hhk", "application/octet-stream");
AddMimeType(".hhp", "application/octet-stream");
AddMimeType(".hlp", "application/winhlp");
AddMimeType(".hqx", "application/mac-binhex40");
AddMimeType(".hta", "application/hta");
AddMimeType(".htc", "text/x-component");
AddMimeType(".htm", "text/html");
AddMimeType(".html", "text/html");
AddMimeType(".htt", "text/webviewhtml");
AddMimeType(".hxt", "text/html");
AddMimeType(".ico", "image/x-icon");
AddMimeType(".ics", "application/octet-stream");
AddMimeType(".ief", "image/ief");
AddMimeType(".iii", "application/x-iphone");
AddMimeType(".inf", "application/octet-stream");
AddMimeType(".ins", "application/x-internet-signup");
AddMimeType(".isp", "application/x-internet-signup");
AddMimeType(".IVF", "video/x-ivf");
AddMimeType(".jar", "application/java-archive");
AddMimeType(".java", "application/octet-stream");
AddMimeType(".jck", "application/liquidmotion");
AddMimeType(".jcz", "application/liquidmotion");
AddMimeType(".jfif", "image/pjpeg");
AddMimeType(".jpb", "application/octet-stream");
AddMimeType(".jpe", "image/jpeg");
AddMimeType(".jpeg", "image/jpeg");
AddMimeType(".jpg", "image/jpeg");
AddMimeType(".js", "application/x-javascript");
AddMimeType(".jsx", "text/jscript");
AddMimeType(".latex", "application/x-latex");
AddMimeType(".lit", "application/x-ms-reader");
AddMimeType(".lpk", "application/octet-stream");
AddMimeType(".lsf", "video/x-la-asf");
AddMimeType(".lsx", "video/x-la-asf");
AddMimeType(".lzh", "application/octet-stream");
AddMimeType(".m13", "application/x-msmediaview");
AddMimeType(".m14", "application/x-msmediaview");
AddMimeType(".m1v", "video/mpeg");
AddMimeType(".m3u", "audio/x-mpegurl");
AddMimeType(".man", "application/x-troff-man");
AddMimeType(".manifest", "application/x-ms-manifest");
AddMimeType(".map", "text/plain");
AddMimeType(".mdb", "application/x-msaccess");
AddMimeType(".mdp", "application/octet-stream");
AddMimeType(".me", "application/x-troff-me");
AddMimeType(".mht", "message/rfc822");
AddMimeType(".mhtml", "message/rfc822");
AddMimeType(".mid", "audio/mid");
AddMimeType(".midi", "audio/mid");
AddMimeType(".mix", "application/octet-stream");
AddMimeType(".mmf", "application/x-smaf");
AddMimeType(".mno", "text/xml");
AddMimeType(".mny", "application/x-msmoney");
AddMimeType(".mov", "video/quicktime");
AddMimeType(".movie", "video/x-sgi-movie");
AddMimeType(".mp2", "video/mpeg");
AddMimeType(".mp3", "audio/mpeg");
AddMimeType(".mpa", "video/mpeg");
AddMimeType(".mpe", "video/mpeg");
AddMimeType(".mpeg", "video/mpeg");
AddMimeType(".mpg", "video/mpeg");
AddMimeType(".mpp", "application/vnd.ms-project");
AddMimeType(".mpv2", "video/mpeg");
AddMimeType(".ms", "application/x-troff-ms");
AddMimeType(".msi", "application/octet-stream");
AddMimeType(".mso", "application/octet-stream");
AddMimeType(".mvb", "application/x-msmediaview");
AddMimeType(".mvc", "application/x-miva-compiled");
AddMimeType(".nc", "application/x-netcdf");
AddMimeType(".nsc", "video/x-ms-asf");
AddMimeType(".nws", "message/rfc822");
AddMimeType(".ocx", "application/octet-stream");
AddMimeType(".oda", "application/oda");
AddMimeType(".odc", "text/x-ms-odc");
AddMimeType(".ods", "application/oleobject");
AddMimeType(".one", "application/onenote");
AddMimeType(".onea", "application/onenote");
AddMimeType(".onetoc", "application/onenote");
AddMimeType(".onetoc2", "application/onenote");
AddMimeType(".onetmp", "application/onenote");
AddMimeType(".onepkg", "application/onenote");
AddMimeType(".osdx", "application/opensearchdescription+xml");
AddMimeType(".p10", "application/pkcs10");
AddMimeType(".p12", "application/x-pkcs12");
AddMimeType(".p7b", "application/x-pkcs7-certificates");
AddMimeType(".p7c", "application/pkcs7-mime");
AddMimeType(".p7m", "application/pkcs7-mime");
AddMimeType(".p7r", "application/x-pkcs7-certreqresp");
AddMimeType(".p7s", "application/pkcs7-signature");
AddMimeType(".pbm", "image/x-portable-bitmap");
AddMimeType(".pcx", "application/octet-stream");
AddMimeType(".pcz", "application/octet-stream");
AddMimeType(".pdf", "application/pdf");
AddMimeType(".pfb", "application/octet-stream");
AddMimeType(".pfm", "application/octet-stream");
AddMimeType(".pfx", "application/x-pkcs12");
AddMimeType(".pgm", "image/x-portable-graymap");
AddMimeType(".pko", "application/vnd.ms-pki.pko");
AddMimeType(".pma", "application/x-perfmon");
AddMimeType(".pmc", "application/x-perfmon");
AddMimeType(".pml", "application/x-perfmon");
AddMimeType(".pmr", "application/x-perfmon");
AddMimeType(".pmw", "application/x-perfmon");
AddMimeType(".png", "image/png");
AddMimeType(".pnm", "image/x-portable-anymap");
AddMimeType(".pnz", "image/png");
AddMimeType(".pot", "application/vnd.ms-powerpoint");
AddMimeType(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
AddMimeType(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
AddMimeType(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
AddMimeType(".ppm", "image/x-portable-pixmap");
AddMimeType(".pps", "application/vnd.ms-powerpoint");
AddMimeType(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
AddMimeType(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
AddMimeType(".ppt", "application/vnd.ms-powerpoint");
AddMimeType(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
AddMimeType(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
AddMimeType(".prf", "application/pics-rules");
AddMimeType(".prm", "application/octet-stream");
AddMimeType(".prx", "application/octet-stream");
AddMimeType(".ps", "application/postscript");
AddMimeType(".psd", "application/octet-stream");
AddMimeType(".psm", "application/octet-stream");
AddMimeType(".psp", "application/octet-stream");
AddMimeType(".pub", "application/x-mspublisher");
AddMimeType(".qt", "video/quicktime");
AddMimeType(".qtl", "application/x-quicktimeplayer");
AddMimeType(".qxd", "application/octet-stream");
AddMimeType(".ra", "audio/x-pn-realaudio");
AddMimeType(".ram", "audio/x-pn-realaudio");
AddMimeType(".rar", "application/octet-stream");
AddMimeType(".ras", "image/x-cmu-raster");
AddMimeType(".rf", "image/vnd.rn-realflash");
AddMimeType(".rgb", "image/x-rgb");
AddMimeType(".rm", "application/vnd.rn-realmedia");
AddMimeType(".rmi", "audio/mid");
AddMimeType(".roff", "application/x-troff");
AddMimeType(".rpm", "audio/x-pn-realaudio-plugin");
AddMimeType(".rtf", "application/rtf");
AddMimeType(".rtx", "text/richtext");
AddMimeType(".scd", "application/x-msschedule");
AddMimeType(".sct", "text/scriptlet");
AddMimeType(".sea", "application/octet-stream");
AddMimeType(".setpay", "application/set-payment-initiation");
AddMimeType(".setreg", "application/set-registration-initiation");
AddMimeType(".sgml", "text/sgml");
AddMimeType(".sh", "application/x-sh");
AddMimeType(".shar", "application/x-shar");
AddMimeType(".sit", "application/x-stuffit");
AddMimeType(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
AddMimeType(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
AddMimeType(".smd", "audio/x-smd");
AddMimeType(".smi", "application/octet-stream");
AddMimeType(".smx", "audio/x-smd");
AddMimeType(".smz", "audio/x-smd");
AddMimeType(".snd", "audio/basic");
AddMimeType(".snp", "application/octet-stream");
AddMimeType(".spc", "application/x-pkcs7-certificates");
AddMimeType(".spl", "application/futuresplash");
AddMimeType(".src", "application/x-wais-source");
AddMimeType(".ssm", "application/streamingmedia");
AddMimeType(".sst", "application/vnd.ms-pki.certstore");
AddMimeType(".stl", "application/vnd.ms-pki.stl");
AddMimeType(".sv4cpio", "application/x-sv4cpio");
AddMimeType(".sv4crc", "application/x-sv4crc");
AddMimeType(".swf", "application/x-shockwave-flash");
AddMimeType(".t", "application/x-troff");
AddMimeType(".tar", "application/x-tar");
AddMimeType(".tcl", "application/x-tcl");
AddMimeType(".tex", "application/x-tex");
AddMimeType(".texi", "application/x-texinfo");
AddMimeType(".texinfo", "application/x-texinfo");
AddMimeType(".tgz", "application/x-compressed");
AddMimeType(".thmx", "application/vnd.ms-officetheme");
AddMimeType(".thn", "application/octet-stream");
AddMimeType(".tif", "image/tiff");
AddMimeType(".tiff", "image/tiff");
AddMimeType(".toc", "application/octet-stream");
AddMimeType(".tr", "application/x-troff");
AddMimeType(".trm", "application/x-msterminal");
AddMimeType(".tsv", "text/tab-separated-values");
AddMimeType(".ttf", "application/octet-stream");
AddMimeType(".txt", "text/plain");
AddMimeType(".u32", "application/octet-stream");
AddMimeType(".uls", "text/iuls");
AddMimeType(".ustar", "application/x-ustar");
AddMimeType(".vbs", "text/vbscript");
AddMimeType(".vcf", "text/x-vcard");
AddMimeType(".vcs", "text/plain");
AddMimeType(".vdx", "application/vnd.ms-visio.viewer");
AddMimeType(".vml", "text/xml");
AddMimeType(".vsd", "application/vnd.visio");
AddMimeType(".vss", "application/vnd.visio");
AddMimeType(".vst", "application/vnd.visio");
AddMimeType(".vsto", "application/x-ms-vsto");
AddMimeType(".vsw", "application/vnd.visio");
AddMimeType(".vsx", "application/vnd.visio");
AddMimeType(".vtx", "application/vnd.visio");
AddMimeType(".wav", "audio/wav");
AddMimeType(".wax", "audio/x-ms-wax");
AddMimeType(".wbmp", "image/vnd.wap.wbmp");
AddMimeType(".wcm", "application/vnd.ms-works");
AddMimeType(".wdb", "application/vnd.ms-works");
AddMimeType(".wks", "application/vnd.ms-works");
AddMimeType(".wm", "video/x-ms-wm");
AddMimeType(".wma", "audio/x-ms-wma");
AddMimeType(".wmd", "application/x-ms-wmd");
AddMimeType(".wmf", "application/x-msmetafile");
AddMimeType(".wml", "text/vnd.wap.wml");
AddMimeType(".wmlc", "application/vnd.wap.wmlc");
AddMimeType(".wmls", "text/vnd.wap.wmlscript");
AddMimeType(".wmlsc", "application/vnd.wap.wmlscriptc");
AddMimeType(".wmp", "video/x-ms-wmp");
AddMimeType(".wmv", "video/x-ms-wmv");
AddMimeType(".wmx", "video/x-ms-wmx");
AddMimeType(".wmz", "application/x-ms-wmz");
AddMimeType(".wps", "application/vnd.ms-works");
AddMimeType(".wri", "application/x-mswrite");
AddMimeType(".wrl", "x-world/x-vrml");
AddMimeType(".wrz", "x-world/x-vrml");
AddMimeType(".wsdl", "text/xml");
AddMimeType(".wvx", "video/x-ms-wvx");
AddMimeType(".x", "application/directx");
AddMimeType(".xaf", "x-world/x-vrml");
AddMimeType(".xaml", "application/xaml+xml");
AddMimeType(".xap", "application/x-silverlight-app");
AddMimeType(".xbap", "application/x-ms-xbap");
AddMimeType(".xbm", "image/x-xbitmap");
AddMimeType(".xdr", "text/plain");
AddMimeType(".xla", "application/vnd.ms-excel");
AddMimeType(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
AddMimeType(".xlc", "application/vnd.ms-excel");
AddMimeType(".xlm", "application/vnd.ms-excel");
AddMimeType(".xls", "application/vnd.ms-excel");
AddMimeType(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
AddMimeType(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
AddMimeType(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
AddMimeType(".xlt", "application/vnd.ms-excel");
AddMimeType(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
AddMimeType(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
AddMimeType(".xlw", "application/vnd.ms-excel");
AddMimeType(".xml", "text/xml");
AddMimeType(".xof", "x-world/x-vrml");
AddMimeType(".xpm", "image/x-xpixmap");
AddMimeType(".xps", "application/vnd.ms-xpsdocument");
AddMimeType(".xsd", "text/xml");
AddMimeType(".xsf", "text/xml");
AddMimeType(".xsl", "text/xml");
AddMimeType(".xslt", "text/xml");
AddMimeType(".xsn", "application/octet-stream");
AddMimeType(".xtp", "application/octet-stream");
AddMimeType(".xwd", "image/x-xwindowdump");
AddMimeType(".z", "application/x-compress");
AddMimeType(".zip", "application/x-zip-compressed");
}
}
}
| |
// 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: This class implements a set of methods for retrieving
// sort key information.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization
{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
public partial class SortKey
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
[OptionalField(VersionAdded = 3)]
internal string _localeName; // locale identifier
[OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
internal int _win32LCID;
// Whidbey serialization
internal CompareOptions _options; // options
internal string _string; // original string
internal byte[] _keyData; // sortkey data
//
// The following constructor is designed to be called from CompareInfo to get the
// the sort key of specific string for synthetic culture
//
internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
{
_keyData = keyData;
_localeName = localeName;
_options = options;
_string = str;
}
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
//set LCID to proper value for Whidbey serialization (no other use)
if (_win32LCID == 0)
{
_win32LCID = CultureInfo.GetCultureInfo(_localeName).LCID;
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
//set locale name to proper value after Whidbey deserialization
if (String.IsNullOrEmpty(_localeName) && _win32LCID != 0)
{
_localeName = CultureInfo.GetCultureInfo(_win32LCID).Name;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
//
// Returns the original string used to create the current instance
// of SortKey.
//
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
get
{
return (_string);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
//
// Returns a byte array representing the current instance of the
// sort key.
//
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
get
{
return (byte[])(_keyData.Clone());
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two sort keys. Returns 0 if the two sort keys are
// equal, a number less than 0 if sortkey1 is less than sortkey2,
// and a number greater than 0 if sortkey1 is greater than sortkey2.
//
////////////////////////////////////////////////////////////////////////
public static int Compare(SortKey sortkey1, SortKey sortkey2)
{
if (sortkey1==null || sortkey2==null)
{
throw new ArgumentNullException((sortkey1 == null ? nameof(sortkey1) : nameof(sortkey2)));
}
Contract.EndContractBlock();
byte[] key1Data = sortkey1._keyData;
byte[] key2Data = sortkey2._keyData;
Debug.Assert(key1Data != null, "key1Data != null");
Debug.Assert(key2Data != null, "key2Data != null");
if (key1Data.Length == 0)
{
if (key2Data.Length == 0)
{
return (0);
}
return (-1);
}
if (key2Data.Length == 0)
{
return (1);
}
int compLen = (key1Data.Length < key2Data.Length) ? key1Data.Length : key2Data.Length;
for (int i=0; i<compLen; i++)
{
if (key1Data[i]>key2Data[i])
{
return (1);
}
if (key1Data[i]<key2Data[i])
{
return (-1);
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same SortKey as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
SortKey that = value as SortKey;
if (that != null)
{
return Compare(this, that) == 0;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// SortKey. The hash code is guaranteed to be the same for
// SortKey A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (CompareInfo.GetCompareInfo(_localeName).GetHashCodeOfString(_string, _options));
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// SortKey.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("SortKey - " + _localeName + ", " + _options + ", " + _string);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.DotNet.Cli.CommandLine
{
internal class CommandLineApplication
{
private enum ParseOptionResult
{
Succeeded,
ShowHelp,
ShowVersion,
UnexpectedArgs,
}
// Indicates whether the parser should throw an exception when it runs into an unexpected argument.
// If this field is set to false, the parser will stop parsing when it sees an unexpected argument, and all
// remaining arguments, including the first unexpected argument, will be stored in RemainingArguments property.
private readonly bool _throwOnUnexpectedArg;
public CommandLineApplication(bool throwOnUnexpectedArg = true)
{
_throwOnUnexpectedArg = throwOnUnexpectedArg;
Options = new List<CommandOption>();
Arguments = new List<CommandArgument>();
Commands = new List<CommandLineApplication>();
RemainingArguments = new List<string>();
Invoke = () => 0;
}
public CommandLineApplication Parent { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public string Syntax { get; set; }
public string Description { get; set; }
public List<CommandOption> Options { get; private set; }
public CommandOption OptionHelp { get; private set; }
public CommandOption OptionVersion { get; private set; }
public List<CommandArgument> Arguments { get; private set; }
public List<string> RemainingArguments { get; private set; }
public bool IsShowingInformation { get; protected set; } // Is showing help or version?
public Func<int> Invoke { get; set; }
public Func<string> LongVersionGetter { get; set; }
public Func<string> ShortVersionGetter { get; set; }
public List<CommandLineApplication> Commands { get; private set; }
public bool HandleResponseFiles { get; set; }
public bool AllowArgumentSeparator { get; set; }
public bool HandleRemainingArguments { get; set; }
public string ArgumentSeparatorHelpText { get; set; }
public CommandLineApplication AddCommand(string name, bool throwOnUnexpectedArg = true)
{
return AddCommand(name, _ => { }, throwOnUnexpectedArg);
}
public CommandLineApplication AddCommand(string name, Action<CommandLineApplication> configuration,
bool throwOnUnexpectedArg = true)
{
var command = new CommandLineApplication(throwOnUnexpectedArg) { Name = name };
return AddCommand(command, configuration, throwOnUnexpectedArg);
}
public CommandLineApplication AddCommand(CommandLineApplication command, bool throwOnUnexpectedArg = true)
{
return AddCommand(command, _ => { }, throwOnUnexpectedArg);
}
public CommandLineApplication AddCommand(
CommandLineApplication command,
Action<CommandLineApplication> configuration,
bool throwOnUnexpectedArg = true)
{
if (command == null || configuration == null)
{
throw new NullReferenceException();
}
command.Parent = this;
Commands.Add(command);
configuration(command);
return command;
}
public CommandOption Option(string template, string description, CommandOptionType optionType)
{
return Option(template, description, optionType, _ => { });
}
public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration)
{
var option = new CommandOption(template, optionType) { Description = description };
Options.Add(option);
configuration(option);
return option;
}
public CommandArgument Argument(string name, string description, bool multipleValues = false)
{
return Argument(name, description, _ => { }, multipleValues);
}
public CommandArgument Argument(string name, string description, Action<CommandArgument> configuration, bool multipleValues = false)
{
var lastArg = Arguments.LastOrDefault();
if (lastArg != null && lastArg.MultipleValues)
{
var message = string.Format(LocalizableStrings.LastArgumentMultiValueError,
lastArg.Name);
throw new InvalidOperationException(message);
}
var argument = new CommandArgument { Name = name, Description = description, MultipleValues = multipleValues };
Arguments.Add(argument);
configuration(argument);
return argument;
}
public void OnExecute(Func<int> invoke)
{
Invoke = invoke;
}
public void OnExecute(Func<Task<int>> invoke)
{
Invoke = () => invoke().Result;
}
public int Execute(params string[] args)
{
CommandLineApplication command = this;
CommandArgumentEnumerator arguments = null;
if (HandleResponseFiles)
{
args = ExpandResponseFiles(args).ToArray();
}
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
bool isLongOption = arg.StartsWith("--");
if (arg == "-?" || arg == "/?")
{
command.ShowHelp();
return 0;
}
else if (isLongOption || arg.StartsWith("-"))
{
CommandOption option;
var result = ParseOption(isLongOption, command, args, ref index, out option);
if (result == ParseOptionResult.ShowHelp)
{
command.ShowHelp();
return 0;
}
else if (result == ParseOptionResult.ShowVersion)
{
command.ShowVersion();
return 0;
}
else if (result == ParseOptionResult.UnexpectedArgs)
{
break;
}
}
else
{
var subcommand = ParseSubCommand(arg, command);
if (subcommand != null)
{
command = subcommand;
}
else
{
if (arguments == null || arguments.CommandName != command.Name)
{
arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator(), command.Name);
}
if (arguments.MoveNext())
{
arguments.Current.Values.Add(arg);
}
else
{
HandleUnexpectedArg(command, args, index, argTypeName: "command or argument");
break;
}
}
}
}
if (Commands.Count > 0 && command == this)
{
throw new CommandParsingException(
command,
"Required command missing",
isRequireSubCommandMissing: true);
}
return command.Invoke();
}
private ParseOptionResult ParseOption(
bool isLongOption,
CommandLineApplication command,
string[] args,
ref int index,
out CommandOption option)
{
option = null;
ParseOptionResult result = ParseOptionResult.Succeeded;
var arg = args[index];
int optionPrefixLength = isLongOption ? 2 : 1;
string[] optionComponents = arg.Substring(optionPrefixLength).Split(new[] { ':', '=' }, 2);
string optionName = optionComponents[0];
if (isLongOption)
{
option = command.Options.SingleOrDefault(
opt => string.Equals(opt.LongName, optionName, StringComparison.Ordinal));
}
else
{
option = command.Options.SingleOrDefault(
opt => string.Equals(opt.ShortName, optionName, StringComparison.Ordinal));
if (option == null)
{
option = command.Options.SingleOrDefault(
opt => string.Equals(opt.SymbolName, optionName, StringComparison.Ordinal));
}
}
if (option == null)
{
if (isLongOption && string.IsNullOrEmpty(optionName) &&
!command._throwOnUnexpectedArg && AllowArgumentSeparator)
{
// a stand-alone "--" is the argument separator, so skip it and
// handle the rest of the args as unexpected args
index++;
}
HandleUnexpectedArg(command, args, index, argTypeName: "option");
result = ParseOptionResult.UnexpectedArgs;
}
else if (command.OptionHelp == option)
{
result = ParseOptionResult.ShowHelp;
}
else if (command.OptionVersion == option)
{
result = ParseOptionResult.ShowVersion;
}
else
{
if (optionComponents.Length == 2)
{
if (!option.TryParse(optionComponents[1]))
{
command.ShowHint();
throw new CommandParsingException(command,
String.Format(LocalizableStrings.UnexpectedValueForOptionError, optionComponents[1], optionName));
}
}
else
{
if (option.OptionType == CommandOptionType.NoValue ||
option.OptionType == CommandOptionType.BoolValue)
{
// No value is needed for this option
option.TryParse(null);
}
else
{
index++;
if (index < args.Length)
{
arg = args[index];
if (!option.TryParse(arg))
{
command.ShowHint();
throw new CommandParsingException(
command,
String.Format(LocalizableStrings.UnexpectedValueForOptionError, arg, optionName));
}
}
else
{
command.ShowHint();
throw new CommandParsingException(
command,
String.Format(LocalizableStrings.OptionRequiresSingleValueWhichIsMissing, arg, optionName));
}
}
}
}
return result;
}
private CommandLineApplication ParseSubCommand(string arg, CommandLineApplication command)
{
foreach (var subcommand in command.Commands)
{
if (string.Equals(subcommand.Name, arg, StringComparison.OrdinalIgnoreCase))
{
return subcommand;
}
}
return null;
}
// Helper method that adds a help option
public CommandOption HelpOption(string template)
{
// Help option is special because we stop parsing once we see it
// So we store it separately for further use
OptionHelp = Option(template, LocalizableStrings.ShowHelpInfo, CommandOptionType.NoValue);
return OptionHelp;
}
public CommandOption VersionOption(string template,
string shortFormVersion,
string longFormVersion = null)
{
if (longFormVersion == null)
{
return VersionOption(template, () => shortFormVersion);
}
else
{
return VersionOption(template, () => shortFormVersion, () => longFormVersion);
}
}
// Helper method that adds a version option
public CommandOption VersionOption(string template,
Func<string> shortFormVersionGetter,
Func<string> longFormVersionGetter = null)
{
// Version option is special because we stop parsing once we see it
// So we store it separately for further use
OptionVersion = Option(template, LocalizableStrings.ShowVersionInfo, CommandOptionType.NoValue);
ShortVersionGetter = shortFormVersionGetter;
LongVersionGetter = longFormVersionGetter ?? shortFormVersionGetter;
return OptionVersion;
}
// Show short hint that reminds users to use help option
public void ShowHint()
{
if (OptionHelp != null)
{
Console.WriteLine(string.Format(LocalizableStrings.ShowHintInfo, OptionHelp.LongName));
}
}
// Show full help
public void ShowHelp(string commandName = null)
{
var headerBuilder = new StringBuilder(LocalizableStrings.UsageHeader);
var usagePrefixLength = headerBuilder.Length;
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
cmd.IsShowingInformation = true;
if (cmd != this && cmd.Arguments.Any())
{
var args = string.Join(" ", cmd.Arguments.Select(arg => arg.Name));
headerBuilder.Insert(usagePrefixLength, string.Format(LocalizableStrings.UsageItemWithArgs, cmd.Name, args));
}
else
{
headerBuilder.Insert(usagePrefixLength, string.Format(LocalizableStrings.UsageItemWithoutArgs, cmd.Name));
}
}
CommandLineApplication target;
if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase))
{
target = this;
}
else
{
target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase));
if (target != null)
{
headerBuilder.AppendFormat(LocalizableStrings.CommandItem, commandName);
}
else
{
// The command name is invalid so don't try to show help for something that doesn't exist
target = this;
}
}
var optionsBuilder = new StringBuilder();
var commandsBuilder = new StringBuilder();
var argumentsBuilder = new StringBuilder();
var argumentSeparatorBuilder = new StringBuilder();
int maxArgLen = 0;
for (var cmd = target; cmd != null; cmd = cmd.Parent)
{
if (cmd.Arguments.Any())
{
if (cmd == target)
{
headerBuilder.Append(LocalizableStrings.UsageArgumentsToken);
}
if (argumentsBuilder.Length == 0)
{
argumentsBuilder.AppendLine();
argumentsBuilder.AppendLine(LocalizableStrings.UsageArgumentsHeader);
}
maxArgLen = Math.Max(maxArgLen, MaxArgumentLength(cmd.Arguments));
}
}
for (var cmd = target; cmd != null; cmd = cmd.Parent)
{
if (cmd.Arguments.Any())
{
var outputFormat = LocalizableStrings.UsageArgumentItem;
foreach (var arg in cmd.Arguments)
{
argumentsBuilder.AppendFormat(
outputFormat,
arg.Name.PadRight(maxArgLen + 2),
arg.Description);
argumentsBuilder.AppendLine();
}
}
}
if (target.Options.Any())
{
headerBuilder.Append(LocalizableStrings.UsageOptionsToken);
optionsBuilder.AppendLine();
optionsBuilder.AppendLine(LocalizableStrings.UsageOptionsHeader);
var maxOptLen = MaxOptionTemplateLength(target.Options);
var outputFormat = string.Format(LocalizableStrings.UsageOptionsItem, maxOptLen + 2);
foreach (var opt in target.Options)
{
optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description);
optionsBuilder.AppendLine();
}
}
if (target.Commands.Any())
{
headerBuilder.Append(LocalizableStrings.UsageCommandToken);
commandsBuilder.AppendLine();
commandsBuilder.AppendLine(LocalizableStrings.UsageCommandsHeader);
var maxCmdLen = MaxCommandLength(target.Commands);
var outputFormat = string.Format(LocalizableStrings.UsageCommandsItem, maxCmdLen + 2);
foreach (var cmd in target.Commands.OrderBy(c => c.Name))
{
commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description);
commandsBuilder.AppendLine();
}
if (OptionHelp != null)
{
commandsBuilder.AppendLine();
commandsBuilder.AppendFormat(LocalizableStrings.UsageCommandsDetailHelp, Name);
commandsBuilder.AppendLine();
}
}
if (target.AllowArgumentSeparator || target.HandleRemainingArguments)
{
if (target.AllowArgumentSeparator)
{
headerBuilder.Append(LocalizableStrings.UsageCommandAdditionalArgs);
}
else
{
headerBuilder.Append(LocalizableStrings.UsageCommandArgs);
}
if (!string.IsNullOrEmpty(target.ArgumentSeparatorHelpText))
{
argumentSeparatorBuilder.AppendLine();
argumentSeparatorBuilder.AppendLine(LocalizableStrings.UsageCommandsAdditionalArgsHeader);
argumentSeparatorBuilder.AppendLine(String.Format(LocalizableStrings.UsageCommandsAdditionalArgsItem, target.ArgumentSeparatorHelpText));
argumentSeparatorBuilder.AppendLine();
}
}
headerBuilder.AppendLine();
var nameAndVersion = new StringBuilder();
nameAndVersion.AppendLine(GetFullNameAndVersion());
nameAndVersion.AppendLine();
Console.Write("{0}{1}{2}{3}{4}{5}", nameAndVersion, headerBuilder, argumentsBuilder, optionsBuilder, commandsBuilder, argumentSeparatorBuilder);
}
public void ShowVersion()
{
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
cmd.IsShowingInformation = true;
}
Console.WriteLine(FullName);
Console.WriteLine(LongVersionGetter());
}
public string GetFullNameAndVersion()
{
return ShortVersionGetter == null ? FullName : string.Format(LocalizableStrings.ShortVersionTemplate, FullName, ShortVersionGetter());
}
public void ShowRootCommandFullNameAndVersion()
{
var rootCmd = this;
while (rootCmd.Parent != null)
{
rootCmd = rootCmd.Parent;
}
Console.WriteLine(rootCmd.GetFullNameAndVersion());
Console.WriteLine();
}
private int MaxOptionTemplateLength(IEnumerable<CommandOption> options)
{
var maxLen = 0;
foreach (var opt in options)
{
maxLen = opt.Template.Length > maxLen ? opt.Template.Length : maxLen;
}
return maxLen;
}
private int MaxCommandLength(IEnumerable<CommandLineApplication> commands)
{
var maxLen = 0;
foreach (var cmd in commands)
{
maxLen = cmd.Name.Length > maxLen ? cmd.Name.Length : maxLen;
}
return maxLen;
}
private int MaxArgumentLength(IEnumerable<CommandArgument> arguments)
{
var maxLen = 0;
foreach (var arg in arguments)
{
maxLen = arg.Name.Length > maxLen ? arg.Name.Length : maxLen;
}
return maxLen;
}
private void HandleUnexpectedArg(CommandLineApplication command, string[] args, int index, string argTypeName)
{
if (command._throwOnUnexpectedArg)
{
command.ShowHint();
throw new CommandParsingException(command, String.Format(LocalizableStrings.UnexpectedArgumentError, argTypeName, args[index]));
}
else
{
// All remaining arguments are stored for further use
command.RemainingArguments.AddRange(new ArraySegment<string>(args, index, args.Length - index));
}
}
private IEnumerable<string> ExpandResponseFiles(IEnumerable<string> args)
{
foreach (var arg in args)
{
if (!arg.StartsWith("@", StringComparison.Ordinal))
{
yield return arg;
}
else
{
var fileName = arg.Substring(1);
var responseFileArguments = ParseResponseFile(fileName);
// ParseResponseFile can suppress expanding this response file by
// returning null. In that case, we'll treat the response
// file token as a regular argument.
if (responseFileArguments == null)
{
yield return arg;
}
else
{
foreach (var responseFileArgument in responseFileArguments)
yield return responseFileArgument.Trim();
}
}
}
}
private IEnumerable<string> ParseResponseFile(string fileName)
{
if (!HandleResponseFiles)
return null;
if (!File.Exists(fileName))
{
throw new InvalidOperationException(String.Format(LocalizableStrings.ResponseFileNotFoundError, fileName));
}
return File.ReadLines(fileName);
}
private class CommandArgumentEnumerator : IEnumerator<CommandArgument>
{
private readonly IEnumerator<CommandArgument> _enumerator;
public CommandArgumentEnumerator(
IEnumerator<CommandArgument> enumerator,
string commandName)
{
CommandName = commandName;
_enumerator = enumerator;
}
public string CommandName { get; }
public CommandArgument Current
{
get
{
return _enumerator.Current;
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public void Dispose()
{
_enumerator.Dispose();
}
public bool MoveNext()
{
if (Current == null || !Current.MultipleValues)
{
return _enumerator.MoveNext();
}
// If current argument allows multiple values, we don't move forward and
// all later values will be added to current CommandArgument.Values
return true;
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
using System;
/// <summary>
/// String.PadLeft(Int32, Char)
/// Right-aligns the characters in this instance,
/// padding on the left with a specified Unicode character for a specified total length.
/// </summary>
public class StringPadLeft2
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringPadLeft2 spl = new StringPadLeft2();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.PadLeft(Int32, Char)");
if (spl.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Total width is greater than old string length";
const string c_TEST_ID = "P001";
int totalWidth;
char ch;
string str;
bool condition1 = false; //Verify the space paded
bool condition2 = false; //Verify the old string
bool expectedValue = true;
bool actualValue = false;
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
//str = "hello";
totalWidth = GetInt32(str.Length + 1, str.Length + c_MAX_STRING_LEN);
//totalWidth = 8;
ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strPaded = str.PadLeft(totalWidth, ch);
char[] trimChs = new char[] {ch};
string spaces = new string(ch, totalWidth - str.Length);
string spacesPaded = strPaded.Substring(0, totalWidth - str.Length);
condition1 = (string.CompareOrdinal(spaces, spacesPaded) == 0);
condition2 = (string.CompareOrdinal(strPaded.TrimStart(trimChs), str) == 0);
actualValue = condition1 && condition2;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(str, totalWidth, ch);
TestLibrary.TestFramework.LogError("001" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth, ch));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: 0 <= total width <= old string length";
const string c_TEST_ID = "P002";
int totalWidth;
char ch;
string str;
bool expectedValue = true;
bool actualValue = false;
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
totalWidth = GetInt32(0, str.Length - 1);
ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strPaded = str.PadLeft(totalWidth, ch);
actualValue = (0 == string.CompareOrdinal(strPaded, str));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(str, totalWidth, ch);
TestLibrary.TestFramework.LogError("003" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth, ch));
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenarios
//ArgumentException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Total width is less than zero. ";
const string c_TEST_ID = "N001";
int totalWidth;
char ch;
string str;
totalWidth = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str.PadLeft(totalWidth);
TestLibrary.TestFramework.LogError("005" + "TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected" + GetDataString(str, totalWidth, ch));
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e +GetDataString(str, totalWidth, ch));
retVal = false;
}
return retVal;
}
//OutOfMemoryException
public bool NegTest2() // bug 8-8-2006 Noter(v-yaduoj)
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: Too great width ";
const string c_TEST_ID = "N002";
int totalWidth;
char ch;
string str;
totalWidth = Int32.MaxValue;
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str.PadLeft(totalWidth,ch);
TestLibrary.TestFramework.LogError("007" + "TestId-" + c_TEST_ID, "OutOfMemoryException is not thrown as expected" + GetDataString(str, totalWidth,ch));
retVal = false;
}
catch (OutOfMemoryException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth, ch));
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
private string GetDataString(string strSrc, int totalWidth, char ch)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Total width]\n{0}", totalWidth);
str += string.Format("\n[Padding character]\n{0}", ch);
return str;
}
}
| |
//
// Authors:
// Ben Motmans <ben.motmans@gmail.com>
//
// Copyright (c) 2007 Ben Motmans
//
// 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 Gtk;
using System;
using System.Threading;
using System.Collections.Generic;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Database.Sql;
using MonoDevelop.Database.Components;
namespace MonoDevelop.Database.Designer
{
[System.ComponentModel.Category("widget")]
[System.ComponentModel.ToolboxItem(true)]
public partial class TriggersEditorWidget : Gtk.Bin
{
public event EventHandler ContentChanged;
private ISchemaProvider schemaProvider;
private TableSchema table;
private TriggerSchemaCollection triggers;
private SchemaActions action;
private ListStore store;
private ListStore storeTypes;
private ListStore storeEvents;
private const int colNameIndex = 0;
private const int colTypeIndex = 1;
private const int colEventIndex = 2;
private const int colFireTypeIndex = 3;
private const int colPositionIndex = 4;
private const int colActiveIndex = 5;
private const int colCommentIndex = 6;
private const int colSourceIndex = 7;
private const int colObjIndex = 8;
public TriggersEditorWidget (ISchemaProvider schemaProvider, SchemaActions action)
{
if (schemaProvider == null)
throw new ArgumentNullException ("schemaProvider");
this.schemaProvider = schemaProvider;
this.action = action;
this.Build();
sqlEditor.Editable = false;
sqlEditor.TextChanged += new EventHandler (SourceChanged);
store = new ListStore (typeof (string), typeof (string), typeof (string), typeof (bool), typeof (string), typeof (bool), typeof (string), typeof (string), typeof (object));
storeTypes = new ListStore (typeof (string));
storeEvents = new ListStore (typeof (string));
listTriggers.Model = store;
listTriggers.Selection.Changed += new EventHandler (OnSelectionChanged);
foreach (string name in Enum.GetNames (typeof (TriggerType)))
storeTypes.AppendValues (name);
foreach (string name in Enum.GetNames (typeof (TriggerEvent)))
storeEvents.AppendValues (name);
TreeViewColumn colName = new TreeViewColumn ();
TreeViewColumn colType = new TreeViewColumn ();
TreeViewColumn colEvent = new TreeViewColumn ();
TreeViewColumn colFireType = new TreeViewColumn ();
TreeViewColumn colPosition = new TreeViewColumn ();
TreeViewColumn colActive = new TreeViewColumn ();
TreeViewColumn colComment = new TreeViewColumn ();
colName.Title = AddinCatalog.GetString ("Name");
colType.Title = AddinCatalog.GetString ("Type");
colEvent.Title = AddinCatalog.GetString ("Event");
colFireType.Title = AddinCatalog.GetString ("Each Row");
colPosition.Title = AddinCatalog.GetString ("Position");
colActive.Title = AddinCatalog.GetString ("Active");
colComment.Title = AddinCatalog.GetString ("Comment");
colType.MinWidth = 120;
colEvent.MinWidth = 120;
CellRendererText nameRenderer = new CellRendererText ();
CellRendererCombo typeRenderer = new CellRendererCombo ();
CellRendererCombo eventRenderer = new CellRendererCombo ();
CellRendererToggle fireTypeRenderer = new CellRendererToggle ();
CellRendererText positionRenderer = new CellRendererText ();
CellRendererToggle activeRenderer = new CellRendererToggle ();
CellRendererText commentRenderer = new CellRendererText ();
nameRenderer.Editable = true;
nameRenderer.Edited += new EditedHandler (NameEdited);
typeRenderer.Model = storeTypes;
typeRenderer.TextColumn = 0;
typeRenderer.Editable = true;
typeRenderer.Edited += new EditedHandler (TypeEdited);
eventRenderer.Model = storeEvents;
eventRenderer.TextColumn = 0;
eventRenderer.Editable = true;
eventRenderer.Edited += new EditedHandler (EventEdited);
fireTypeRenderer.Activatable = true;
fireTypeRenderer.Toggled += new ToggledHandler (FireTypeToggled);
positionRenderer.Editable = true;
positionRenderer.Edited += new EditedHandler (PositionEdited);
activeRenderer.Activatable = true;
activeRenderer.Toggled += new ToggledHandler (ActiveToggled);
commentRenderer.Editable = true;
commentRenderer.Edited += new EditedHandler (CommentEdited);
colName.PackStart (nameRenderer, true);
colType.PackStart (typeRenderer, true);
colEvent.PackStart (eventRenderer, true);
colFireType.PackStart (fireTypeRenderer, true);
colPosition.PackStart (positionRenderer, true);
colActive.PackStart (activeRenderer, true);
colComment.PackStart (commentRenderer, true);
colName.AddAttribute (nameRenderer, "text", colNameIndex);
colType.AddAttribute (typeRenderer, "text", colTypeIndex);
colEvent.AddAttribute (eventRenderer, "text", colEventIndex);
colFireType.AddAttribute (fireTypeRenderer, "active", colFireTypeIndex);
colPosition.AddAttribute (positionRenderer, "text", colPositionIndex);
colActive.AddAttribute (activeRenderer, "active", colActiveIndex);
colComment.AddAttribute (commentRenderer, "text", colCommentIndex);
listTriggers.AppendColumn (colName);
listTriggers.AppendColumn (colType);
listTriggers.AppendColumn (colEvent);
listTriggers.AppendColumn (colFireType);
listTriggers.AppendColumn (colPosition);
listTriggers.AppendColumn (colActive);
listTriggers.AppendColumn (colComment);
ShowAll ();
}
public void Initialize (TableSchema table, TriggerSchemaCollection triggers)
{
if (table == null)
throw new ArgumentNullException ("table");
if (triggers == null)
throw new ArgumentNullException ("triggers");
this.table = table;
this.triggers = triggers;
if (action == SchemaActions.Alter)
foreach (TriggerSchema trigger in triggers)
AddTrigger (trigger);
}
protected virtual void RemoveClicked (object sender, System.EventArgs e)
{
TreeIter iter;
if (listTriggers.Selection.GetSelected (out iter)) {
TriggerSchema trigger = store.GetValue (iter, colObjIndex) as TriggerSchema;
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to remove trigger '{0}'?", trigger.Name),
AlertButton.Remove
)) {
store.Remove (ref iter);
triggers.Remove (trigger);
EmitContentChanged ();
}
}
}
protected virtual void AddClicked (object sender, EventArgs e)
{
TriggerSchema trigger = schemaProvider.CreateTriggerSchema (string.Concat (table.Name,
"_",
"trigger_",
table.Name));
trigger.TableName = table.Name;
int index = 1;
while (triggers.Contains (trigger.Name))
trigger.Name = "trigger_" + table.Name + (index++);
// triggers.Add (trigger);
AddTrigger (trigger);
EmitContentChanged ();
}
private void AddTrigger (TriggerSchema trigger)
{
store.AppendValues (trigger.Name, trigger.TriggerType.ToString (),
trigger.TriggerEvent.ToString (), trigger.TriggerFireType == TriggerFireType.ForEachRow,
trigger.Position.ToString (), trigger.IsActive, trigger.Comment,
trigger.Source , trigger);
}
private void NameEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
if (!string.IsNullOrEmpty (args.NewText)) {
store.SetValue (iter, colNameIndex, args.NewText);
} else {
string oldText = store.GetValue (iter, colNameIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
}
protected virtual void OnSelectionChanged (object sender, EventArgs e)
{
TreeIter iter;
if (listTriggers.Selection.GetSelected (out iter)) {
buttonRemove.Sensitive = true;
sqlEditor.Editable = true;
TriggerSchema trigger = store.GetValue (iter, colObjIndex) as TriggerSchema;
sqlEditor.Text = trigger.Source;
} else {
buttonRemove.Sensitive = false;
sqlEditor.Editable = false;
sqlEditor.Text = String.Empty;
}
}
private void SourceChanged (object sender, EventArgs args)
{
TreeIter iter;
if (listTriggers.Selection.GetSelected (out iter)) {
store.SetValue (iter, colSourceIndex, sqlEditor.Text);
EmitContentChanged ();
}
}
private void TypeEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
foreach (string name in Enum.GetNames (typeof (TriggerType))) {
if (args.NewText == name) {
store.SetValue (iter, colTypeIndex, args.NewText);
EmitContentChanged ();
return;
}
}
string oldText = store.GetValue (iter, colTypeIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
private void EventEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
foreach (string name in Enum.GetNames (typeof (TriggerEvent))) {
if (args.NewText == name) {
store.SetValue (iter, colEventIndex, args.NewText);
EmitContentChanged ();
return;
}
}
string oldText = store.GetValue (iter, colEventIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
private void PositionEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
int len;
if (!string.IsNullOrEmpty (args.NewText) && int.TryParse (args.NewText, out len)) {
store.SetValue (iter, colPositionIndex, args.NewText);
EmitContentChanged ();
} else {
string oldText = store.GetValue (iter, colPositionIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
}
private void FireTypeToggled (object sender, ToggledArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
bool val = (bool) store.GetValue (iter, colFireTypeIndex);
store.SetValue (iter, colFireTypeIndex, !val);
EmitContentChanged ();
}
}
private void ActiveToggled (object sender, ToggledArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
bool val = (bool) store.GetValue (iter, colActiveIndex);
store.SetValue (iter, colActiveIndex, !val);
EmitContentChanged ();
}
}
private void CommentEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
store.SetValue (iter, colCommentIndex, args.NewText);
EmitContentChanged ();
}
}
public virtual bool ValidateSchemaObjects (out string msg)
{
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
string name = store.GetValue (iter, colNameIndex) as string;
string source = store.GetValue (iter, colSourceIndex) as string;
//type, event, firetype, position and fireType are always valid
if (String.IsNullOrEmpty (source)) {
msg = AddinCatalog.GetString ("Trigger '{0}' does not contain a trigger statement.", name);
return false;
}
} while (store.IterNext (ref iter));
}
msg = null;
return true;
}
public virtual void FillSchemaObjects ()
{
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
TriggerSchema trigger = store.GetValue (iter, colObjIndex) as TriggerSchema;
trigger.Name = store.GetValue (iter, colNameIndex) as string;
trigger.TriggerType = (TriggerType)Enum.Parse (typeof (TriggerType), store.GetValue (iter, colTypeIndex) as string);
trigger.TriggerEvent = (TriggerEvent)Enum.Parse (typeof (TriggerEvent), store.GetValue (iter, colEventIndex) as string);
if (Convert.ToBoolean(store.GetValue (iter, colFireTypeIndex)))
trigger.TriggerFireType = TriggerFireType.ForEachRow;
else
trigger.TriggerFireType = TriggerFireType.ForEachStatement;
trigger.Position = int.Parse (store.GetValue (iter, colPositionIndex) as string);
trigger.IsActive = (bool)store.GetValue (iter, colActiveIndex);
trigger.Comment = store.GetValue (iter, colCommentIndex) as string;
trigger.Source = store.GetValue (iter, colSourceIndex) as string;
table.Triggers.Add (trigger);
} while (store.IterNext (ref iter));
}
}
protected virtual void EmitContentChanged ()
{
if (ContentChanged != null)
ContentChanged (this, EventArgs.Empty);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Collections.Generic;
using System.Text;
using NPOI.HSSF.Record.Cont;
using NPOI.Util;
/**
* Title: Unicode String<p/>
* Description: Unicode String - just standard fields that are in several records.
* It is considered more desirable then repeating it in all of them.<p/>
* This is often called a XLUnicodeRichExtendedString in MS documentation.<p/>
* REFERENCE: PG 264 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<p/>
* REFERENCE: PG 951 Excel Binary File Format (.xls) Structure Specification v20091214
*/
public class UnicodeString : IComparable<UnicodeString>
{ // TODO - make this when the compatibility version is Removed
private static POILogger _logger = POILogFactory.GetLogger(typeof(UnicodeString));
private short field_1_charCount;
private byte field_2_optionflags;
private String field_3_string;
private List<FormatRun> field_4_format_runs;
private ExtRst field_5_ext_rst;
private static BitField highByte = BitFieldFactory.GetInstance(0x1);
// 0x2 is reserved
private static BitField extBit = BitFieldFactory.GetInstance(0x4);
private static BitField richText = BitFieldFactory.GetInstance(0x8);
public class FormatRun : IComparable<FormatRun>
{
internal short _character;
internal short _fontIndex;
public FormatRun(short character, short fontIndex)
{
this._character = character;
this._fontIndex = fontIndex;
}
public FormatRun(ILittleEndianInput in1) :
this(in1.ReadShort(), in1.ReadShort())
{
}
public short CharacterPos
{
get
{
return _character;
}
}
public short FontIndex
{
get
{
return _fontIndex;
}
}
public override bool Equals(Object o)
{
if (!(o is FormatRun))
{
return false;
}
FormatRun other = (FormatRun)o;
return _character == other._character && _fontIndex == other._fontIndex;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public int CompareTo(FormatRun r)
{
if (_character == r._character && _fontIndex == r._fontIndex)
{
return 0;
}
if (_character == r._character)
{
return _fontIndex - r._fontIndex;
}
return _character - r._character;
}
public override String ToString()
{
return "character=" + _character + ",fontIndex=" + _fontIndex;
}
public void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(_character);
out1.WriteShort(_fontIndex);
}
}
// See page 681
public class ExtRst : IComparable<ExtRst>
{
private short reserved;
// This is a Phs (see page 881)
private short formattingFontIndex;
private short formattingOptions;
// This is a RPHSSub (see page 894)
private int numberOfRuns;
private String phoneticText;
// This is an array of PhRuns (see page 881)
private PhRun[] phRuns;
// Sometimes there's some cruft at the end
private byte[] extraData;
private void populateEmpty()
{
reserved = 1;
phoneticText = "";
phRuns = new PhRun[0];
extraData = new byte[0];
}
public override int GetHashCode()
{
int hash = reserved;
hash = 31 * hash + formattingFontIndex;
hash = 31 * hash + formattingOptions;
hash = 31 * hash + numberOfRuns;
hash = 31 * hash + phoneticText.GetHashCode();
if (phRuns != null)
{
foreach (PhRun ph in phRuns)
{
hash = 31 * hash + ph.phoneticTextFirstCharacterOffset;
hash = 31 * hash + ph.realTextFirstCharacterOffset;
hash = 31 * hash + ph.realTextLength;
}
}
return hash;
}
internal ExtRst()
{
populateEmpty();
}
internal ExtRst(ILittleEndianInput in1, int expectedLength)
{
reserved = in1.ReadShort();
// Old style detection (Reserved = 0xFF)
if (reserved == -1)
{
populateEmpty();
return;
}
// Spot corrupt records
if (reserved != 1)
{
_logger.Log(POILogger.WARN, "Warning - ExtRst has wrong magic marker, expecting 1 but found " + reserved + " - ignoring");
// Grab all the remaining data, and ignore it
for (int i = 0; i < expectedLength - 2; i++)
{
in1.ReadByte();
}
// And make us be empty
populateEmpty();
return;
}
// Carry on Reading in as normal
short stringDataSize = in1.ReadShort();
formattingFontIndex = in1.ReadShort();
formattingOptions = in1.ReadShort();
// RPHSSub
numberOfRuns = in1.ReadUShort();
short length1 = in1.ReadShort();
// No really. Someone Clearly forgot to read
// the docs on their datastructure...
short length2 = in1.ReadShort();
// And sometimes they write out garbage :(
if (length1 == 0 && length2 > 0)
{
length2 = 0;
}
if (length1 != length2)
{
throw new InvalidOperationException(
"The two length fields of the Phonetic Text don't agree! " +
length1 + " vs " + length2
);
}
phoneticText = StringUtil.ReadUnicodeLE(in1, length1);
int RunData = stringDataSize - 4 - 6 - (2 * phoneticText.Length);
int numRuns = (RunData / 6);
phRuns = new PhRun[numRuns];
for (int i = 0; i < phRuns.Length; i++)
{
phRuns[i] = new PhRun(in1);
}
int extraDataLength = RunData - (numRuns * 6);
if (extraDataLength < 0)
{
//System.err.Println("Warning - ExtRst overran by " + (0-extraDataLength) + " bytes");
extraDataLength = 0;
}
extraData = new byte[extraDataLength];
for (int i = 0; i < extraData.Length; i++)
{
extraData[i] = (byte)in1.ReadByte();
}
}
/**
* Returns our size, excluding our
* 4 byte header
*/
internal int DataSize
{
get
{
return 4 + 6 + (2 * phoneticText.Length) +
(6 * phRuns.Length) + extraData.Length;
}
}
internal void Serialize(ContinuableRecordOutput out1)
{
int dataSize = DataSize;
out1.WriteContinueIfRequired(8);
out1.WriteShort(reserved);
out1.WriteShort(dataSize);
out1.WriteShort(formattingFontIndex);
out1.WriteShort(formattingOptions);
out1.WriteContinueIfRequired(6);
out1.WriteShort(numberOfRuns);
out1.WriteShort(phoneticText.Length);
out1.WriteShort(phoneticText.Length);
out1.WriteContinueIfRequired(phoneticText.Length * 2);
StringUtil.PutUnicodeLE(phoneticText, out1);
for (int i = 0; i < phRuns.Length; i++)
{
phRuns[i].Serialize(out1);
}
out1.Write(extraData);
}
public override bool Equals(Object obj)
{
if (!(obj is ExtRst))
{
return false;
}
ExtRst other = (ExtRst)obj;
return (CompareTo(other) == 0);
}
public override string ToString()
{
return base.ToString();
}
public int CompareTo(ExtRst o)
{
int result;
result = reserved - o.reserved;
if (result != 0) return result;
result = formattingFontIndex - o.formattingFontIndex;
if (result != 0) return result;
result = formattingOptions - o.formattingOptions;
if (result != 0) return result;
result = numberOfRuns - o.numberOfRuns;
if (result != 0) return result;
//result = phoneticText.CompareTo(o.phoneticText);
result = string.Compare(phoneticText, o.phoneticText, StringComparison.CurrentCulture);
if (result != 0) return result;
result = phRuns.Length - o.phRuns.Length;
if (result != 0) return result;
for (int i = 0; i < phRuns.Length; i++)
{
result = phRuns[i].phoneticTextFirstCharacterOffset - o.phRuns[i].phoneticTextFirstCharacterOffset;
if (result != 0) return result;
result = phRuns[i].realTextFirstCharacterOffset - o.phRuns[i].realTextFirstCharacterOffset;
if (result != 0) return result;
result = phRuns[i].realTextLength - o.phRuns[i].realTextLength;
if (result != 0) return result;
}
result = Arrays.HashCode(extraData) - Arrays.HashCode(o.extraData);
// If we Get here, it's the same
return result;
}
internal ExtRst Clone()
{
ExtRst ext = new ExtRst();
ext.reserved = reserved;
ext.formattingFontIndex = formattingFontIndex;
ext.formattingOptions = formattingOptions;
ext.numberOfRuns = numberOfRuns;
ext.phoneticText = phoneticText;
ext.phRuns = new PhRun[phRuns.Length];
for (int i = 0; i < ext.phRuns.Length; i++)
{
ext.phRuns[i] = new PhRun(
phRuns[i].phoneticTextFirstCharacterOffset,
phRuns[i].realTextFirstCharacterOffset,
phRuns[i].realTextLength
);
}
return ext;
}
public short FormattingFontIndex
{
get
{
return formattingFontIndex;
}
}
public short FormattingOptions
{
get
{
return formattingOptions;
}
}
public int NumberOfRuns
{
get
{
return numberOfRuns;
}
}
public String PhoneticText
{
get
{
return phoneticText;
}
}
public PhRun[] PhRuns
{
get
{
return phRuns;
}
}
}
public class PhRun
{
internal int phoneticTextFirstCharacterOffset;
internal int realTextFirstCharacterOffset;
internal int realTextLength;
public PhRun(int phoneticTextFirstCharacterOffset,
int realTextFirstCharacterOffset, int realTextLength)
{
this.phoneticTextFirstCharacterOffset = phoneticTextFirstCharacterOffset;
this.realTextFirstCharacterOffset = realTextFirstCharacterOffset;
this.realTextLength = realTextLength;
}
internal PhRun(ILittleEndianInput in1)
{
phoneticTextFirstCharacterOffset = in1.ReadUShort();
realTextFirstCharacterOffset = in1.ReadUShort();
realTextLength = in1.ReadUShort();
}
internal void Serialize(ContinuableRecordOutput out1)
{
out1.WriteContinueIfRequired(6);
out1.WriteShort(phoneticTextFirstCharacterOffset);
out1.WriteShort(realTextFirstCharacterOffset);
out1.WriteShort(realTextLength);
}
}
private UnicodeString()
{
//Used for clone method.
}
public UnicodeString(String str)
{
String = (str);
}
public override int GetHashCode()
{
int stringHash = 0;
if (field_3_string != null)
stringHash = field_3_string.GetHashCode();
return field_1_charCount + stringHash;
}
/**
* Our handling of Equals is inconsistent with CompareTo. The trouble is because we don't truely understand
* rich text fields yet it's difficult to make a sound comparison.
*
* @param o The object to Compare.
* @return true if the object is actually Equal.
*/
public override bool Equals(Object o)
{
if (!(o is UnicodeString))
{
return false;
}
UnicodeString other = (UnicodeString)o;
//OK lets do this in stages to return a quickly, first check the actual string
if (field_1_charCount != other.field_1_charCount
|| field_2_optionflags != other.field_2_optionflags
|| !field_3_string.Equals(other.field_3_string))
{
return false;
}
//OK string appears to be equal but now lets compare formatting Runs
if (field_4_format_runs == null)
{
// Strings are equal, and there are not formatting runs.
return (other.field_4_format_runs == null);
}
else if (other.field_4_format_runs == null)
{
// Strings are equal, but one or the other has formatting runs
return false;
}
//Strings are Equal, so now compare formatting Runs.
int size = field_4_format_runs.Count;
if (size != other.field_4_format_runs.Count)
return false;
for (int i = 0; i < size; i++)
{
FormatRun Run1 = field_4_format_runs[(i)];
FormatRun run2 = other.field_4_format_runs[(i)];
if (!Run1.Equals(run2))
return false;
}
// Well the format Runs are equal as well!, better check the ExtRst data
if (field_5_ext_rst == null)
{
return (other.field_5_ext_rst == null);
}
else if (other.field_5_ext_rst == null)
{
return false;
}
return field_5_ext_rst.Equals(other.field_5_ext_rst);
}
/**
* construct a unicode string record and fill its fields, ID is ignored
* @param in the RecordInputstream to read the record from
*/
public UnicodeString(RecordInputStream in1)
{
field_1_charCount = in1.ReadShort();
field_2_optionflags = (byte)in1.ReadByte();
int RunCount = 0;
int extensionLength = 0;
//Read the number of rich Runs if rich text.
if (IsRichText)
{
RunCount = in1.ReadShort();
}
//Read the size of extended data if present.
if (IsExtendedText)
{
extensionLength = in1.ReadInt();
}
bool isCompressed = ((field_2_optionflags & 1) == 0);
int cc = CharCount;
field_3_string = (isCompressed) ? in1.ReadCompressedUnicode(cc) : in1.ReadUnicodeLEString(cc);
if (IsRichText && (RunCount > 0))
{
field_4_format_runs = new List<FormatRun>(RunCount);
for (int i = 0; i < RunCount; i++)
{
field_4_format_runs.Add(new FormatRun(in1));
}
}
if (IsExtendedText && (extensionLength > 0))
{
field_5_ext_rst = new ExtRst(new ContinuableRecordInput(in1), extensionLength);
if (field_5_ext_rst.DataSize + 4 != extensionLength)
{
_logger.Log(POILogger.WARN, "ExtRst was supposed to be " + extensionLength + " bytes long, but seems to actually be " + (field_5_ext_rst.DataSize + 4));
}
}
}
/**
* get the number of characters in the string,
* as an un-wrapped int
*
* @return number of characters
*/
public int CharCount
{
get
{
if (field_1_charCount < 0)
{
return field_1_charCount + 65536;
}
return field_1_charCount;
}
set
{
field_1_charCount = (short)value;
}
}
public short CharCountShort
{
get { return field_1_charCount; }
}
/**
* Get the option flags which among other things return if this is a 16-bit or
* 8 bit string
*
* @return optionflags bitmask
*
*/
public byte OptionFlags
{
get
{
return field_2_optionflags;
}
set
{
field_2_optionflags = value;
}
}
/**
* @return the actual string this Contains as a java String object
*/
public String String
{
get
{
return field_3_string;
}
set
{
field_3_string = value;
CharCount = ((short)field_3_string.Length);
// scan for characters greater than 255 ... if any are
// present, we have to use 16-bit encoding. Otherwise, we
// can use 8-bit encoding
bool useUTF16 = false;
int strlen = value.Length;
for (int j = 0; j < strlen; j++)
{
if (value[j] > 255)
{
useUTF16 = true;
break;
}
}
if (useUTF16)
//Set the uncompressed bit
field_2_optionflags = highByte.SetByte(field_2_optionflags);
else
field_2_optionflags = highByte.ClearByte(field_2_optionflags);
}
}
public int FormatRunCount
{
get
{
return (field_4_format_runs == null) ? 0: field_4_format_runs.Count;
}
}
public FormatRun GetFormatRun(int index)
{
if (field_4_format_runs == null)
{
return null;
}
if (index < 0 || index >= field_4_format_runs.Count)
{
return null;
}
return field_4_format_runs[(index)];
}
private int FindFormatRunAt(int characterPos)
{
int size = field_4_format_runs.Count;
for (int i = 0; i < size; i++)
{
FormatRun r = field_4_format_runs[(i)];
if (r._character == characterPos)
return i;
else if (r._character > characterPos)
return -1;
}
return -1;
}
/** Adds a font run to the formatted string.
*
* If a font run exists at the current charcter location, then it is
* Replaced with the font run to be Added.
*/
public void AddFormatRun(FormatRun r)
{
if (field_4_format_runs == null)
{
field_4_format_runs = new List<FormatRun>();
}
int index = FindFormatRunAt(r._character);
if (index != -1)
field_4_format_runs.RemoveAt(index);
field_4_format_runs.Add(r);
//Need to sort the font Runs to ensure that the font Runs appear in
//character order
//collections.Sort(field_4_format_Runs);
field_4_format_runs.Sort();
//Make sure that we now say that we are a rich string
field_2_optionflags = richText.SetByte(field_2_optionflags);
}
public List<FormatRun> FormatIterator()
{
if (field_4_format_runs != null)
{
return field_4_format_runs;
}
return null;
}
public void RemoveFormatRun(FormatRun r)
{
field_4_format_runs.Remove(r);
if (field_4_format_runs.Count == 0)
{
field_4_format_runs = null;
field_2_optionflags = richText.ClearByte(field_2_optionflags);
}
}
public void ClearFormatting()
{
field_4_format_runs = null;
field_2_optionflags = richText.ClearByte(field_2_optionflags);
}
public ExtRst ExtendedRst
{
get
{
return this.field_5_ext_rst;
}
set
{
if (value != null)
{
field_2_optionflags = extBit.SetByte(field_2_optionflags);
}
else
{
field_2_optionflags = extBit.ClearByte(field_2_optionflags);
}
this.field_5_ext_rst = value;
}
}
/**
* Swaps all use in the string of one font index
* for use of a different font index.
* Normally only called when fonts have been
* Removed / re-ordered
*/
public void SwapFontUse(short oldFontIndex, short newFontIndex)
{
foreach (FormatRun run in field_4_format_runs)
{
if (run._fontIndex == oldFontIndex)
{
run._fontIndex = newFontIndex;
}
}
}
/**
* unlike the real records we return the same as "getString()" rather than debug info
* @see #getDebugInfo()
* @return String value of the record
*/
public override String ToString()
{
return String;
}
/**
* return a character representation of the fields of this record
*
*
* @return String of output for biffviewer etc.
*
*/
public String GetDebugInfo()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[UNICODESTRING]\n");
buffer.Append(" .charcount = ")
.Append(StringUtil.ToHexString(CharCount)).Append("\n");
buffer.Append(" .optionflags = ")
.Append(StringUtil.ToHexString(OptionFlags)).Append("\n");
buffer.Append(" .string = ").Append(String).Append("\n");
if (field_4_format_runs != null)
{
for (int i = 0; i < field_4_format_runs.Count; i++)
{
FormatRun r = field_4_format_runs[(i)];
buffer.Append(" .format_Run" + i + " = ").Append(r.ToString()).Append("\n");
}
}
if (field_5_ext_rst != null)
{
buffer.Append(" .field_5_ext_rst = ").Append("\n");
buffer.Append(field_5_ext_rst.ToString()).Append("\n");
}
buffer.Append("[/UNICODESTRING]\n");
return buffer.ToString();
}
/**
* Serialises out the String. There are special rules
* about where we can and can't split onto
* Continue records.
*/
public void Serialize(ContinuableRecordOutput out1)
{
int numberOfRichTextRuns = 0;
int extendedDataSize = 0;
if (IsRichText && field_4_format_runs != null)
{
numberOfRichTextRuns = field_4_format_runs.Count;
}
if (IsExtendedText && field_5_ext_rst != null)
{
extendedDataSize = 4 + field_5_ext_rst.DataSize;
}
// Serialise the bulk of the String
// The WriteString handles tricky continue stuff for us
out1.WriteString(field_3_string, numberOfRichTextRuns, extendedDataSize);
if (numberOfRichTextRuns > 0)
{
//This will ensure that a run does not split a continue
for (int i = 0; i < numberOfRichTextRuns; i++)
{
if (out1.AvailableSpace < 4)
{
out1.WriteContinue();
}
FormatRun r = field_4_format_runs[(i)];
r.Serialize(out1);
}
}
if (extendedDataSize > 0)
{
field_5_ext_rst.Serialize(out1);
}
}
public int CompareTo(UnicodeString str)
{
//int result = String.CompareTo(str.String);
int result = string.Compare(String, str.String, StringComparison.CurrentCulture);
//As per the Equals method lets do this in stages
if (result != 0)
return result;
//OK string appears to be equal but now lets compare formatting Runs
if (field_4_format_runs == null)
{
//Strings are equal, and there are no formatting runs. -> 0
//Strings are equal, but one or the other has formatting runs -> 1
return (str.field_4_format_runs == null) ? 0 : 1;
}
else if (str.field_4_format_runs == null)
{
//Strings are equal, but one or the other has formatting runs
return -1;
}
//Strings are Equal, so now compare formatting Runs.
int size = field_4_format_runs.Count;
if (size != str.field_4_format_runs.Count)
return size - str.field_4_format_runs.Count;
for (int i = 0; i < size; i++)
{
FormatRun Run1 = field_4_format_runs[(i)];
FormatRun run2 = str.field_4_format_runs[(i)];
result = Run1.CompareTo(run2);
if (result != 0)
return result;
}
//Well the format Runs are equal as well!, better check the ExtRst data
if (field_5_ext_rst == null)
{
return (str.field_5_ext_rst == null) ? 0 : 1;
}
else if (str.field_5_ext_rst == null)
{
return -1;
}
else
{
return field_5_ext_rst.CompareTo(str.field_5_ext_rst);
}
}
private bool IsRichText
{
get
{
return richText.IsSet(OptionFlags);
}
}
private bool IsExtendedText
{
get
{
return extBit.IsSet(OptionFlags);
}
}
public Object Clone()
{
UnicodeString str = new UnicodeString();
str.field_1_charCount = field_1_charCount;
str.field_2_optionflags = field_2_optionflags;
str.field_3_string = field_3_string;
if (field_4_format_runs != null)
{
str.field_4_format_runs = new List<FormatRun>();
foreach (FormatRun r in field_4_format_runs)
{
str.field_4_format_runs.Add(new FormatRun(r._character, r._fontIndex));
}
}
if (field_5_ext_rst != null)
{
str.field_5_ext_rst = field_5_ext_rst.Clone();
}
return str;
}
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using Azure;
using Azure.Data.Tables.Models;
using Orleans.Clustering.AzureStorage;
using Orleans.TestingHost.Utils;
using Xunit;
namespace Tester.AzureUtils
{
[TestCategory("Azure"), TestCategory("Storage")]
public class AzureTableDataManagerTests : AzureStorageBasicTests
{
private string PartitionKey;
private UnitTestAzureTableDataManager manager;
private UnitTestAzureTableData GenerateNewData()
{
return new UnitTestAzureTableData("JustData", PartitionKey, "RK-" + Guid.NewGuid());
}
public AzureTableDataManagerTests()
{
TestingUtils.ConfigureThreadPoolSettingsForStorageTests();
// Pre-create table, if required
manager = new UnitTestAzureTableDataManager();
PartitionKey = "PK-AzureTableDataManagerTests-" + Guid.NewGuid();
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_CreateTableEntryAsync()
{
var data = GenerateNewData();
await manager.CreateTableEntryAsync(data);
try
{
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.CreateTableEntryAsync(data2);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.Status); // "Creating an already existing entry."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Entity.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpsertTableEntryAsync()
{
var data = GenerateNewData();
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Entity.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.UpsertTableEntryAsync(data2);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Entity.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpdateTableEntryAsync()
{
var data = GenerateNewData();
try
{
await manager.UpdateTableEntryAsync(data, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.Status); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(TableErrorCode.ResourceNotFound.ToString(), restStatus);
}
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Entity.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
string eTag1 = await manager.UpdateTableEntryAsync(data2, AzureTableUtils.ANY_ETAG);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Entity.StringData);
var data3 = data.Clone();
data3.StringData = "EvenNewerData";
_ = await manager.UpdateTableEntryAsync(data3, eTag1);
tuple = await manager.ReadSingleTableEntryAsync(data3.PartitionKey, data3.RowKey);
Assert.Equal(data3.StringData, tuple.Entity.StringData);
try
{
string eTag3 = await manager.UpdateTableEntryAsync(data3.Clone(), eTag1);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.Status); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCode.UpdateConditionNotSatisfied.ToString());
}
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_DeleteTableAsync()
{
var data = GenerateNewData();
try
{
await manager.DeleteTableEntryAsync(data, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.Status); // "Delete before create."
HttpStatusCode httpStatusCode;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out _, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
await manager.DeleteTableEntryAsync(data, eTag1);
try
{
await manager.DeleteTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.Status); // "Deleting an already deleted item."
HttpStatusCode httpStatusCode;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out _, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple.Entity);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_MergeTableAsync()
{
var data = GenerateNewData();
try
{
await manager.MergeTableEntryAsync(data, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.Status); // "Merge before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(TableErrorCode.ResourceNotFound.ToString(), restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.MergeTableEntryAsync(data2, eTag1);
try
{
await manager.MergeTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.Status); // "Wrong eTag."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCode.UpdateConditionNotSatisfied.ToString());
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal("NewData", tuple.Entity.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_ReadSingleTableEntryAsync()
{
var data = GenerateNewData();
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple.Entity);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_InsertTwoTableEntriesConditionallyAsync()
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, AzureTableUtils.ANY_ETAG);
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.Status); // "Upadte item 2 before created it."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(TableErrorCode.ResourceNotFound.ToString(), restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), tuple.Item2);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.Status); // "Inserting an already existing item 1."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.Status); // "Inserting an already existing item 1 AND wring eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
};
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpdateTwoTableEntriesConditionallyAsync()
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, AzureTableUtils.ANY_ETAG, data2, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Update should have failed since the data has not been created yet");
}
catch (RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.Status); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(TableErrorCode.ResourceNotFound.ToString(), restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple1 = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
_ = await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
Assert.True(false, "Should have thrown RequestFailedException.");
}
catch(RequestFailedException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.Status); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCode.UpdateConditionNotSatisfied.ToString());
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/**
We test this API's functionality comprehensively via Directory.GetFiles(String, String, SearchOption). Here, we concentrate on the following
- vanilla
- parm validation, including non existent dir
- security
**/
using System;
using System.Runtime.CompilerServices;
using System.IO;
using System.Collections.Generic;
using System.Security;
using System.Globalization;
using Xunit;
public class DirectoryInfo_GetFiles_str_so
{
private delegate void ExceptionCode();
private static bool s_pass = true;
[Fact]
public static void RunTest()
{
try
{
String dirName;
DirectoryInfo dirInfo;
String[] expectedFiles;
FileInfo[] files;
List<String> list;
//Scenario 1: Vanilla
try
{
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirInfo = new DirectoryInfo(dirName);
expectedFiles = fileManager.GetAllFiles();
list = new List<String>(expectedFiles);
files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
Eval(files.Length == list.Count, "Err_415mbz! wrong count");
for (int i = 0; i < expectedFiles.Length; i++)
{
if (Eval(list.Contains(files[i].FullName), "Err_287kkm! No file found: {0}", files[i].FullName))
list.Remove(files[i].FullName);
}
if (!Eval(list.Count == 0, "Err_921mhs! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_349t7g! Exception caught in scenario: {0}", ex);
}
//Scenario 3: Parm Validation
try
{
// dir not present and then after creating
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
dirInfo = new DirectoryInfo(dirName);
CheckException<DirectoryNotFoundException>(delegate { files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories); }, "Err_326pgt! worng exception thrown");
// create the dir and then check that we dont cache this info
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirInfo = new DirectoryInfo(dirName);
expectedFiles = fileManager.GetAllFiles();
list = new List<String>(expectedFiles);
files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
Eval(files.Length == list.Count, "Err_948kxt! wrong count");
for (int i = 0; i < expectedFiles.Length; i++)
{
if (Eval(list.Contains(files[i].FullName), "Err_535xaj! No file found: {0}", files[i].FullName))
list.Remove(files[i].FullName);
}
if (!Eval(list.Count == 0, "Err_370pjl! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
CheckException<ArgumentNullException>(delegate { files = dirInfo.GetFiles(null, SearchOption.TopDirectoryOnly); }, "Err_751mwu! worng exception thrown");
CheckException<ArgumentOutOfRangeException>(delegate { files = dirInfo.GetFiles("*.*", (SearchOption)100); }, "Err_589kvu! worng exception thrown - see bug #386545");
CheckException<ArgumentOutOfRangeException>(delegate { files = dirInfo.GetFiles("*.*", (SearchOption)(-1)); }, "Err_359vcj! worng exception thrown - see bug #386545");
String[] invalidValuesForSearch = { "..", @".." + Path.DirectorySeparatorChar };
for (int i = 0; i < invalidValuesForSearch.Length; i++)
{
CheckException<ArgumentException>(delegate { files = dirInfo.GetFiles(invalidValuesForSearch[i], SearchOption.TopDirectoryOnly); }, String.Format("Err_631bwy! worng exception thrown: {1}", i, invalidValuesForSearch[i]));
}
Char[] invalidFileNames = Interop.IsWindows ? Path.GetInvalidFileNameChars() : new[] { '\0' };
for (int i = 0; i < invalidFileNames.Length; i++)
{
switch (invalidFileNames[i])
{
case '\\':
case '/':
CheckException<DirectoryNotFoundException>(delegate { files = dirInfo.GetFiles(String.Format("te{0}st", invalidFileNames[i].ToString()), SearchOption.TopDirectoryOnly); }, String.Format("Err_631bwy_{0}! worng exception thrown: {1} - bug#387196", i, (int)invalidFileNames[i]));
break;
case ':':
//History:
// 1) we assumed that this will work in all non-9x machine
// 2) Then only in XP
// 3) NTFS?
if (Interop.IsWindows && FileSystemDebugInfo.IsCurrentDriveNTFS())
CheckException<IOException>(delegate { files = dirInfo.GetFiles(String.Format("te{0}st", invalidFileNames[i].ToString()), SearchOption.TopDirectoryOnly); }, String.Format("Err_997gqs! worng exception thrown: {1} - bug#387196", i, (int)invalidFileNames[i]));
else
{
try
{
files = dirInfo.GetFiles(String.Format("te{0}st", invalidFileNames[i].ToString()), SearchOption.TopDirectoryOnly);
}
catch (IOException)
{
Console.WriteLine(FileSystemDebugInfo.MachineInfo());
Eval(false, "Err_3947g! Another OS throwing for DI.GetFiles(). modify the above check after confirming the v1.x behavior in that machine");
/**
try
{
DirectoryInfo dirInfo = new DirectoryInfo(".");
FileInfo[] files = dirInfo.GetFiles("te:st");
pass=false;
Console.WriteLine("No exception thrown");
}
catch(IOException){}
catch (Exception ex)
{
pass=false;
Console.WriteLine("Err_723jvl! Different Exception caught in scenario: {0}", ex);
}
**/
}
}
break;
case '*':
case '?':
files = dirInfo.GetFiles(String.Format("te{0}st", invalidFileNames[i].ToString()), SearchOption.TopDirectoryOnly);
break;
default:
CheckException<ArgumentException>(delegate { files = dirInfo.GetFiles(String.Format("te{0}st", invalidFileNames[i].ToString()), SearchOption.TopDirectoryOnly); }, String.Format("Err_036gza! worng exception thrown: {1} - bug#387196", i, (int)invalidFileNames[i]));
break;
}
}
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_006dwq! Exception caught in scenario: {0}", ex);
}
//Scenario for bug #461014 - Getting files/directories of CurrentDirectory of drives are broken
/* Test disabled while porting because it relies on state outside of its working directory not changing over time
try
{
string anotherDrive = IOServices.GetNtfsDriveOtherThanCurrent();
String[] paths = null == anotherDrive ? new String[] { Directory.GetCurrentDirectory() } : new String[] { anotherDrive, Directory.GetCurrentDirectory() };
String path;
for (int i = 0; i < paths.Length; i++)
{
path = paths[i];
if (path.Length > 1)
{
path = path.Substring(0, 2);
FileInfo[] f1 = new DirectoryInfo(Path.GetFullPath(path)).GetFiles();
FileInfo[] f2 = new DirectoryInfo(path).GetFiles();
Eval<int>(f1.Length, f2.Length, "Err_2497gds! wrong value");
for (int j = 0; j < f1.Length; j++)
{
Eval<String>(f1[j].FullName, f2[j].FullName, "Err_03284t! wrong value");
Eval<String>(f1[j].Name, f2[j].Name, "Err_03284t! wrong value");
}
}
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_349t7g! Exception caught in scenario: {0}", ex);
}
*/
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_234rsgf! Uncaught exception in RunTest: {0}", ex);
}
Assert.True(s_pass);
}
private void DeleteFile(String fileName)
{
if (File.Exists(fileName))
File.Delete(fileName);
}
private void DeleteDir(String dirName)
{
if (Directory.Exists(dirName))
Directory.Delete(dirName);
}
//Checks for error
private static bool Eval(bool expression, String msg, params Object[] values)
{
return Eval(expression, String.Format(msg, values));
}
private static bool Eval<T>(T actual, T expected, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return retValue;
}
private static bool Eval(bool expression, String msg)
{
if (!expression)
{
s_pass = false;
Console.WriteLine(msg);
}
return expression;
}
//Checks for a particular type of exception
private static void CheckException<E>(ExceptionCode test, string error)
{
CheckException<E>(test, error, null);
}
//Checks for a particular type of exception and an Exception msg in the English locale
private static void CheckException<E>(ExceptionCode test, string error, String msgExpected)
{
bool exception = false;
try
{
test();
error = String.Format("{0} Exception NOT thrown ", error);
}
catch (Exception e)
{
if (e.GetType() == typeof(E))
{
exception = true;
if (msgExpected != null && System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && e.Message != msgExpected)
{
exception = false;
error = String.Format("{0} Message Different: <{1}>", error, e.Message);
}
}
else
error = String.Format("{0} Exception type: {1}", error, e.GetType().Name);
}
Eval(exception, error);
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Avatar
{
public class AvatarServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAvatarService m_AvatarService;
public AvatarServerPostHandler(IAvatarService service) :
base("POST", "/avatar")
{
m_AvatarService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "getavatar":
return GetAvatar(request);
case "setavatar":
return SetAvatar(request);
case "resetavatar":
return ResetAvatar(request);
case "setitems":
return SetItems(request);
case "removeitems":
return RemoveItems(request);
}
m_log.DebugFormat("[AVATAR HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Debug("[AVATAR HANDLER]: Exception {0}" + e);
}
return FailureResult();
}
byte[] GetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (UUID.TryParse(request["UserID"].ToString(), out user))
{
AvatarData avatar = m_AvatarService.GetAvatar(user);
if (avatar == null)
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
if (avatar == null)
result["result"] = "null";
else
result["result"] = avatar.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
return FailureResult();
}
byte[] SetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
AvatarData avatar = new AvatarData(request);
if (m_AvatarService.SetAvatar(user, avatar))
return SuccessResult();
return FailureResult();
}
byte[] ResetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (m_AvatarService.ResetAvatar(user))
return SuccessResult();
return FailureResult();
}
byte[] SetItems(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
string[] names, values;
if (!request.ContainsKey("UserID") || !request.ContainsKey("Names") || !request.ContainsKey("Values"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (!(request["Names"] is List<string> || request["Values"] is List<string>))
return FailureResult();
List<string> _names = (List<string>)request["Names"];
names = _names.ToArray();
List<string> _values = (List<string>)request["Values"];
values = _values.ToArray();
if (m_AvatarService.SetItems(user, names, values))
return SuccessResult();
return FailureResult();
}
byte[] RemoveItems(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
string[] names;
if (!request.ContainsKey("UserID") || !request.ContainsKey("Names"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (!(request["Names"] is List<string>))
return FailureResult();
List<string> _names = (List<string>)request["Names"];
names = _names.ToArray();
if (m_AvatarService.RemoveItems(user, names))
return SuccessResult();
return FailureResult();
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.XPath;
namespace System.Xml.Xsl.Xslt
{
using FunctionInfo = XPathBuilder.FunctionInfo<QilGenerator.FuncId>;
using T = XmlQueryTypeFactory;
internal partial class QilGenerator : IXPathEnvironment
{
// Everywhere in this code in case of error in the stylesheet we should throw XslLoadException.
// This helper IErrorHelper implementation is used to wrap XmlException's into XslLoadException's.
private readonly struct ThrowErrorHelper : IErrorHelper
{
public void ReportError(string res, params string[] args)
{
Debug.Assert(args == null || args.Length == 0, "Error message must already be composed in res");
throw new XslLoadException(SR.Xml_UserException, res);
}
public void ReportWarning(string res, params string[] args)
{
Debug.Fail("Should never get here");
}
}
// -------------------------------- IXPathEnvironment --------------------------------
// IXPathEnvironment represents static context (namespaces, focus) and most naturaly implemented by QilGenerator itself
// $var current() key()
// */@select or */@test + + +
// template/@match - - +
// key/@match - - -
// key/@use - + -
// number/@count + - +
// number/@from + - +
private bool _allowVariables = true;
private bool _allowCurrent = true;
private bool _allowKey = true;
private void SetEnvironmentFlags(bool allowVariables, bool allowCurrent, bool allowKey)
{
_allowVariables = allowVariables;
_allowCurrent = allowCurrent;
_allowKey = allowKey;
}
XPathQilFactory IXPathEnvironment.Factory { get { return _f; } }
// IXPathEnvironment interface
QilNode IFocus.GetCurrent() { return this.GetCurrentNode(); }
QilNode IFocus.GetPosition() { return this.GetCurrentPosition(); }
QilNode IFocus.GetLast() { return this.GetLastPosition(); }
string IXPathEnvironment.ResolvePrefix(string prefix)
{
return ResolvePrefixThrow(true, prefix);
}
QilNode IXPathEnvironment.ResolveVariable(string prefix, string name)
{
if (!_allowVariables)
{
throw new XslLoadException(SR.Xslt_VariablesNotAllowed);
}
string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
Debug.Assert(ns != null);
// Look up in params and variables of the current scope and all outer ones
QilNode var = _scope.LookupVariable(name, ns);
if (var == null)
{
throw new XslLoadException(SR.Xslt_InvalidVariable, Compiler.ConstructQName(prefix, name));
}
// All Node* parameters are guaranteed to be in document order with no duplicates, so TypeAssert
// this so that optimizer can use this information to avoid redundant sorts and duplicate removal.
XmlQueryType varType = var.XmlType;
if (var.NodeType == QilNodeType.Parameter && varType.IsNode && varType.IsNotRtf && varType.MaybeMany && !varType.IsDod)
{
var = _f.TypeAssert(var, XmlQueryTypeFactory.NodeSDod);
}
return var;
}
// NOTE: DO NOT call QilNode.Clone() while executing this method since fixup nodes cannot be cloned
QilNode IXPathEnvironment.ResolveFunction(string prefix, string name, IList<QilNode> args, IFocus env)
{
Debug.Assert(!args.IsReadOnly, "Writable collection expected");
if (prefix.Length == 0)
{
FunctionInfo func;
if (FunctionTable.TryGetValue(name, out func))
{
func.CastArguments(args, name, _f);
switch (func.id)
{
case FuncId.Current:
if (!_allowCurrent)
{
throw new XslLoadException(SR.Xslt_CurrentNotAllowed);
}
// NOTE: This is the only place where the current node (and not the context node) must be used
return ((IXPathEnvironment)this).GetCurrent();
case FuncId.Key:
if (!_allowKey)
{
throw new XslLoadException(SR.Xslt_KeyNotAllowed);
}
return CompileFnKey(args[0], args[1], env);
case FuncId.Document: return CompileFnDocument(args[0], args.Count > 1 ? args[1] : null);
case FuncId.FormatNumber: return CompileFormatNumber(args[0], args[1], args.Count > 2 ? args[2] : null);
case FuncId.UnparsedEntityUri: return CompileUnparsedEntityUri(args[0]);
case FuncId.GenerateId: return CompileGenerateId(args.Count > 0 ? args[0] : env.GetCurrent());
case FuncId.SystemProperty: return CompileSystemProperty(args[0]);
case FuncId.ElementAvailable: return CompileElementAvailable(args[0]);
case FuncId.FunctionAvailable: return CompileFunctionAvailable(args[0]);
default:
Debug.Fail(func.id + " is present in the function table, but absent from the switch");
return null;
}
}
else
{
throw new XslLoadException(SR.Xslt_UnknownXsltFunction, Compiler.ConstructQName(prefix, name));
}
}
else
{
string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
Debug.Assert(ns != null);
if (ns == XmlReservedNs.NsMsxsl)
{
if (name == "node-set")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return CompileMsNodeSet(args[0]);
}
else if (name == "string-compare")
{
FunctionInfo.CheckArity(/*minArg:*/2, /*maxArg:*/4, name, args.Count);
return _f.InvokeMsStringCompare(
/*x: */_f.ConvertToString(args[0]),
/*y: */_f.ConvertToString(args[1]),
/*lang: */2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty),
/*options:*/3 < args.Count ? _f.ConvertToString(args[3]) : _f.String(string.Empty)
);
}
else if (name == "utc")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsUtc(/*datetime:*/_f.ConvertToString(args[0]));
}
else if (name == "format-date" || name == "format-time")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/3, name, args.Count);
return _f.InvokeMsFormatDateTime(
/*datetime:*/_f.ConvertToString(args[0]),
/*format: */1 < args.Count ? _f.ConvertToString(args[1]) : _f.String(string.Empty),
/*lang: */2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty),
/*isDate: */_f.Boolean(name == "format-date")
);
}
else if (name == "local-name")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsLocalName(_f.ConvertToString(args[0]));
}
else if (name == "namespace-uri")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsNamespaceUri(_f.ConvertToString(args[0]), env.GetCurrent());
}
else if (name == "number")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsNumber(args[0]);
}
}
if (ns == XmlReservedNs.NsExsltCommon)
{
if (name == "node-set")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return CompileMsNodeSet(args[0]);
}
else if (name == "object-type")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return EXslObjectType(args[0]);
}
}
// NOTE: If you add any function here, add it to IsFunctionAvailable as well
// Ensure that all node-set parameters are DocOrderDistinct
for (int i = 0; i < args.Count; i++)
args[i] = _f.SafeDocOrderDistinct(args[i]);
if (_compiler.Settings.EnableScript)
{
XmlExtensionFunction scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, (IErrorHelper)this);
if (scrFunc != null)
{
return GenerateScriptCall(_f.QName(name, ns, prefix), scrFunc, args);
}
}
else
{
if (_compiler.Scripts.ScriptClasses.ContainsKey(ns))
{
ReportWarning(SR.Xslt_ScriptsProhibited);
return _f.Error(_lastScope.SourceLine, SR.Xslt_ScriptsProhibited);
}
}
return _f.XsltInvokeLateBound(_f.QName(name, ns, prefix), args);
}
}
private QilNode GenerateScriptCall(QilName name, XmlExtensionFunction scrFunc, IList<QilNode> args)
{
XmlQueryType xmlTypeFormalArg;
for (int i = 0; i < args.Count; i++)
{
xmlTypeFormalArg = scrFunc.GetXmlArgumentType(i);
switch (xmlTypeFormalArg.TypeCode)
{
case XmlTypeCode.Boolean: args[i] = _f.ConvertToBoolean(args[i]); break;
case XmlTypeCode.Double: args[i] = _f.ConvertToNumber(args[i]); break;
case XmlTypeCode.String: args[i] = _f.ConvertToString(args[i]); break;
case XmlTypeCode.Node: args[i] = xmlTypeFormalArg.IsSingleton ? _f.ConvertToNode(args[i]) : _f.ConvertToNodeSet(args[i]); break;
case XmlTypeCode.Item: break;
default: Debug.Fail("This XmlTypeCode should never be inferred from a Clr type: " + xmlTypeFormalArg.TypeCode); break;
}
}
return _f.XsltInvokeEarlyBound(name, scrFunc.Method, scrFunc.XmlReturnType, args);
}
private string ResolvePrefixThrow(bool ignoreDefaultNs, string prefix)
{
if (ignoreDefaultNs && prefix.Length == 0)
{
return string.Empty;
}
else
{
string ns = _scope.LookupNamespace(prefix);
if (ns == null)
{
if (prefix.Length != 0)
{
throw new XslLoadException(SR.Xslt_InvalidPrefix, prefix);
}
ns = string.Empty;
}
return ns;
}
}
//------------------------------------------------
// XSLT Functions
//------------------------------------------------
public enum FuncId
{
Current,
Document,
Key,
FormatNumber,
UnparsedEntityUri,
GenerateId,
SystemProperty,
ElementAvailable,
FunctionAvailable,
}
private static readonly XmlTypeCode[] s_argFnDocument = { XmlTypeCode.Item, XmlTypeCode.Node };
private static readonly XmlTypeCode[] s_argFnKey = { XmlTypeCode.String, XmlTypeCode.Item };
private static readonly XmlTypeCode[] s_argFnFormatNumber = { XmlTypeCode.Double, XmlTypeCode.String, XmlTypeCode.String };
public static Dictionary<string, FunctionInfo> FunctionTable = CreateFunctionTable();
private static Dictionary<string, FunctionInfo> CreateFunctionTable()
{
Dictionary<string, FunctionInfo> table = new Dictionary<string, FunctionInfo>(16);
table.Add("current", new FunctionInfo(FuncId.Current, 0, 0, null));
table.Add("document", new FunctionInfo(FuncId.Document, 1, 2, s_argFnDocument));
table.Add("key", new FunctionInfo(FuncId.Key, 2, 2, s_argFnKey));
table.Add("format-number", new FunctionInfo(FuncId.FormatNumber, 2, 3, s_argFnFormatNumber));
table.Add("unparsed-entity-uri", new FunctionInfo(FuncId.UnparsedEntityUri, 1, 1, XPathBuilder.argString));
table.Add("generate-id", new FunctionInfo(FuncId.GenerateId, 0, 1, XPathBuilder.argNodeSet));
table.Add("system-property", new FunctionInfo(FuncId.SystemProperty, 1, 1, XPathBuilder.argString));
table.Add("element-available", new FunctionInfo(FuncId.ElementAvailable, 1, 1, XPathBuilder.argString));
table.Add("function-available", new FunctionInfo(FuncId.FunctionAvailable, 1, 1, XPathBuilder.argString));
return table;
}
public static bool IsFunctionAvailable(string localName, string nsUri)
{
if (XPathBuilder.IsFunctionAvailable(localName, nsUri))
{
return true;
}
if (nsUri.Length == 0)
{
return FunctionTable.ContainsKey(localName) && localName != "unparsed-entity-uri";
}
if (nsUri == XmlReservedNs.NsMsxsl)
{
return (
localName == "node-set" ||
localName == "format-date" ||
localName == "format-time" ||
localName == "local-name" ||
localName == "namespace-uri" ||
localName == "number" ||
localName == "string-compare" ||
localName == "utc"
);
}
if (nsUri == XmlReservedNs.NsExsltCommon)
{
return localName == "node-set" || localName == "object-type";
}
return false;
}
public static bool IsElementAvailable(XmlQualifiedName name)
{
if (name.Namespace == XmlReservedNs.NsXslt)
{
string localName = name.Name;
return (
localName == "apply-imports" ||
localName == "apply-templates" ||
localName == "attribute" ||
localName == "call-template" ||
localName == "choose" ||
localName == "comment" ||
localName == "copy" ||
localName == "copy-of" ||
localName == "element" ||
localName == "fallback" ||
localName == "for-each" ||
localName == "if" ||
localName == "message" ||
localName == "number" ||
localName == "processing-instruction" ||
localName == "text" ||
localName == "value-of" ||
localName == "variable"
);
}
// NOTE: msxsl:script is not an "instruction", so we return false for it
return false;
}
private QilNode CompileFnKey(QilNode name, QilNode keys, IFocus env)
{
QilNode result;
QilIterator i, n, k;
if (keys.XmlType.IsNode)
{
if (keys.XmlType.IsSingleton)
{
result = CompileSingleKey(name, _f.ConvertToString(keys), env);
}
else
{
result = _f.Loop(i = _f.For(keys), CompileSingleKey(name, _f.ConvertToString(i), env));
}
}
else if (keys.XmlType.IsAtomicValue)
{
result = CompileSingleKey(name, _f.ConvertToString(keys), env);
}
else
{
result = _f.Loop(n = _f.Let(name), _f.Loop(k = _f.Let(keys),
_f.Conditional(_f.Not(_f.IsType(k, T.AnyAtomicType)),
_f.Loop(i = _f.For(_f.TypeAssert(k, T.NodeS)), CompileSingleKey(n, _f.ConvertToString(i), env)),
CompileSingleKey(n, _f.XsltConvert(k, T.StringX), env)
)
));
}
return _f.DocOrderDistinct(result);
}
private QilNode CompileSingleKey(QilNode name, QilNode key, IFocus env)
{
Debug.Assert(name.XmlType == T.StringX && key.XmlType == T.StringX);
QilNode result;
if (name.NodeType == QilNodeType.LiteralString)
{
string keyName = (QilLiteral)name;
_compiler.ParseQName(keyName, out string prefix, out string local, new ThrowErrorHelper());
string nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
QilName qname = _f.QName(local, nsUri, prefix);
if (!_compiler.Keys.Contains(qname))
{
throw new XslLoadException(SR.Xslt_UndefinedKey, keyName);
}
result = CompileSingleKey(_compiler.Keys[qname], key, env);
}
else
{
if (_generalKey == null)
{
_generalKey = CreateGeneralKeyFunction();
}
QilIterator i = _f.Let(name);
QilNode resolvedName = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
result = _f.Invoke(_generalKey, _f.ActualParameterList(i, resolvedName, key, env.GetCurrent()));
result = _f.Loop(i, result);
}
return result;
}
private QilNode CompileSingleKey(List<Key> defList, QilNode key, IFocus env)
{
Debug.Assert(defList != null && defList.Count > 0);
if (defList.Count == 1)
{
return _f.Invoke(defList[0].Function, _f.ActualParameterList(env.GetCurrent(), key));
}
QilIterator i = _f.Let(key);
QilNode result = _f.Sequence();
foreach (Key keyDef in defList)
{
result.Add(_f.Invoke(keyDef.Function, _f.ActualParameterList(env.GetCurrent(), i)));
}
return _f.Loop(i, result);
}
private QilNode CompileSingleKey(List<Key> defList, QilIterator key, QilIterator context)
{
Debug.Assert(defList != null && defList.Count > 0);
QilList result = _f.BaseFactory.Sequence();
QilNode keyRef = null;
foreach (Key keyDef in defList)
{
keyRef = _f.Invoke(keyDef.Function, _f.ActualParameterList(context, key));
result.Add(keyRef);
}
return defList.Count == 1 ? keyRef : result;
}
private QilFunction CreateGeneralKeyFunction()
{
QilIterator name = _f.Parameter(T.StringX);
QilIterator resolvedName = _f.Parameter(T.QNameX);
QilIterator key = _f.Parameter(T.StringX);
QilIterator context = _f.Parameter(T.NodeNotRtf);
QilNode fdef = _f.Error(SR.Xslt_UndefinedKey, name);
for (int idx = 0; idx < _compiler.Keys.Count; idx++)
{
fdef = _f.Conditional(_f.Eq(resolvedName, _compiler.Keys[idx][0].Name.DeepClone(_f.BaseFactory)),
CompileSingleKey(_compiler.Keys[idx], key, context),
fdef
);
}
QilFunction result = _f.Function(_f.FormalParameterList(name, resolvedName, key, context), fdef, _f.False());
result.DebugName = "key";
_functions.Add(result);
return result;
}
private QilNode CompileFnDocument(QilNode uris, QilNode baseNode)
{
QilNode result;
QilIterator i, j, u;
if (!_compiler.Settings.EnableDocumentFunction)
{
ReportWarning(SR.Xslt_DocumentFuncProhibited);
return _f.Error(_lastScope.SourceLine, SR.Xslt_DocumentFuncProhibited);
}
if (uris.XmlType.IsNode)
{
result = _f.DocOrderDistinct(_f.Loop(i = _f.For(uris),
CompileSingleDocument(_f.ConvertToString(i), baseNode ?? i)
));
}
else if (uris.XmlType.IsAtomicValue)
{
result = CompileSingleDocument(_f.ConvertToString(uris), baseNode);
}
else
{
u = _f.Let(uris);
j = (baseNode != null) ? _f.Let(baseNode) : null;
result = _f.Conditional(_f.Not(_f.IsType(u, T.AnyAtomicType)),
_f.DocOrderDistinct(_f.Loop(i = _f.For(_f.TypeAssert(u, T.NodeS)),
CompileSingleDocument(_f.ConvertToString(i), j ?? i)
)),
CompileSingleDocument(_f.XsltConvert(u, T.StringX), j)
);
result = (baseNode != null) ? _f.Loop(j, result) : result;
result = _f.Loop(u, result);
}
return result;
}
private QilNode CompileSingleDocument(QilNode uri, QilNode baseNode)
{
_f.CheckString(uri);
QilNode baseUri;
if (baseNode == null)
{
baseUri = _f.String(_lastScope.SourceLine.Uri);
}
else
{
_f.CheckNodeSet(baseNode);
if (baseNode.XmlType.IsSingleton)
{
baseUri = _f.InvokeBaseUri(baseNode);
}
else
{
// According to errata E14, it is an error if the second argument node-set is empty
// and the URI reference is relative. We pass an empty string as a baseUri to indicate
// that case.
QilIterator i;
baseUri = _f.StrConcat(_f.Loop(i = _f.FirstNode(baseNode), _f.InvokeBaseUri(i)));
}
}
_f.CheckString(baseUri);
return _f.DataSource(uri, baseUri);
}
private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNode formatName)
{
_f.CheckDouble(value);
_f.CheckString(formatPicture);
XmlQualifiedName resolvedName;
if (formatName == null)
{
resolvedName = new XmlQualifiedName();
// formatName must be non-null in the f.InvokeFormatNumberDynamic() call below
formatName = _f.String(string.Empty);
}
else
{
_f.CheckString(formatName);
if (formatName.NodeType == QilNodeType.LiteralString)
{
resolvedName = ResolveQNameThrow(/*ignoreDefaultNs:*/true, formatName);
}
else
{
resolvedName = null;
}
}
if (resolvedName != null)
{
DecimalFormatDecl format;
if (_compiler.DecimalFormats.Contains(resolvedName))
{
format = _compiler.DecimalFormats[resolvedName];
}
else
{
if (resolvedName != DecimalFormatDecl.Default.Name)
{
throw new XslLoadException(SR.Xslt_NoDecimalFormat, (string)(QilLiteral)formatName);
}
format = DecimalFormatDecl.Default;
}
// If both formatPicture and formatName are literal strings, there is no need to reparse
// formatPicture on every execution of this format-number(). Instead, we create a DecimalFormatter
// object on the first execution, save its index into a global variable, and reuse that object
// on all subsequent executions.
if (formatPicture.NodeType == QilNodeType.LiteralString)
{
QilIterator fmtIdx = _f.Let(_f.InvokeRegisterDecimalFormatter(formatPicture, format));
fmtIdx.DebugName = _f.QName("formatter" + _formatterCnt++, XmlReservedNs.NsXslDebug).ToString();
_gloVars.Add(fmtIdx);
return _f.InvokeFormatNumberStatic(value, fmtIdx);
}
_formatNumberDynamicUsed = true;
QilNode name = _f.QName(resolvedName.Name, resolvedName.Namespace);
return _f.InvokeFormatNumberDynamic(value, formatPicture, name, formatName);
}
else
{
_formatNumberDynamicUsed = true;
QilIterator i = _f.Let(formatName);
QilNode name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
return _f.Loop(i, _f.InvokeFormatNumberDynamic(value, formatPicture, name, i));
}
}
private QilNode CompileUnparsedEntityUri(QilNode n)
{
_f.CheckString(n);
return _f.Error(_lastScope.SourceLine, SR.Xslt_UnsupportedXsltFunction, "unparsed-entity-uri");
}
private QilNode CompileGenerateId(QilNode n)
{
_f.CheckNodeSet(n);
if (n.XmlType.IsSingleton)
{
return _f.XsltGenerateId(n);
}
else
{
QilIterator i;
return _f.StrConcat(_f.Loop(i = _f.FirstNode(n), _f.XsltGenerateId(i)));
}
}
private XmlQualifiedName ResolveQNameThrow(bool ignoreDefaultNs, QilNode qilName)
{
string name = (QilLiteral)qilName;
_compiler.ParseQName(name, out string prefix, out string local, new ThrowErrorHelper());
string nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/ignoreDefaultNs, prefix);
return new XmlQualifiedName(local, nsUri);
}
private QilNode CompileSystemProperty(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name);
if (EvaluateFuncCalls)
{
XPathItem propValue = XsltFunctions.SystemProperty(qname);
if (propValue.ValueType == XsltConvert.StringType)
{
return _f.String(propValue.Value);
}
else
{
Debug.Assert(propValue.ValueType == XsltConvert.DoubleType);
return _f.Double((double)propValue.ValueAsDouble);
}
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, name);
}
return _f.InvokeSystemProperty(name);
}
private QilNode CompileElementAvailable(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/false, name);
if (EvaluateFuncCalls)
{
return _f.Boolean(IsElementAvailable(qname));
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/false, name);
}
return _f.InvokeElementAvailable(name);
}
private QilNode CompileFunctionAvailable(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name);
if (EvaluateFuncCalls)
{
// Script blocks and extension objects cannot implement neither null nor XSLT namespace
if (qname.Namespace.Length == 0 || qname.Namespace == XmlReservedNs.NsXslt)
{
return _f.Boolean(QilGenerator.IsFunctionAvailable(qname.Name, qname.Namespace));
}
// We might precalculate the result for script namespaces as well
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, name);
}
return _f.InvokeFunctionAvailable(name);
}
private QilNode CompileMsNodeSet(QilNode n)
{
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return n;
}
return _f.XsltConvert(n, T.NodeSDod);
}
//------------------------------------------------
// EXSLT Functions
//------------------------------------------------
private QilNode EXslObjectType(QilNode n)
{
if (EvaluateFuncCalls)
{
switch (n.XmlType.TypeCode)
{
case XmlTypeCode.Boolean: return _f.String("boolean");
case XmlTypeCode.Double: return _f.String("number");
case XmlTypeCode.String: return _f.String("string");
default:
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return _f.String("node-set");
}
break;
}
}
return _f.InvokeEXslObjectType(n);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Represents a contiguous region of memory, similar to <see cref="ReadOnlySpan{T}"/>.
/// Unlike <see cref="ReadOnlySpan{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct ReadOnlyMemory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is a pre-pinned array.
// (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
// (else) => Pin() needs to allocate a new GCHandle to pin the object.
private readonly object _object;
private readonly int _index;
private readonly int _length;
internal const int RemoveFlagsBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array)
{
if (array == null)
{
this = default;
return; // returns default
}
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
_object = array;
_index = start;
_length = length;
}
/// <summary>Creates a new memory over the existing object, start, and length. No validation is performed.</summary>
/// <param name="obj">The target object.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(object obj, int start, int length)
{
// No validation performed in release builds; caller must provide any necessary validation.
// 'obj is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert((obj == null) || (typeof(T) == typeof(char) && obj is string) || (obj is T[]) || (obj is MemoryManager<T>));
_object = obj;
_index = start;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) => new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
/// <summary>
/// Returns an empty <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// For <see cref="ReadOnlyMemory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
}
return string.Format("System.ReadOnlyMemory<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#else
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#endif
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'startIndex'
/// </summary>
/// <param name="startIndex">The index at which to begin this slice.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(Index startIndex)
{
int actualIndex = startIndex.GetOffset(_length);
return Slice(actualIndex);
}
/// <summary>
/// Forms a slice out of the given memory using the range start and end indexes.
/// </summary>
/// <param name="range">The range used to slice the memory using its start and end indexes.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(Range range)
{
(int start, int length) = range.GetOffsetAndLength(_length);
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, length);
}
/// <summary>
/// Forms a slice out of the given memory using the range start and end indexes.
/// </summary>
/// <param name="range">The range used to slice the memory using its start and end indexes.</param>
public ReadOnlyMemory<T> this[Range range] => Slice(range);
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref T refToReturn = ref Unsafe.AsRef<T>(null);
int lengthOfUnderlyingSpan = 0;
// Copy this field into a local so that it can't change out from under us mid-operation.
object tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string))
{
// Special-case string since it's the most common for ROM<char>.
refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData());
lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length;
}
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// We know the object is not null, it's not a string, and it is variable-length. The only
// remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[]
// and uint[]). Otherwise somebody used private reflection to set this field, and we're not
// too worried about type safety violations at this point.
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData());
lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length;
}
else
{
// We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>.
// Otherwise somebody used private reflection to set this field, and we're not too worried about
// type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and
// T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no
// constructor or other public API which would allow such a conversion.
Debug.Assert(tmpObject is MemoryManager<T>);
Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan();
refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan);
lengthOfUnderlyingSpan = memoryManagerSpan.Length;
}
// If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior.
// We try to detect this condition and throw an exception, but it's possible that a torn struct might
// appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.
int desiredStartIndex = _index & RemoveFlagsBitMask;
int desiredLength = _length;
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#else
if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#endif
refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}
return new ReadOnlySpan<T>(ref refToReturn, lengthOfUnderlyingSpan);
}
}
/// <summary>
/// Copies the contents of the read-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the readonly-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// <exception cref="System.ArgumentException">
/// An instance with nonprimitive (non-blittable) members cannot be pinned.
/// </exception>
/// </summary>
public unsafe MemoryHandle Pin()
{
// It's possible that the below logic could result in an AV if the struct
// is torn. This is ok since the caller is expecting to use raw pointers,
// and we're not required to keep this as safe as the other Span-based APIs.
object tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject is string s)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
// Array is already pre-pinned
if (_index < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & RemoveFlagsBitMask);
return new MemoryHandle(pointer);
}
else
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index);
return new MemoryHandle(pointer, handle);
}
}
else
{
Debug.Assert(tmpObject is MemoryManager<T>);
return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index);
}
}
return default;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>Determines whether the specified object is equal to the current object.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>Returns the hash code for this <see cref="ReadOnlyMemory{T}"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
// We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
// code is based on object identity and referential equality, not deep equality (as common with string).
return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
}
/// <summary>Gets the state of the memory as individual fields.</summary>
/// <param name="start">The offset.</param>
/// <param name="length">The count.</param>
/// <returns>The object.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal object GetObjectStartLength(out int start, out int length)
{
start = _index;
length = _length;
return _object;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
namespace Thesis {
public class BuildingMesh : DrawableObject
{
/*************** FIELDS ***************/
public readonly Building parent;
public List<Face> faces = new List<Face>();
private int _floorCount = 0;
public int floorCount
{
get { return _floorCount; }
set
{
_floorCount = value;
if (_floorHeight > 0f)
height = _floorHeight * _floorCount;
}
}
private float _floorHeight = 0f;
public float floorHeight
{
get { return _floorHeight; }
set
{
_floorHeight = value;
if (_floorCount > 0)
height = _floorHeight * _floorCount;
}
}
public float height = 0f;
/// <summary>
/// Stores the indexes of faces in sorted order.
/// </summary>
public int[] sortedFaces;
private const float _componentWidthMin = 1.1f;
private const float _componentWidthMax = 1.25f;
private const float _componentSpaceMin = 2f;
private const float _componentSpaceMax = 2.25f;
public float windowHeight;
public float doorHeight;
public float balconyHeight;
public float balconyFloorHeight;
public float balconyFloorWidth;
public float balconyFloorDepth;
public Roof roof;
public RoofBase roofBase;
/*************** CONSTRUCTORS ***************/
public BuildingMesh (Building parent, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
{
this.parent = parent;
name = "neo_building_mesh";
var list = MaterialManager.Instance.GetCollection("mat_walls");
material = list[Random.Range(0, list.Count)];
parent.AddCombinable(material.name, this);
if (parent.floorHeight <= 0f)
floorHeight = Random.Range(3.8f, 4f);
else
floorHeight = parent.floorHeight;
if (parent.floorCount <= 0)
floorCount = Util.RollDice(new float[] {0.15f, 0.7f, 0.15f});
else
floorCount = parent.floorCount;
FindMeshOrigin(p1, p3, p2, p4);
boundaries = new Vector3[8];
boundaries[0] = p1 - meshOrigin;
boundaries[1] = p2 - meshOrigin;
boundaries[2] = p3 - meshOrigin;
boundaries[3] = p4 - meshOrigin;
for (int i = 0; i < 4; ++i)
boundaries[i + 4] = boundaries[i] + height * Vector3.up;
ConstructFaces();
ConstructFaceComponents();
ConstructRoof();
}
public BuildingMesh (Building parent, BuildingLot lot)
{
this.parent = parent;
name = "neo_building_mesh";
var list = MaterialManager.Instance.GetCollection("mat_walls");
material = list[Random.Range(0, list.Count)];
parent.AddCombinable(material.name, this);
if (parent.floorHeight <= 0f)
floorHeight = Random.Range(3.8f, 4f);
else
floorHeight = parent.floorHeight;
if (parent.floorCount <= 0)
floorCount = Util.RollDice(new float[] {0.15f, 0.7f, 0.15f});
else
floorCount = parent.floorCount;
FindMeshOrigin(lot.edges[0].start, lot.edges[2].start,
lot.edges[1].start, lot.edges[3].start);
boundaries = new Vector3[8];
boundaries[0] = lot.edges[0].start - meshOrigin;
boundaries[1] = lot.edges[1].start - meshOrigin;
boundaries[2] = lot.edges[2].start - meshOrigin;
boundaries[3] = lot.edges[3].start - meshOrigin;
for (int i = 0; i < 4; ++i)
boundaries[i + 4] = boundaries[i] + height * Vector3.up;
ConstructFaces(lot);
ConstructFaceComponents();
ConstructRoof();
}
/*************** METHODS ***************/
public void ConstructFaces ()
{
faces.Add(new Face(this, boundaries[0], boundaries[1]));
faces.Add(new Face(this, boundaries[1], boundaries[2]));
faces.Add(new Face(this, boundaries[2], boundaries[3]));
faces.Add(new Face(this, boundaries[3], boundaries[0]));
SortFaces();
}
public void ConstructFaces (BuildingLot lot)
{
faces.Add(new Face(this, boundaries[0], boundaries[1],
lot.freeEdges.Contains(0)));
faces.Add(new Face(this, boundaries[1], boundaries[2],
lot.freeEdges.Contains(1)));
faces.Add(new Face(this, boundaries[2], boundaries[3],
lot.freeEdges.Contains(2)));
faces.Add(new Face(this, boundaries[3], boundaries[0],
lot.freeEdges.Contains(3)));
SortFaces();
}
public void ConstructFaceComponents ()
{
if (parent.windowHeight <= 0f)
windowHeight = Random.Range(1.5f, 1.7f);
else
windowHeight = parent.windowHeight;
if (parent.doorHeight <= 0f)
doorHeight = Random.Range(2.8f, 3f);
else
doorHeight = parent.doorHeight;
if (parent.balconyHeight <= 0f)
if (parent.windowHeight <= 0f)
balconyHeight = windowHeight / 2 + floorHeight / 2.25f;
else
balconyHeight = 0.66f * floorHeight;
else
balconyHeight = parent.balconyHeight;
balconyFloorHeight = 0.2f;
balconyFloorDepth = 1f;
balconyFloorWidth = 0.6f;
float component_width = Random.Range(_componentWidthMin, _componentWidthMax);
float inbetween_space = Random.Range(_componentSpaceMin, _componentSpaceMax);
foreach (Face face in faces)
face.ConstructFaceComponents(component_width, inbetween_space);
}
private void ConstructRoof()
{
roofBase = new RoofBase(this);
if (parent.roofBaseMaterial == null)
{
var list = MaterialManager.Instance.GetCollection("mat_roof_base");
roofBase.material = list[Random.Range(0, list.Count - 1)];
}
else
roofBase.material = parent.roofBaseMaterial;
parent.AddCombinable(roofBase.material.name, roofBase);
int maxcpf = Mathf.Max(faces[0].componentsPerFloor, faces[1].componentsPerFloor);
if (parent.roofType == null)
{
int n = Util.RollDice(new float[] { 0.33f, 0.33f, 0.34f });
if (n == 1)
roof = new FlatRoof(this);
else if (n == 2 && maxcpf <= 3)
roof = new SinglePeakRoof(this);
else
roof = new DoublePeakRoof(this);
}
else
{
var ctors = parent.roofType.GetConstructors(BindingFlags.Instance |
BindingFlags.Public);
roof = (Roof) ctors[0].Invoke(new object[] { this });
}
if (parent.roofMaterial == null)
{
var list = MaterialManager.Instance.GetCollection("mat_roof");
if (roof.GetType().Equals(typeof(FlatRoof)))
roof.material = list[Random.Range(0, 2)];
else
roof.material = list[Random.Range(0, list.Count - 1)];
}
else
roof.material = parent.roofMaterial;
parent.AddCombinable(roof.material.name, roof);
}
public override void FindVertices ()
{
int vert_count = 0;
for (int i = 0; i < 4; ++i)
{
faces[i].FindVertices();
vert_count += faces[i].vertices.Length;
}
vertices = new Vector3[vert_count + 4];
// add roof vertices first
for (int i = 0; i < 4; ++i)
vertices[i] = boundaries[i + 4];
// copy the vertices of the faces to this.vertices
// index starts from 4 because of roof vertices
int index = 4;
for (int i = 0; i < 4; ++i)
{
System.Array.Copy(faces[i].vertices, 0, vertices, index, faces[i].vertices.Length);
index += faces[i].vertices.Length;
}
}
public override void FindTriangles ()
{
int tris_count = 0;
for (int i = 0; i < 4; ++i)
if (faces[i].componentsPerFloor == 0)
tris_count += 2;
else
tris_count += floorCount * (6 * faces[i].componentsPerFloor + 2);
triangles = new int[tris_count * 3];
// triangles index
int trin = 0;
int offset = 4;
for (int face = 0; face < 4; ++face)
{
if (faces[face].componentsPerFloor == 0)
{
triangles[trin++] = offset;
triangles[trin++] = offset + 1;
triangles[trin++] = offset + 2;
triangles[trin++] = offset;
triangles[trin++] = offset + 2;
triangles[trin++] = offset + 3;
}
else
{
for (int floor = 0; floor < floorCount; ++floor)
{
int fixedOffset = offset + faces[face].edgeVerticesCount +
8 * faces[face].componentsPerFloor * floor;
int cpfX6 = 6 * faces[face].componentsPerFloor;
int floorX2 = 2 * floor;
triangles[trin++] = offset + floorX2;
triangles[trin++] = fixedOffset;
triangles[trin++] = offset + floorX2 + 2;
triangles[trin++] = fixedOffset;
triangles[trin++] = fixedOffset + cpfX6;
triangles[trin++] = offset + floorX2 + 2;
// wall between each component
int index = fixedOffset + 1;
for (int i = 1; i < faces[face].componentsPerFloor; ++i)
{
triangles[trin++] = index;
triangles[trin++] = index + 1;
triangles[trin++] = index + cpfX6;
triangles[trin++] = index + 1;
triangles[trin++] = index + cpfX6 + 1;
triangles[trin++] = index + cpfX6;
index += 2;
}
triangles[trin++] = index;
triangles[trin++] = offset + floorX2 + 1;
triangles[trin++] = index + cpfX6;
triangles[trin++] = offset + floorX2 + 1;
triangles[trin++] = offset + floorX2 + 3;
triangles[trin++] = index + cpfX6;
// wall over and under each component
for (int i = 0; i < faces[face].componentsPerFloor; ++i)
{
int extOffset = fixedOffset + (i << 1);
// under
triangles[trin++] = extOffset;
triangles[trin++] = extOffset + 1;
triangles[trin++] = extOffset + 2 * faces[face].componentsPerFloor;
triangles[trin++] = extOffset + 1;
triangles[trin++] = extOffset + 2 * faces[face].componentsPerFloor + 1;
triangles[trin++] = extOffset + 2 * faces[face].componentsPerFloor;
// over
triangles[trin++] = extOffset + 4 * faces[face].componentsPerFloor;
triangles[trin++] = extOffset + 4 * faces[face].componentsPerFloor + 1;
triangles[trin++] = extOffset + cpfX6;
triangles[trin++] = extOffset + 4 * faces[face].componentsPerFloor + 1;
triangles[trin++] = extOffset + cpfX6 + 1;
triangles[trin++] = extOffset + cpfX6;
}
}
}
offset += faces[face].vertices.Length;
}
}
public override void Draw ()
{
base.Draw();
foreach (Face face in faces)
foreach (FaceComponent component in face.faceComponents)
component.Draw();
gameObject.transform.position = meshOrigin;
gameObject.transform.parent = parent.gameObject.transform;
roof.FindVertices();
roof.FindTriangles();
roof.Draw();
roofBase.FindVertices();
roofBase.FindTriangles();
roofBase.Draw();
}
/// <summary>
/// Sorts the faces of the building by width.
/// </summary>
public void SortFaces (bool descending = true)
{
List<KeyValuePair<int, float>> lkv = new List<KeyValuePair<int, float>>();
for (int i = 0; i < faces.Count; ++i)
lkv.Add(new KeyValuePair<int, float>(i, faces[i].width));
if (descending)
lkv.Sort(delegate (KeyValuePair<int, float> x, KeyValuePair<int, float> y)
{
return y.Value.CompareTo(x.Value);
});
else
lkv.Sort(delegate (KeyValuePair<int, float> x, KeyValuePair<int, float> y)
{
return x.Value.CompareTo(y.Value);
});
sortedFaces = new int[lkv.Count];
for (int i = 0; i < lkv.Count; ++i)
sortedFaces[i] = lkv[i].Key;
}
public override void Destroy()
{
base.Destroy();
foreach (Face face in faces)
face.Destroy();
roof.Destroy();
roofBase.Destroy();
}
}
} // namespace Thesis
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CoolFishBotNS.FiniteStateMachine.States;
using CoolFishBotNS.Properties;
using CoolFishNS.Exceptions;
using CoolFishNS.Management;
using CoolFishNS.Management.CoolManager.HookingLua;
using CoolFishNS.Utilities;
using NLog;
namespace CoolFishBotNS.FiniteStateMachine
{
/// <summary>
/// The main driving Engine of the Finite State Machine. This performs all the state running logic.
/// </summary>
public class CoolFishEngine
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly object LockObject = new object();
private readonly SortedSet<State> _states;
private Task _workerTask;
public CoolFishEngine()
{
_states = new SortedSet<State>
{
new StateDoNothing(),
new StateStopOrLogout(),
new StateFish(),
new StateBobbing(),
new StateDoLoot(),
new StateApplyLure(),
new StateUseRaft(),
new StateDoWhisper(),
new StateUseRumsey(),
new StateUseSpear(),
new StateApplyBait()
};
}
/// <summary>
/// True if the Engine is running. False otherwise.
/// </summary>
public bool Running { get; private set; }
#region StatePriority enum
/// <summary>
/// Simple priority list for all the states in our FSM
/// </summary>
public enum StatePriority
{
StateFish = 0,
StateUseRumsey,
StateUseSpear,
StateApplyLure,
StateApplyBait,
StateUseRaft,
StateDoNothing,
StateBobbing,
StateDoLoot,
StateDoWhisper,
StateStopOrLogout
}
#endregion
/// <summary>
/// Starts the engine.
/// </summary>
public void StartEngine()
{
lock (LockObject)
{
if (Running)
{
Logger.Info("The engine is running");
return;
}
Running = true;
_workerTask = Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning);
}
}
/// <summary>
/// Stops the engine.
/// </summary>
public void StopEngine()
{
lock (LockObject)
{
if (!Running)
{
Logger.Info("The engine is stopped");
return;
}
Running = false;
_workerTask = null;
}
}
private void InitOptions()
{
UserPreferences.Default.StopTime = UserPreferences.Default.StopOnTime
? (DateTime?) DateTime.Now.AddMinutes(UserPreferences.Default.MinutesToStop)
: null;
var builder = new StringBuilder();
foreach (SerializableItem serializableItem in UserPreferences.Default.Items.Where(item => !string.IsNullOrWhiteSpace(item.Value)))
{
builder.Append("[\"");
builder.Append(serializableItem.Value);
builder.Append("\"] = true, ");
}
string items = builder.ToString();
if (items.Length > 0)
{
items = items.Remove(items.Length - 2);
}
builder.Clear();
builder.AppendLine("ItemsList = {" + items + "}");
builder.AppendLine("LootLeftOnly = " +
UserPreferences.Default.LootOnlyItems.ToString().ToLower());
builder.AppendLine("DontLootLeft = " +
UserPreferences.Default.DontLootLeft.ToString().ToLower());
builder.AppendLine("LootQuality = " + UserPreferences.Default.LootQuality);
builder.AppendLine(Resources.WhisperNotes);
if (UserPreferences.Default.BaitItem != null)
{
builder.AppendLine("BaitItemId = " + UserPreferences.Default.BaitItem.Value);
builder.AppendLine("BaitSpellId = " + UserPreferences.Default.BaitItem.ValueTwo);
}
builder.AppendLine("LootLog = {}; ");
builder.AppendLine("NoLootLog = {}; ");
DxHook.ExecuteScript(builder.ToString());
}
private void Pulse()
{
foreach (State state in _states)
{
if (!Running || !BotManager.LoggedIn)
{
return;
}
if (state.Run())
{
return;
}
}
}
private void Run()
{
Logger.Info("Started Engine");
try
{
InitOptions();
while (Running && BotManager.LoggedIn)
{
Pulse();
Thread.Sleep(1000/60);
}
if (BotManager.LoggedIn)
{
DxHook.ExecuteScript(
"if CoolFrame then CoolFrame:UnregisterAllEvents(); end print(\"|cff00ff00---Loot Log---\"); for key,value in pairs(LootLog) do local _, itemLink = GetItemInfo(key); print(itemLink .. \": \" .. value) end print(\"|cffff0000---DID NOT Loot Log---\"); for key,value in pairs(NoLootLog) do _, itemLink = GetItemInfo(key); print(itemLink .. \": \" .. value) end");
}
}
catch (CodeInjectionFailedException ex)
{
Logger.Error("Stopping bot because we could not execute code required to continue", (Exception)ex);
}
catch (HookNotAppliedException ex)
{
Logger.Warn("Stopping bot because required hook is no longer applied", (Exception) ex);
}
catch (AccessViolationException ex)
{
Logger.Warn("Stopping bot because we failed to read memory.", (Exception) ex);
}
catch (Exception ex)
{
Logger.Error("Unhandled error occurred. LoggedIn: " + BotManager.LoggedIn + " Attached: " + BotManager.IsAttached, ex);
}
Running = false;
Logger.Info("Engine Stopped");
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
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.Collections.Generic;
using System.ComponentModel;
using DSL.POS.Facade;
using DSL.POS.DTO.DTO;
using DSL.POS.BusinessLogicLayer.Interface;
using DSL.POS.Common.Utility;
using DSL.POS.BusinessLogicLayer.Imp;
public partial class Client_Purchase_PurchaseReturn : System.Web.UI.Page
{
protected DataTable myDt;
Guid guidPurchaseMain_Pk_Code = new Guid();
ClsErrorHandle cls = new ClsErrorHandle();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!Roles.IsUserInRole(ConfigurationManager.AppSettings["purchaseuserrolename"]))
{
Response.Redirect("~/CustomErrorPages/NotAuthorized.aspx");
}
try
{
this.txtGRNNo.Focus();
this.txtGRNNo.Attributes.Add("onkeypress","clickbtn('" + btnClickGRNNo.ClientID+"')");
this.ddlSupplierCode.Attributes.Add("onkeypress", "clickbtn('" + btnClickSupplierCode.ClientID + "')");
this.ddlProductName.Attributes.Add("onkeypress", "clickbtn('" + btnClickPurductName.ClientID + "')");
this.txtRemarks.Attributes.Add("onkeypress", "clickbtn('" + btnAdd.ClientID + "')");
this.txtRefno.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtGRNDate.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtGRNDate.Attributes.Add("onKeyUp", "formatDateField()");
this.txtQuantity.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtQuantity.Attributes.Add("onKeyUp", "Product_Price()");
this.txtDiscoutInd.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtDiscoutInd.Attributes.Add("onKeyUp", "Product_Price()");
this.txtUnitPrice.Attributes.Add("onkeypress", "FocusControl_byEnter()");
//this.txtAmount.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtDeduction.Attributes.Add("onkeypress", "FocusControl_byEnter()");
this.txtReturnAmount.Attributes.Add("onKeyUp", "CalculateNetPayable()");
// fill drop down list
Facade facade = Facade.GetInstance();
DropDownListSupplier(facade);
DropDownListProduct(facade);
// Create a New Table and keep in Session
CreateTableInSession();
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
}
}
/// All Method available here
# region All Method
/// <summary>
/// Create a New Table & Keep in Session
/// </summary>
protected void CreateTableInSession()
{
//Initialize data table
myDt = new DataTable();
//create data table: column, data type, name
myDt = CreateDataTable();
//Keep data table in session
Session["myDatatable"] = myDt;
//Convert data table from session, put data source for grid view
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
//Bind grid
this.GridView1.DataBind();
}
/// <summary>
/// Create data table
/// </summary>
/// <returns>Data table</returns>
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Product Code";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Product Name";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Quantity";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Rate";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Discount";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Total Amount";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Guid");
myDataColumn.ColumnName = "PK";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Remarks";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
/// <summary>
/// Add New Raw in Table
/// </summary>
/// <param name="ProductCode">string</param>
/// <param name="strProductName">string</param>
/// <param name="quantity">string</param>
/// <param name="rate">string</param>
/// <param name="discount">string</param>
/// <param name="Amount">string</param>
/// <param name="P_PK">string</param>
/// <param name="remarks">string</param>
/// <param name="myTable">DataTable</param>
private void AddDataToTable(string ProductCode,
string strProductName,
string quantity,
string rate,
string discount,
string Amount,
string P_PK,
string remarks,
DataTable myTable)
{
try
{
DataRow row;
row = myTable.NewRow();
row["Product Code"] = ProductCode;
row["Product Name"] = strProductName;
row["Quantity"] = quantity;
row["Rate"] = rate;
row["Discount"] = discount;
row["Total Amount"] = (((this.txtUnitPrice.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text)) *
Convert.ToDecimal(quantity)) - (this.txtDiscoutInd.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscoutInd.Text)));
Guid p_pk = new Guid(P_PK);
row["PK"] = p_pk;
row["Remarks"] = remarks;
myTable.Rows.Add(row);
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
}
/// <summary>
/// Update Product rate & discount
/// </summary>
protected void Update_Product()
{
try
{
SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
SqlCommand objCmd = new SqlCommand();
objCmd.CommandText = "Update ProductInfo Set P_CostPrice=@P_CostPrice,P_Discount=@P_Discount,EntryBy=@EntryBy,EntryDate=@EntryDate Where P_PK=@P_PK";
objCmd.Parameters.Add(new SqlParameter("@P_PK", SqlDbType.UniqueIdentifier, 16));
objCmd.Parameters.Add(new SqlParameter("@P_CostPrice", SqlDbType.Decimal, 9));
objCmd.Parameters.Add(new SqlParameter("@P_Discount", SqlDbType.Decimal, 9));
objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 6));
objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime, 8));
Guid productguid = Guid.NewGuid();
productguid = ((Guid)TypeDescriptor.GetConverter(productguid).ConvertFromString(this.ddlProductName.SelectedValue));
objCmd.Parameters["@P_PK"].Value = productguid;
objCmd.Parameters["@P_CostPrice"].Value = this.txtUnitPrice.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text);
objCmd.Parameters["@P_Discount"].Value = this.txtDiscoutInd.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscoutInd.Text);
objCmd.Parameters["@EntryBy"].Value = Convert.ToString(User.Identity.Name);
objCmd.Parameters["@EntryDate"].Value = DateTime.Now.Date;
objCmd.Connection = objMyCon;
objMyCon.Open();
objCmd.ExecuteNonQuery();
objMyCon.Close();
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
finally
{
}
}
/// <summary>
/// Get Data for table when user want to insert new one or update existing one
/// </summary>
protected void Get_Data_In_Table()
{
try
{
int count = 0;
int rowNo = 0;
int totalRows = 0;
if (this.ddlProductName.SelectedValue == "")
{
throw new Exception("Invalid Product Selected.");
}
else if (txtQuantity.Text.Trim() == "")
{
this.lblErrorMessage.Text = "You must fill a Quantity.";
return;
}
else if (txtUnitPrice.Text.Trim() == "")
{
this.lblErrorMessage.Text = "You must fill a Unit Price.";
return;
}
else
{
this.lblErrorMessage.Text = "";
DataTable myDataTable = new DataTable();
myDataTable = ((DataTable)Session["myDatatable"]);
totalRows = myDataTable.Rows.Count;
for (rowNo = 0; rowNo < totalRows; rowNo++)
{
if (this.hfPrimaryKey.Value != "")
{
if (Convert.ToString(this.hfPrimaryKey.Value) == myDataTable.Rows[rowNo][6].ToString())
{
myDataTable.Rows[rowNo][0] = this.hfProductCode.Value.ToString();
myDataTable.Rows[rowNo][1] = this.ddlProductName.SelectedItem.ToString();
myDataTable.Rows[rowNo][2] = this.txtQuantity.Text;
myDataTable.Rows[rowNo][3] = this.txtUnitPrice.Text;
myDataTable.Rows[rowNo][4] = this.txtDiscoutInd.Text;
myDataTable.Rows[rowNo][5] = this.txtAmount.Text;
myDataTable.Rows[rowNo][5] = ((this.txtUnitPrice.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text)) *
(this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text))) -
((this.txtDiscoutInd.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscoutInd.Text)) *
(this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text)));
myDataTable.Rows[rowNo][6] = this.hfPrimaryKey.Value.ToString();
myDataTable.Rows[rowNo][7] = this.txtRemarks.Text;
count = 1;
this.hfPrimaryKey.Value = "";
this.hfProductCode.Value = "";
this.btnAdd.Text = "Add";
break;
}
else
count = 0;
}
else if (this.ddlProductName.SelectedItem.ToString().Trim() == myDataTable.Rows[rowNo][1].ToString())
{
string addQuantity;
decimal totalQuantity = 0;
addQuantity = myDataTable.Rows[rowNo][2].ToString();
totalQuantity = (this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text)) + Convert.ToDecimal(addQuantity);
myDataTable.Rows[rowNo][2] = totalQuantity.ToString();
myDataTable.Rows[rowNo][6] = this.HiddenField1.Value.ToString();
myDataTable.Rows[rowNo][5] = this.txtAmount.Text;
myDataTable.Rows[rowNo][5] = ((this.txtUnitPrice.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text)) *
totalQuantity) - ((this.txtDiscoutInd.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscoutInd.Text)) * totalQuantity);
count = 1;
this.HiddenField1.Value = "";
this.btnAdd.Text = "Add";
break;
}
else
count = 0;
}
if (count == 0)
{
AddDataToTable(this.hfProductCode.Value.ToString(),
this.ddlProductName.SelectedItem.ToString().Trim(),
this.txtQuantity.Text.Trim(),
this.txtUnitPrice.Text.Trim(),
this.txtDiscoutInd.Text.Trim(),
this.txtAmount.Text.Trim(),
this.HiddenField1.Value.ToString(),
this.txtRemarks.Text.Trim(),
(DataTable)Session["myDatatable"]);
}
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
this.GridView1.DataBind();
//clear input texts
this.ddlProductName.SelectedValue = "";
this.txtQuantity.Text = "";
this.txtUnitPrice.Text = "";
this.txtDiscoutInd.Text = "";
this.txtQuantity.Text = "";
this.hfProductCode.Value = "";
this.txtAmount.Text = "";
this.txtRemarks.Text = "";
this.HiddenField1.Value = "";
this.hfPrimaryKey.Value = "";
}
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
finally
{
this.txtGroseTotal.Text = GetTotalAmount().ToString("#####.#0");
this.txtReturnAmount.Text = GetTotalAmount().ToString("#####.#0");
//this.txtTotalDiscount.Focus();
}
}
/// <summary>
/// Get Total Amount all entery product
/// </summary>
/// <returns>decimal</returns>
private decimal GetTotalAmount()
{
decimal totalAmount = 0;
int rowNo = 0;
int totalRows = 0;
DataTable myDataTable = new DataTable();
myDataTable = ((DataTable)Session["myDatatable"]);
totalRows = myDataTable.Rows.Count;
for (rowNo = 0; rowNo < totalRows; rowNo++)
{
totalAmount = totalAmount + Convert.ToDecimal(myDataTable.Rows[rowNo][5]);
}
return totalAmount;
}
# endregion
private void DropDownListSupplier(Facade facade)
{
ISupplierInfoBL oISupplierInfoBL = facade.createSupplierBL();
List<SupplierInfoDTO> oSupplierList = oISupplierInfoBL.showDataSupplierInfo();
int i = 0;
ddlSupplierCode.Items.Clear();
ddlSupplierCode.Items.Add("(Select any Supplier)");
this.ddlSupplierCode.Items[i].Value = "";
foreach (SupplierInfoDTO newDto in oSupplierList)
{
i++;
this.ddlSupplierCode.Items.Add(newDto.SupplierName);
this.ddlSupplierCode.Items[i].Value = newDto.PrimaryKey.ToString();
}
}
private void DropDownListProduct(Facade facade)
{
IProductInfoBL oIProductInfoBL = facade.GetProductInfoInstance();
List<ProductInfoDTO> oCategoryList = oIProductInfoBL.GetProductInfo();
int i = 0;
ddlProductName.Items.Clear();
ddlProductName.Items.Add("(Select any category)");
this.ddlProductName.Items[i].Value = "";
foreach (ProductInfoDTO newDto in oCategoryList)
{
i++;
this.ddlProductName.Items.Add(newDto.P_Name);
this.ddlProductName.Items[i].Value = newDto.PrimaryKey.ToString();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (this.ddlProductName.SelectedValue == "")
{
return;
}
this.Update_Product();
this.Get_Data_In_Table();
}
catch (Exception exp)
{
lblErrorMessage.Text = cls.ErrorString(exp);
}
finally
{
ScriptManager1.SetFocus(ddlProductName);
}
}
/// <summary>
/// Entey Product update or delete
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowEdting(object sender, GridViewCommandEventArgs e)
{
//===========================================================
// under the variable used for Data delele
DataTable myDataTable = new DataTable();
int rowNo = 0;
int totalRows = 0;
//============================================================
try
{
if (e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Facade facade = Facade.GetInstance();
DataKey xx = this.GridView1.DataKeys[index];
this.ddlProductName.SelectedValue = xx.Value.ToString();
this.txtQuantity.Text = Server.HtmlDecode(row.Cells[4].Text);
this.txtUnitPrice.Text = Server.HtmlDecode(row.Cells[5].Text);
this.txtDiscoutInd.Text = Server.HtmlDecode(row.Cells[6].Text);
this.txtAmount.Text = Server.HtmlDecode(row.Cells[7].Text);
this.txtRemarks.Text = Server.HtmlDecode(row.Cells[9].Text);
this.btnAdd.Text = "Update";
this.hfProductCode.Value = Server.HtmlDecode(row.Cells[2].Text);
this.hfPrimaryKey.Value = xx.Value.ToString();
}
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
this.hfPrimaryKey.Value = row.Cells[2].Text;
myDataTable = ((DataTable)Session["myDatatable"]);
totalRows = myDataTable.Rows.Count;
for (rowNo = 0; rowNo < totalRows; rowNo++)
{
if (Convert.ToString(hfPrimaryKey.Value) == (string)myDataTable.Rows[rowNo][0])
{
myDataTable.Rows.RemoveAt(rowNo);
break;
}
}
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
this.GridView1.DataBind();
this.txtGroseTotal.Text = GetTotalAmount().ToString("#####.#0");
this.txtReturnAmount.Text = GetTotalAmount().ToString("#####.#0");
}
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
//LabelDocument lblBarcode = new LabelDocument();
//int intBQty=0 ;
//string strBarCodeVal = "" ;
//string strBarHeading = "";
//LabelField lblFields ;
//LabelField lblField ;
if (this.ddlSupplierCode.SelectedValue == "")
{
this.lblErrorMessage.Text = "Select a Supplier Name";
return;
}
try
{
DataTable myDataTable = new DataTable();
myDataTable = ((DataTable)Session["myDatatable"]);
PurchaseReturnMainDTO dto = populate(myDataTable);
Facade facade = Facade.GetInstance();
IPurchaseReturnInfoBL oIPurchaseReturnInfoBL = facade.createPurchaseReturnBL();
oIPurchaseReturnInfoBL.addNewPurchaseReturnInfo(dto);
lblErrorMessage.Text = "Data Save Successfully.";
this.GridView1.DataBind();
//================Clear All Text Box and Grid View====================
this.hfPrimaryKey.Value = "";
this.hfProductCode.Value = "";
this.HiddenField1.Value = "";
this.hfGRNNo.Value = "";
this.ddlSupplierCode.SelectedValue = "";
this.txtRefno.Text = "";
this.txtGRNDate.Text = "";
this.txtRemarks.Text = "";
this.txtSupplierAddress.Text = "";
this.txtGRNNo.Text = "";
this.txtDeduction.Text = "";
this.txtUnitPrice.Text = "";
this.txtQuantity.Text = "";
this.txtGroseTotal.Text = "";
this.txtReturnAmount.Text = "";
//this.txtPurchaseId.Text = "";
this.txtCurrentBalance.Text = "";
this.txtRemarks.Text = "";
myDataTable.Clear();
myDataTable.Reset();
//myDataTable.Rows.Remove();
this.GridView1.DataSource = myDataTable.DefaultView;
this.GridView1.DataBind();
// Create a New Session and Table
CreateTableInSession();
//====================================================================
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
}
/// <summary>
/// set up Purchase Main and Sub DTO
/// </summary>
/// <returns>PurchaseMainDTO</returns>
public PurchaseReturnMainDTO populate(DataTable myDataTable)
{
PurchaseReturnMainDTO oPurchaseReturnMainDTO = new PurchaseReturnMainDTO();
List<PurchaseReturnSubDTO> lPurchaseReturnSubDTO = new List<PurchaseReturnSubDTO>();
int rowNo = 0;
int totalRows = 0;
try
{
//Guid SupplierP_PK = new Guid(this.hfSupplierPrimaryKey.Value.ToString());
//DataTable myDataTable = new DataTable();
guidPurchaseMain_Pk_Code = Guid.NewGuid();
oPurchaseReturnMainDTO.PrimaryKey = guidPurchaseMain_Pk_Code;
if ((this.hfSupplierPrimaryKey.Value.ToString()) == "")
{
oPurchaseReturnMainDTO.Sp_PK = new Guid("00000000-0000-0000-0000-000000000000");
}
else
oPurchaseReturnMainDTO.Sp_PK = new Guid(this.hfSupplierPrimaryKey.Value.ToString()); ;
if (this.txtGRNNo.Text.Length != 0)
oPurchaseReturnMainDTO.GRN_No = this.txtGRNNo.Text;
else
oPurchaseReturnMainDTO.GRN_No = "";
oPurchaseReturnMainDTO.GRNDate = Convert.ToDateTime(this.txtGRNDate.Text);
oPurchaseReturnMainDTO.ReferenceNo = this.txtRefno.Text;
oPurchaseReturnMainDTO.TotalReturnAmount = Decimal.Parse(this.txtGroseTotal.Text);
if (this.txtDeduction.Text.Length != 0)
oPurchaseReturnMainDTO.PurchaseDeduction = Decimal.Parse(this.txtDeduction.Text);
else
oPurchaseReturnMainDTO.PurchaseDeduction= 0;
//================================Get Data From Table/GridView for SalesSub=====================
//myDataTable = ((DataTable)Session["myDatatable"]);
totalRows = myDataTable.Rows.Count;
// set up in Purchase Sub Info from Data Table.
for (rowNo = 0; rowNo < totalRows; rowNo++)
{
PurchaseReturnSubDTO oPurchaseReturnSubDTO = SetPurchaseReturnSubDTO(rowNo, guidPurchaseMain_Pk_Code, myDataTable);
lPurchaseReturnSubDTO.Add(oPurchaseReturnSubDTO);
}
oPurchaseReturnMainDTO.PurchaseReturnSubDTO = lPurchaseReturnSubDTO;
oPurchaseReturnMainDTO.EntryBy = User.Identity.Name;
//====================================================================================
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
return oPurchaseReturnMainDTO;
}
/// <summary>
/// set up in Purchase Sub DTO
/// </summary>
/// <param name="rowNo">int </param>
/// <param name="guidPurchaseMain_Pk_Code">Guid</param>
/// <param name="myDataTable">DataTable</param>
/// <returns>PurchaseSubDTO</returns>
protected PurchaseReturnSubDTO SetPurchaseReturnSubDTO(int rowNo, Guid guidPurchaseMain_Pk_Code, DataTable myDataTable)
{
PurchaseReturnSubDTO dto = new PurchaseReturnSubDTO();
dto.P_PK = (Guid)myDataTable.Rows[rowNo][6];
dto.PRM_PK = guidPurchaseMain_Pk_Code;
dto.ItemRate = Decimal.Parse(myDataTable.Rows[rowNo][3].ToString());
dto.Notes = this.txtRemarks.Text;
dto.Discount = Decimal.Parse(myDataTable.Rows[rowNo][4].ToString());
dto.Notes = myDataTable.Rows[rowNo][7].ToString();
dto.ReceivedQuantity = Decimal.Parse(myDataTable.Rows[rowNo][2].ToString());
dto.EntryBy = User.Identity.Name;
return dto;
}
/// <summary>
/// Get Supplier Information Corresponding entered Supplier Code in TextBox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnClickSupplierCode_Click(object sender, EventArgs e)
{
try
{
if ((this.lblErrorMessage.Text.Length != 0) || (this.lblSuccessMessage.Text.Length != 0))
{
this.lblSuccessMessage.Text = "";
this.lblErrorMessage.Text = "";
}
SupplierInfoDTO dto = new SupplierInfoDTO();
if (this.ddlSupplierCode.SelectedValue == "")
{
return;
}
Facade facade = Facade.GetInstance();
dto = facade.getSupplierInfo((Guid)TypeDescriptor.GetConverter(dto.PrimaryKey).ConvertFromString(this.ddlSupplierCode.SelectedValue));
//dto = facade.getSupplierInfoByCode(strSupplierCode);
this.hfSupplierPrimaryKey.Value = dto.PrimaryKey.ToString();
if (this.hfSupplierPrimaryKey.Value != "00000000-0000-0000-0000-000000000000")
{
this.ddlSupplierCode.DataTextField = dto.SupplierName;
this.txtSupplierAddress.Text = dto.Address;
}
else
{
this.lblErrorMessage.Text = "Supplier Not Available. Please Insert Correct Supplier ID.";
this.ddlSupplierCode.SelectedValue = "";
//this.txtSupplierName.Text = "";
this.txtSupplierAddress.Text = "";
this.ddlSupplierCode.Focus();
return;
}
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
finally
{
ScriptManager1.SetFocus(txtRefno);
}
}
/// <summary>
/// Get Product Information corresponding Selected Product from Drop Down List
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnClickPurductName_Click(object sender, EventArgs e)
{
try
{
decimal totalAmount = 0;
if ((this.lblErrorMessage.Text.Length != 0) || (this.lblSuccessMessage.Text.Length != 0))
{
this.lblSuccessMessage.Text = "";
this.lblErrorMessage.Text = "";
}
if (this.ddlProductName.SelectedValue == "")
{
return;
}
ProductInfoDTO oProductInfoDTO = new ProductInfoDTO();
Facade facade = Facade.GetInstance();
if (this.ddlProductName.SelectedValue != "")
{
oProductInfoDTO = ProductInfoBLImp.LoadProductInfoDTO((Guid)TypeDescriptor.GetConverter(oProductInfoDTO.PrimaryKey).ConvertFromString(this.ddlProductName.SelectedValue));
this.txtUnitPrice.Text = oProductInfoDTO.P_CostPrice.ToString();
this.txtDiscoutInd.Text = oProductInfoDTO.P_Discount.ToString();
this.hfProductCode.Value = oProductInfoDTO.P_Code;
this.HiddenField1.Value = oProductInfoDTO.PrimaryKey.ToString();
this.txtQuantity.Text = "1";
totalAmount = ((this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text)) *
(this.txtUnitPrice.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text))) -
(this.txtDiscoutInd.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscoutInd.Text));
this.txtAmount.Text = totalAmount.ToString();
}
}
catch (Exception exp)
{
lblErrorMessage.Text = cls.ErrorString(exp);
}
finally
{
ScriptManager1.SetFocus(txtQuantity);
}
}
/// <summary>
/// Get Purchase Information corresponding GRN No.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnClickGRNNo_Click(object sender, EventArgs e)
{
try
{
string strGRNNo = this.txtGRNNo.Text;
if (strGRNNo.Length == 0)
{
return;
}
PurchaseMainDTO dto = new PurchaseMainDTO();
PurchaseReturnMainDTO reDto = new PurchaseReturnMainDTO();
Facade facade = Facade.GetInstance();
reDto = facade.GetPurchaseReturnInfoDTO(strGRNNo);
// set up the member primary code in local declared Hidden field
this.hfGRNNo.Value = reDto.PurchaseMainDTO.PrimaryKey.ToString();
if (this.hfGRNNo.Value != "00000000-0000-0000-0000-000000000000")
{
this.lblErrorMessage.Text = "";
pnlPurchaseRDate.Visible = true;
pnlCurrentBalance.Visible = true;
}
else
{
pnlPurchaseRDate.Visible = false;
pnlCurrentBalance.Visible = false;
this.txtGRNNo.Text = "";
this.lblErrorMessage.Text = "Purchase Not Available. Please Insert Correct GRN No.";
return;
}
string strDate;
this.hfSupplierPrimaryKey.Value = reDto.SupplierInfoDTO.PrimaryKey.ToString();
strDate = Convert.ToString(reDto.PurchaseMainDTO.GRNDate);
this.txtGRNDate.Text = strDate.Substring(0,10);
this.ddlSupplierCode.SelectedValue = reDto.SupplierInfoDTO.PrimaryKey.ToString();
this.txtSupplierAddress.Text = reDto.SupplierInfoDTO.Address;
//this.txtDepositBalance.Text = reDto.MemberInfoDTO.CreditLimit.ToString();
//this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
//this.GridView1.DataBind();
this.txtGRNNo.Focus();
}
catch (Exception Exp)
{
lblErrorMessage.Text = cls.ErrorString(Exp);
}
finally
{
if (this.txtGRNNo.Text.Length != 0)
{
ScriptManager1.SetFocus(ddlProductName);
}
else
{
ScriptManager1.SetFocus(ddlSupplierCode);
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Camera3Animation1
{
Demo demo;
PhysicsScene scene;
string instanceIndexName;
string sphereName;
string cursorName;
string shotName;
Shape sphere;
DemoMouseState oldMouseState;
Vector3 startPosition;
Vector3 step;
int stepCount;
int maxStepCount;
Vector3 position;
Matrix4 rotation;
Matrix4 cameraRotation;
Matrix4 projection;
Matrix4 view;
Vector2 mousePosition;
Vector3 vectorZero;
Matrix4 matrixIdentity;
Quaternion quaternionIdentity;
public Camera3Animation1(Demo demo, int instanceIndex)
{
this.demo = demo;
instanceIndexName = " " + instanceIndex.ToString();
sphereName = "Sphere";
cursorName = "Cursor";
shotName = "Camera 3 Shot" + instanceIndexName + " ";
vectorZero = Vector3.Zero;
matrixIdentity = Matrix4.Identity;
quaternionIdentity = Quaternion.Identity;
}
public void Initialize(PhysicsScene scene)
{
this.scene = scene;
startPosition = Vector3.Zero;
step = Vector3.Zero;
stepCount = 0;
maxStepCount = 0;
}
public void SetControllers(Vector3 objectStep, int objectMaxStepCount)
{
step = objectStep;
maxStepCount = objectMaxStepCount;
sphere = scene.Factory.ShapeManager.Find("Sphere");
stepCount = 0;
oldMouseState = demo.GetMouseState();
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Find("Camera 3" + instanceIndexName);
if (objectBase != null)
{
objectBase.Camera.Active = false;
objectBase.UserControllers.TransformMethods += new SimulateMethod(MoveCursor);
objectBase.UserControllers.PostTransformMethods += new SimulateMethod(Move);
}
}
public void RefreshControllers()
{
stepCount = 0;
oldMouseState = demo.GetMouseState();
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Find("Camera 3" + instanceIndexName);
if (objectBase != null)
objectBase.Camera.Active = false;
}
public void MoveCursor(SimulateMethodArgs args)
{
PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);
if (!objectBase.Camera.Enabled) return;
if (!objectBase.Camera.Active) return;
float time = (float)args.Time;
DemoMouseState mouseState = demo.GetMouseState();
mousePosition.X = mouseState.X;
mousePosition.Y = mouseState.Y;
objectBase.Camera.View.GetViewMatrix(ref view);
objectBase.Camera.Projection.GetProjectionMatrix(ref projection);
ScreenToRayController screenToRayController = objectBase.InternalControllers.ScreenToRayController;
screenToRayController.SetViewport(0, 0, demo.WindowWidth, demo.WindowHeight, 0.0f, 1.0f);
screenToRayController.SetViewMatrix(ref view);
screenToRayController.SetProjectionMatrix(ref projection);
screenToRayController.SetScreenPosition(ref mousePosition);
screenToRayController.MouseButton = true;
screenToRayController.Update();
}
void Move(SimulateMethodArgs args)
{
Vector3 cameraPosition;
PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);
if (!objectBase.Camera.Enabled) return;
if (!objectBase.Camera.Active)
{
objectBase.InitLocalTransform.GetPosition(ref startPosition);
Vector3.Multiply(ref step, stepCount, out cameraPosition);
Vector3.Add(ref cameraPosition, ref startPosition, out cameraPosition);
if (stepCount <= maxStepCount)
{
objectBase.MainWorldTransform.SetPosition(ref cameraPosition);
objectBase.RecalculateMainTransform();
stepCount++;
}
else
objectBase.Camera.Active = true;
}
float time = (float)args.Time;
bool enableShot = false;
DemoMouseState mouseState = demo.GetMouseState();
if (mouseState[MouseButton.Left] && !oldMouseState[MouseButton.Left])
enableShot = true;
mousePosition.X = mouseState.X;
mousePosition.Y = mouseState.Y;
oldMouseState = mouseState;
objectBase.Camera.Projection.CreatePerspectiveLH(1.0f, 11000.0f, 70.0f, demo.WindowWidth, demo.WindowHeight);
objectBase.MainWorldTransform.GetPosition(ref position);
objectBase.Camera.GetTransposeRotation(ref cameraRotation);
objectBase.Camera.View.CreateLookAtLH(ref position, ref cameraRotation, 0.0f);
objectBase.Camera.UpdateFrustum();
objectBase.Camera.View.GetViewMatrix(ref view);
objectBase.Camera.Projection.GetProjectionMatrix(ref projection);
Vector3 rayPosition, rayDirection;
rayPosition = rayDirection = vectorZero;
objectBase.UnProjectToRay(ref mousePosition, 0, 0, demo.WindowWidth, demo.WindowHeight, 0.0f, 1.0f, ref view, ref matrixIdentity, ref projection, ref rayPosition, ref rayDirection);
PhysicsObject cursor = scene.Factory.PhysicsObjectManager.Find(cursorName);
if (cursor != null)
{
Vector3 cursorPosition = vectorZero;
Matrix4 cursorLocalRotation = matrixIdentity;
Matrix4 cursorWorldRotation = matrixIdentity;
cursor.InitLocalTransform.GetPosition(ref cursorPosition);
cursor.InitLocalTransform.GetRotation(ref cursorLocalRotation);
cursor.MainWorldTransform.GetRotation(ref cursorWorldRotation);
objectBase.Camera.GetTransposeRotation(ref cameraRotation);
Matrix4.Mult(ref cursorLocalRotation, ref cameraRotation, out rotation);
Vector3.TransformVector(ref cursorPosition, ref cursorWorldRotation, out position);
cursor.MainWorldTransform.SetRotation(ref rotation);
Vector3.Add(ref position, ref rayPosition, out position);
Vector3.Add(ref position, ref rayDirection, out position);
cursor.MainWorldTransform.SetPosition(ref position);
}
if (enableShot)
{
PhysicsObject shot = scene.Factory.PhysicsObjectManager.Create(shotName + scene.SimulationFrameCount.ToString());
shot.Shape = sphere;
shot.UserDataStr = sphereName;
Vector3 shotScale = vectorZero;
shotScale.X = shotScale.Y = shotScale.Z = 0.5f;
Vector3.Multiply(ref rayDirection, 1000.0f, out rayDirection);
shot.InitLocalTransform.SetRotation(ref matrixIdentity);
shot.InitLocalTransform.SetPosition(ref rayPosition);
shot.InitLocalTransform.SetScale(ref shotScale);
shot.InitLocalTransform.SetLinearVelocity(ref rayDirection);
shot.InitLocalTransform.SetAngularVelocity(ref vectorZero);
shot.Integral.SetDensity(10.0f);
shot.MaxSimulationFrameCount = 10;
shot.EnableCursorInteraction = false;
shot.EnableCollisionResponse = false;
shot.EnableDrawing = false;
shot.EnableCollisions = true;
shot.DisableCollision(objectBase, true);
shot.MaxDisableCollisionFrameCount = 10;
scene.UpdateFromInitLocalTransform(shot);
}
objectBase.Camera.UpdatePhysicsObjects(true, true, true);
objectBase.Camera.SortDrawPhysicsObjects(PhysicsCameraSortOrderType.DrawPriorityShapePrimitiveType);
objectBase.Camera.SortTransparentPhysicsObjects(PhysicsCameraSortOrderType.DrawPriorityShapePrimitiveType);
}
}
}
| |
using System;
using Acr.UserDialogs.Builders;
using Acr.UserDialogs.Fragments;
using Acr.UserDialogs.Infrastructure;
using Android.App;
using Android.Text;
using Android.Views;
using Android.Widget;
using Android.Text.Style;
using AndroidHUD;
#if ANDROIDX
using AndroidX.AppCompat.App;
using Google.Android.Material.Snackbar;
#else
using Android.Support.V7.App;
using Android.Support.Design.Widget;
#endif
namespace Acr.UserDialogs
{
public class UserDialogsImpl : AbstractUserDialogs
{
public static string FragmentTag { get; set; } = "UserDialogs";
protected internal Func<Activity> TopActivityFunc { get; set; }
public UserDialogsImpl(Func<Activity> getTopActivity)
{
this.TopActivityFunc = getTopActivity;
}
#region Alert Dialogs
public override IDisposable Alert(AlertConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
return this.ShowDialog<AlertAppCompatDialogFragment, AlertConfig>(act, config);
return this.Show(activity, () => new AlertBuilder().Build(activity, config));
}
public override IDisposable ActionSheet(ActionSheetConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
{
if (config.UseBottomSheet)
return this.ShowDialog<Fragments.BottomSheetDialogFragment, ActionSheetConfig>(act, config);
return this.ShowDialog<ActionSheetAppCompatDialogFragment, ActionSheetConfig>(act, config);
}
return this.Show(activity, () => new ActionSheetBuilder().Build(activity, config));
}
public override IDisposable Confirm(ConfirmConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
return this.ShowDialog<ConfirmAppCompatDialogFragment, ConfirmConfig>(act, config);
return this.Show(activity, () => new ConfirmBuilder().Build(activity, config));
}
public override IDisposable DatePrompt(DatePromptConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
return this.ShowDialog<DateAppCompatDialogFragment, DatePromptConfig>(act, config);
return this.Show(activity, () => DatePromptBuilder.Build(activity, config));
}
public override IDisposable Login(LoginConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
return this.ShowDialog<LoginAppCompatDialogFragment, LoginConfig>(act, config);
return this.Show(activity, () => new LoginBuilder().Build(activity, config));
}
public override IDisposable Prompt(PromptConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
return this.ShowDialog<PromptAppCompatDialogFragment, PromptConfig>(act, config);
return this.Show(activity, () => new PromptBuilder().Build(activity, config));
}
public override IDisposable TimePrompt(TimePromptConfig config)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity act)
return this.ShowDialog<TimeAppCompatDialogFragment, TimePromptConfig>(act, config);
return this.Show(activity, () => TimePromptBuilder.Build(activity, config));
}
#endregion
#region Toasts
public override IDisposable Toast(ToastConfig cfg)
{
var activity = this.TopActivityFunc();
if (activity is AppCompatActivity compat)
return this.ToastAppCompat(compat, cfg);
return this.ToastFallback(activity, cfg);
}
protected virtual IDisposable ToastAppCompat(AppCompatActivity activity, ToastConfig cfg)
{
Snackbar snackBar = null;
activity.SafeRunOnUi(() =>
{
var view = activity.Window.DecorView.RootView.FindViewById(Android.Resource.Id.Content);
var msg = this.GetSnackbarText(cfg);
snackBar = Snackbar.Make(
view,
msg,
(int)cfg.Duration.TotalMilliseconds
);
if (cfg.BackgroundColor != null)
snackBar.View.SetBackgroundColor(cfg.BackgroundColor.Value.ToNative());
if (cfg.Position == ToastPosition.Top)
{
// watch for this to change in future support lib versions
var layoutParams = snackBar.View.LayoutParameters as FrameLayout.LayoutParams;
if (layoutParams != null)
{
layoutParams.Gravity = GravityFlags.Top;
layoutParams.SetMargins(0, 80, 0, 0);
snackBar.View.LayoutParameters = layoutParams;
}
}
if (cfg.Action != null)
{
snackBar.SetAction(cfg.Action.Text, x =>
{
cfg.Action?.Action?.Invoke();
snackBar.Dismiss();
});
var color = cfg.Action.TextColor;
if (color != null)
snackBar.SetActionTextColor(color.Value.ToNative());
}
snackBar.Show();
});
return new DisposableAction(() =>
{
if (snackBar.IsShown)
activity.SafeRunOnUi(snackBar.Dismiss);
});
}
protected virtual ISpanned GetSnackbarText(ToastConfig cfg)
{
var sb = new SpannableStringBuilder();
string message = cfg.Message;
var hasIcon = (cfg.Icon != null);
if (hasIcon)
message = "\u2002\u2002" + message; // add 2 spaces, 1 for the image the next for spacing between text and image
sb.Append(message);
if (hasIcon)
{
var drawable = ImageLoader.Load(cfg.Icon);
drawable.SetBounds(0, 0, drawable.IntrinsicWidth, drawable.IntrinsicHeight);
sb.SetSpan(new ImageSpan(drawable, SpanAlign.Bottom), 0, 1, SpanTypes.ExclusiveExclusive);
}
if (cfg.MessageTextColor != null)
{
sb.SetSpan(
new ForegroundColorSpan(cfg.MessageTextColor.Value.ToNative()),
0,
sb.Length(),
SpanTypes.ExclusiveExclusive
);
}
return sb;
}
protected virtual string ToHex(System.Drawing.Color color)
{
var red = (int)(color.R * 255);
var green = (int)(color.G * 255);
var blue = (int)(color.B * 255);
//var alpha = (int)(color.A * 255);
//var hex = String.Format($"#{red:X2}{green:X2}{blue:X2}{alpha:X2}");
var hex = String.Format($"#{red:X2}{green:X2}{blue:X2}");
return hex;
}
protected virtual IDisposable ToastFallback(Activity activity, ToastConfig cfg)
{
AndHUD.Shared.ShowToast(
activity,
cfg.Message,
AndroidHUD.MaskType.None,
cfg.Duration,
false,
() =>
{
AndHUD.Shared.Dismiss();
cfg.Action?.Action?.Invoke();
}
);
return new DisposableAction(() =>
{
try
{
AndHUD.Shared.Dismiss(activity);
}
catch
{
}
});
}
#endregion
#region Internals
protected override IProgressDialog CreateDialogInstance(ProgressDialogConfig config)
{
var activity = this.TopActivityFunc();
var dialog = new ProgressDialog(config, activity);
//if (activity != null)
//{
// var frag = new LoadingFragment();
// activity.RunOnUiThread(() =>
// {
// frag.Config = dialog;
// frag.Show(activity.SupportFragmentManager, FragmentTag);
// });
//}
return dialog;
}
protected virtual IDisposable Show(Activity activity, Func<Dialog> dialogBuilder)
{
Dialog dialog = null;
activity.SafeRunOnUi(() =>
{
dialog = dialogBuilder();
dialog.Show();
});
return new DisposableAction(() =>
activity.SafeRunOnUi(dialog.Dismiss)
);
}
protected virtual IDisposable ShowDialog<TFragment, TConfig>(AppCompatActivity activity, TConfig config) where TFragment : AbstractAppCompatDialogFragment<TConfig> where TConfig : class, new()
{
TFragment frag = null;
activity.SafeRunOnUi(() =>
{
frag = (TFragment)Activator.CreateInstance(typeof(TFragment));
frag.Config = config;
frag.Show(activity.SupportFragmentManager, FragmentTag);
});
return new DisposableAction(() =>
activity.SafeRunOnUi(frag.Dismiss)
);
}
#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.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class MutexTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Fact]
public void Ctor_ConstructWaitRelease()
{
using (Mutex m = new Mutex())
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(false))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(true))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
m.ReleaseMutex();
}
}
[Fact]
public void Ctor_InvalidName()
{
AssertExtensions.Throws<ArgumentException>("name", null, () => new Mutex(false, new string('a', 1000)));
}
[Fact]
public void Ctor_ValidName()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Mutex m1 = new Mutex(false, name, out createdNew))
{
Assert.True(createdNew);
using (Mutex m2 = new Mutex(false, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore s = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't create global objects in appcontainer
[SkipOnTargetFramework(
TargetFrameworkMonikers.NetFramework,
"The fix necessary for this test (PR https://github.com/dotnet/coreclr/pull/12381) is not in the .NET Framework.")]
public void Ctor_ImpersonateAnonymousAndTryCreateGlobalMutexTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
if (!ImpersonateAnonymousToken(GetCurrentThread()))
{
// Impersonation is not allowed in the current context, this test is inappropriate in such a case
return;
}
Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N")));
Assert.True(RevertToSelf());
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // Can't create global objects in appcontainer
[PlatformSpecific(TestPlatforms.Windows)]
public void Ctor_TryCreateGlobalMutexTest_Uwp()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N"))));
}
[Fact]
public void OpenExisting()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[Fact]
public void OpenExisting_InvalidNames()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(string.Empty));
AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(new string('a', 10000)));
}
[Fact]
public void OpenExisting_UnavailableName()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore sema = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
}
private static IEnumerable<string> GetNamePrefixes()
{
yield return string.Empty;
yield return "Local\\";
// Creating global sync objects is not allowed in UWP apps
if (!PlatformDetection.IsUap)
{
yield return "Global\\";
}
}
public static IEnumerable<object[]> AbandonExisting_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
for (int waitType = 0; waitType < 2; ++waitType) // 0 == WaitOne, 1 == WaitAny
{
yield return new object[] { null, waitType };
foreach (var namePrefix in GetNamePrefixes())
{
yield return new object[] { namePrefix + nameGuidStr, waitType };
}
}
}
[Theory]
[MemberData(nameof(AbandonExisting_MemberData))]
public void AbandonExisting(string name, int waitType)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
using (var m = new Mutex(false, name))
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
// don't release the mutex; abandon it on this thread
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Assert.True(t.Wait(FailedWaitTimeout));
switch (waitType)
{
case 0: // WaitOne
Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
break;
case 1: // WaitAny
AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
Assert.Equal(0, ame.MutexIndex);
Assert.Equal(m, ame.Mutex);
break;
}
}
});
}
public static IEnumerable<object[]> CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
foreach (var namePrefix in GetNamePrefixes())
{
yield return new object[] { namePrefix + nameGuidStr };
}
}
[Theory]
[MemberData(nameof(CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData))]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
Func<string, string, int> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
mutex.WaitOne();
try
{ File.WriteAllText(f, "0"); }
finally { mutex.ReleaseMutex(); }
IncrementValueInFileNTimes(mutex, f, 10);
}
return SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
using (var remote = RemoteInvoke(otherProcess, mutexName, fileName))
{
SpinWait.SpinUntil(() => File.Exists(fileName));
IncrementValueInFileNTimes(mutex, fileName, 10);
}
Assert.Equal(20, int.Parse(File.ReadAllText(fileName)));
});
}
private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n)
{
for (int i = 0; i < n; i++)
{
mutex.WaitOne();
try
{
int current = int.Parse(File.ReadAllText(fileName));
Thread.Sleep(10);
File.WriteAllText(fileName, (current + 1).ToString());
}
finally { mutex.ReleaseMutex(); }
}
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentThread();
[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ImpersonateAnonymousToken(IntPtr threadHandle);
[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RevertToSelf();
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
// TODO:
// - Plumb status through async APIs to avoid callbacks on synchronous completion
// - NOTE: this will require refactoring in the *Async APIs to accommodate the lack
// of completion posting
// - Add support for unregistering + reregistering for events
// - This will require a new state for each queue, unregistred, to track whether or
// not the queue is currently registered to receive events
// - Audit Close()-related code for the possibility of file descriptor recycling issues
// - It might make sense to change _closeLock to a ReaderWriterLockSlim that is
// acquired for read by all public methods before attempting a completion and
// acquired for write by Close() and HandlEvents()
// - Audit event-related code for the possibility of GCHandle recycling issues
// - There is a potential issue with handle recycling in event loop processing
// if the processing of an event races with the close of a GCHandle
// - It may be necessary for the event loop thread to do all file descriptor
// unregistration in order to avoid this. If so, this would probably happen
// by adding a flag that indicates that the event loop is processing events and
// a queue of contexts to unregister once processing completes.
internal sealed class SocketAsyncContext
{
private abstract class AsyncOperation
{
private enum State
{
Waiting = 0,
Running = 1,
Complete = 2,
Cancelled = 3
}
private int _state; // Actually AsyncOperation.State.
#if DEBUG
private int _callbackQueued; // When non-zero, the callback has been queued.
#endif
public AsyncOperation Next;
protected object CallbackOrEvent;
public SocketError ErrorCode;
public byte[] SocketAddress;
public int SocketAddressLen;
public ManualResetEventSlim Event
{
private get { return (ManualResetEventSlim)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
public AsyncOperation()
{
_state = (int)State.Waiting;
Next = this;
}
public void QueueCompletionCallback()
{
Debug.Assert(!(CallbackOrEvent is ManualResetEventSlim));
Debug.Assert(_state != (int)State.Cancelled);
#if DEBUG
Debug.Assert(Interlocked.CompareExchange(ref _callbackQueued, 1, 0) == 0);
#endif
ThreadPool.QueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(), this);
}
public bool TryComplete(int fileDescriptor)
{
Debug.Assert(_state == (int)State.Waiting);
return DoTryComplete(fileDescriptor);
}
public bool TryCompleteAsync(int fileDescriptor)
{
return TryCompleteOrAbortAsync(fileDescriptor, abort: false);
}
public void AbortAsync()
{
bool completed = TryCompleteOrAbortAsync(fileDescriptor: -1, abort: true);
Debug.Assert(completed);
}
private bool TryCompleteOrAbortAsync(int fileDescriptor, bool abort)
{
int state = Interlocked.CompareExchange(ref _state, (int)State.Running, (int)State.Waiting);
if (state == (int)State.Cancelled)
{
// This operation has been cancelled. The canceller is responsible for
// correctly updating any state that would have been handled by
// AsyncOperation.Abort.
return true;
}
Debug.Assert(state != (int)State.Complete && state != (int)State.Running);
bool completed;
if (abort)
{
Abort();
ErrorCode = SocketError.OperationAborted;
completed = true;
}
else
{
completed = DoTryComplete(fileDescriptor);
}
if (completed)
{
var @event = CallbackOrEvent as ManualResetEventSlim;
if (@event != null)
{
@event.Set();
}
else
{
QueueCompletionCallback();
}
Volatile.Write(ref _state, (int)State.Complete);
return true;
}
Volatile.Write(ref _state, (int)State.Waiting);
return false;
}
public bool Wait(int timeout)
{
if (Event.Wait(timeout))
{
return true;
}
var spinWait = new SpinWait();
for (;;)
{
int state = Interlocked.CompareExchange(ref _state, (int)State.Cancelled, (int)State.Waiting);
switch ((State)state)
{
case State.Running:
// A completion attempt is in progress. Keep busy-waiting.
spinWait.SpinOnce();
break;
case State.Complete:
// A completion attempt succeeded. Consider this operation as having completed within the timeout.
return true;
case State.Waiting:
// This operation was successfully cancelled.
return false;
}
}
}
protected abstract void Abort();
protected abstract bool DoTryComplete(int fileDescriptor);
protected abstract void InvokeCallback();
}
private abstract class TransferOperation : AsyncOperation
{
public byte[] Buffer;
public int Offset;
public int Count;
public int Flags;
public int BytesTransferred;
public int ReceivedFlags;
protected sealed override void Abort() { }
}
private abstract class SendReceiveOperation : TransferOperation
{
public IList<ArraySegment<byte>> Buffers;
public int BufferIndex;
public Action<int, byte[], int, int, SocketError> Callback
{
private get { return (Action<int, byte[], int, int, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected sealed override void InvokeCallback()
{
Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode);
}
}
private sealed class SendOperation : SendReceiveOperation
{
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteSendTo(fileDescriptor, Buffer, Buffers, ref BufferIndex, ref Offset, ref Count, Flags, SocketAddress, SocketAddressLen, ref BytesTransferred, out ErrorCode);
}
}
private sealed class ReceiveOperation : SendReceiveOperation
{
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteReceiveFrom(fileDescriptor, Buffer, Buffers, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode);
}
}
private sealed class ReceiveMessageFromOperation : TransferOperation
{
public bool IsIPv4;
public bool IsIPv6;
public IPPacketInformation IPPacketInformation;
public Action<int, byte[], int, int, IPPacketInformation, SocketError> Callback
{
private get { return (Action<int, byte[], int, int, IPPacketInformation, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteReceiveMessageFrom(fileDescriptor, Buffer, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
}
protected override void InvokeCallback()
{
Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
}
}
private abstract class AcceptOrConnectOperation : AsyncOperation
{
}
private sealed class AcceptOperation : AcceptOrConnectOperation
{
public int AcceptedFileDescriptor;
public Action<int, byte[], int, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override void Abort()
{
AcceptedFileDescriptor = -1;
}
protected override bool DoTryComplete(int fileDescriptor)
{
bool completed = SocketPal.TryCompleteAccept(fileDescriptor, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == -1);
return completed;
}
protected override void InvokeCallback()
{
Callback(AcceptedFileDescriptor, SocketAddress, SocketAddressLen, ErrorCode);
}
}
private sealed class ConnectOperation : AcceptOrConnectOperation
{
public Action<SocketError> Callback
{
private get { return (Action<SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override void Abort() { }
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteConnect(fileDescriptor, SocketAddressLen, out ErrorCode);
}
protected override void InvokeCallback()
{
Callback(ErrorCode);
}
}
private enum QueueState
{
Clear = 0,
Set = 1,
Stopped = 2,
}
private struct OperationQueue<TOperation>
where TOperation : AsyncOperation
{
private AsyncOperation _tail;
public QueueState State { get; set; }
public bool IsStopped { get { return State == QueueState.Stopped; } }
public bool IsEmpty { get { return _tail == null; } }
public TOperation Head
{
get
{
Debug.Assert(!IsStopped);
return (TOperation)_tail.Next;
}
}
public TOperation Tail
{
get
{
return (TOperation)_tail;
}
}
public void Enqueue(TOperation operation)
{
Debug.Assert(!IsStopped);
Debug.Assert(operation.Next == operation);
if (!IsEmpty)
{
operation.Next = _tail.Next;
_tail.Next = operation;
}
_tail = operation;
}
public void Dequeue()
{
Debug.Assert(!IsStopped);
Debug.Assert(!IsEmpty);
AsyncOperation head = _tail.Next;
if (head == _tail)
{
_tail = null;
}
else
{
_tail.Next = head.Next;
}
}
public OperationQueue<TOperation> Stop()
{
OperationQueue<TOperation> result = this;
_tail = null;
State = QueueState.Stopped;
return result;
}
}
private int _fileDescriptor;
private GCHandle _handle;
private OperationQueue<TransferOperation> _receiveQueue;
private OperationQueue<SendOperation> _sendQueue;
private OperationQueue<AcceptOrConnectOperation> _acceptOrConnectQueue;
private SocketAsyncEngine _engine;
private SocketAsyncEvents _registeredEvents;
// These locks are hierarchical: _closeLock must be acquired before _queueLock in order
// to prevent deadlock.
private object _closeLock = new object();
private object _queueLock = new object();
public SocketAsyncContext(int fileDescriptor, SocketAsyncEngine engine)
{
_fileDescriptor = fileDescriptor;
_engine = engine;
}
private void Register(SocketAsyncEvents events)
{
Debug.Assert(Monitor.IsEntered(_queueLock));
Debug.Assert(!_handle.IsAllocated || _registeredEvents != SocketAsyncEvents.None);
Debug.Assert((_registeredEvents & events) == SocketAsyncEvents.None);
if (_registeredEvents == SocketAsyncEvents.None)
{
Debug.Assert(!_handle.IsAllocated);
_handle = GCHandle.Alloc(this, GCHandleType.Normal);
}
events |= _registeredEvents;
Interop.Error errorCode;
if (!_engine.TryRegister(_fileDescriptor, _registeredEvents, events, _handle, out errorCode))
{
if (_registeredEvents == SocketAsyncEvents.None)
{
_handle.Free();
}
// TODO: throw an appropiate exception
throw new Exception(string.Format("SocketAsyncContext.Register: {0}", errorCode));
}
_registeredEvents = events;
}
private void UnregisterRead()
{
Debug.Assert(Monitor.IsEntered(_queueLock));
Debug.Assert((_registeredEvents & SocketAsyncEvents.Read) != SocketAsyncEvents.None);
SocketAsyncEvents events = _registeredEvents & ~SocketAsyncEvents.Read;
if (events == SocketAsyncEvents.None)
{
Unregister();
}
else
{
Interop.Error errorCode;
bool unregistered = _engine.TryRegister(_fileDescriptor, _registeredEvents, events, _handle, out errorCode);
if (unregistered)
{
_registeredEvents = events;
}
else
{
Debug.Fail(string.Format("UnregisterRead failed: {0}", errorCode));
}
}
}
private void Unregister()
{
Debug.Assert(Monitor.IsEntered(_queueLock));
if (_registeredEvents == SocketAsyncEvents.None)
{
Debug.Assert(!_handle.IsAllocated);
return;
}
Interop.Error errorCode;
bool unregistered = _engine.TryRegister(_fileDescriptor, _registeredEvents, SocketAsyncEvents.None, _handle, out errorCode);
_registeredEvents = (SocketAsyncEvents)(-1);
if (unregistered)
{
_registeredEvents = SocketAsyncEvents.None;
_handle.Free();
}
else
{
Debug.Fail(string.Format("Unregister failed: {0}", errorCode));
}
}
private void CloseInner()
{
Debug.Assert(Monitor.IsEntered(_closeLock) && !Monitor.IsEntered(_queueLock));
OperationQueue<AcceptOrConnectOperation> acceptOrConnectQueue;
OperationQueue<SendOperation> sendQueue;
OperationQueue<TransferOperation> receiveQueue;
lock (_queueLock)
{
// Drain queues and unregister events
acceptOrConnectQueue = _acceptOrConnectQueue.Stop();
sendQueue = _sendQueue.Stop();
receiveQueue = _receiveQueue.Stop();
Unregister();
// TODO: assert that queues are all empty if _registeredEvents was SocketAsyncEvents.None?
}
// TODO: the error codes on these operations may need to be changed to account for
// the close. I think Winsock returns OperationAborted in the case that
// the socket for an outstanding operation is closed.
Debug.Assert(!acceptOrConnectQueue.IsStopped || acceptOrConnectQueue.IsEmpty);
while (!acceptOrConnectQueue.IsEmpty)
{
AcceptOrConnectOperation op = acceptOrConnectQueue.Head;
op.AbortAsync();
acceptOrConnectQueue.Dequeue();
}
Debug.Assert(!sendQueue.IsStopped || sendQueue.IsEmpty);
while (!sendQueue.IsEmpty)
{
SendReceiveOperation op = sendQueue.Head;
op.AbortAsync();
sendQueue.Dequeue();
}
Debug.Assert(!receiveQueue.IsStopped || receiveQueue.IsEmpty);
while (!receiveQueue.IsEmpty)
{
TransferOperation op = receiveQueue.Head;
op.AbortAsync();
receiveQueue.Dequeue();
}
}
public void Close()
{
Debug.Assert(!Monitor.IsEntered(_queueLock));
lock (_closeLock)
{
CloseInner();
}
}
private bool TryBeginOperation<TOperation>(ref OperationQueue<TOperation> queue, TOperation operation, SocketAsyncEvents events, out bool isStopped)
where TOperation : AsyncOperation
{
lock (_queueLock)
{
switch (queue.State)
{
case QueueState.Stopped:
isStopped = true;
return false;
case QueueState.Clear:
break;
case QueueState.Set:
isStopped = false;
queue.State = QueueState.Clear;
return false;
}
if ((_registeredEvents & events) == SocketAsyncEvents.None)
{
Register(events);
}
queue.Enqueue(operation);
isStopped = false;
return true;
}
}
private void EndOperation<TOperation>(ref OperationQueue<TOperation> queue)
where TOperation : AsyncOperation
{
lock (_queueLock)
{
Debug.Assert(!queue.IsStopped);
queue.Dequeue();
}
}
public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, int timeout, out int acceptedFd)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(timeout == -1 || timeout > 0);
SocketError errorCode;
if (SocketPal.TryCompleteAccept(_fileDescriptor, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode))
{
Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1);
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new AcceptOperation {
Event = @event,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error reasonable for a closed socket? Check with Winsock.
acceptedFd = -1;
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
acceptedFd = operation.AcceptedFileDescriptor;
return operation.ErrorCode;
}
}
if (!operation.Wait(timeout))
{
acceptedFd = -1;
return SocketError.TimedOut;
}
socketAddressLen = operation.SocketAddressLen;
acceptedFd = operation.AcceptedFileDescriptor;
return operation.ErrorCode;
}
}
public SocketError AcceptAsync(byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketError> callback)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(callback != null);
int acceptedFd;
SocketError errorCode;
if (SocketPal.TryCompleteAccept(_fileDescriptor, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode))
{
Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1);
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketError.Success);
}, Tuple.Create(callback, acceptedFd, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new AcceptOperation {
Callback = callback,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error reasonable for a closed socket? Check with Winsock.
operation.AcceptedFileDescriptor = -1;
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Connect(byte[] socketAddress, int socketAddressLen, int timeout)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(timeout == -1 || timeout > 0);
SocketError errorCode;
if (SocketPal.TryStartConnect(_fileDescriptor, socketAddress, socketAddressLen, out errorCode))
{
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ConnectOperation {
Event = @event,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, SocketAsyncEvents.Write, out isStopped))
{
if (isStopped)
{
// TODO: is this error reasonable for a closed socket? Check with Winsock.
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
return operation.ErrorCode;
}
}
return operation.Wait(timeout) ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ConnectAsync(byte[] socketAddress, int socketAddressLen, Action<SocketError> callback)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(callback != null);
SocketError errorCode;
if (SocketPal.TryStartConnect(_fileDescriptor, socketAddress, socketAddressLen, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(arg => ((Action<SocketError>)arg)(SocketError.Success), callback);
}
return errorCode;
}
var operation = new ConnectOperation {
Callback = callback,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, SocketAsyncEvents.Write, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Receive(byte[] buffer, int offset, int count, ref int flags, int timeout, out int bytesReceived)
{
int socketAddressLen = 0;
return ReceiveFrom(buffer, offset, count, ref flags, null, ref socketAddressLen, timeout, out bytesReceived);
}
public SocketError ReceiveAsync(byte[] buffer, int offset, int count, int flags, Action<int, byte[], int, int, SocketError> callback)
{
return ReceiveFromAsync(buffer, offset, count, flags, null, 0, callback);
}
public SocketError ReceiveFrom(byte[] buffer, int offset, int count, ref int flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0);
int receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ReceiveOperation {
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ReceiveFromAsync(byte[] buffer, int offset, int count, int flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, int, SocketError> callback)
{
int bytesReceived;
int receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, int, SocketError>, int, byte[], int, int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags));
}
return errorCode;
}
var operation = new ReceiveOperation {
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Receive(IList<ArraySegment<byte>> buffers, ref int flags, int timeout, out int bytesReceived)
{
return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived);
}
public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, int flags, Action<int, byte[], int, int, SocketError> callback)
{
return ReceiveFromAsync(buffers, flags, null, 0, callback);
}
public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref int flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0);
int receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ReceiveOperation {
Event = @event,
Buffers = buffers,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, int flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, int, SocketError> callback)
{
int bytesReceived;
int receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, int, SocketError>, int, byte[], int, int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags));
}
return errorCode;
}
var operation = new ReceiveOperation {
Callback = callback,
Buffers = buffers,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError ReceiveMessageFrom(byte[] buffer, int offset, int count, ref int flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0);
int receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveMessageFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ReceiveMessageFromOperation {
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
IsIPv4 = isIPv4,
IsIPv6 = isIPv6,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags,
IPPacketInformation = ipPacketInformation,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ReceiveMessageFromAsync(byte[] buffer, int offset, int count, int flags, byte[] socketAddress, int socketAddressLen, bool isIPv4, bool isIPv6, Action<int, byte[], int, int, IPPacketInformation, SocketError> callback)
{
int bytesReceived;
int receivedFlags;
IPPacketInformation ipPacketInformation;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveMessageFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, int, IPPacketInformation, SocketError>, int, byte[], int, int, IPPacketInformation>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, tup.Item6, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags, ipPacketInformation));
}
return errorCode;
}
var operation = new ReceiveMessageFromOperation {
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
IsIPv4 = isIPv4,
IsIPv6 = isIPv6,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags,
IPPacketInformation = ipPacketInformation,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, SocketAsyncEvents.Read, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Send(byte[] buffer, int offset, int count, int flags, int timeout, out int bytesSent)
{
return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent);
}
public SocketError SendAsync(byte[] buffer, int offset, int count, int flags, Action<int, byte[], int, int, SocketError> callback)
{
return SendToAsync(buffer, offset, count, flags, null, 0, callback);
}
public SocketError SendTo(byte[] buffer, int offset, int count, int flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0);
bytesSent = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new SendOperation {
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, SocketAsyncEvents.Write, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
bytesSent = operation.BytesTransferred;
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
bytesSent = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
bytesSent = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError SendToAsync(byte[] buffer, int offset, int count, int flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, int, SocketError> callback)
{
int bytesSent = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, int, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, 0, SocketError.Success);
}, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new SendOperation {
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, SocketAsyncEvents.Write, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Send(IList<ArraySegment<byte>> buffers, int flags, int timeout, out int bytesSent)
{
return SendTo(buffers, flags, null, 0, timeout, out bytesSent);
}
public SocketError SendAsync(IList<ArraySegment<byte>> buffers, int flags, Action<int, byte[], int, int, SocketError> callback)
{
return SendToAsync(buffers, flags, null, 0, callback);
}
public SocketError SendTo(IList<ArraySegment<byte>> buffers, int flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0);
bytesSent = 0;
int bufferIndex = 0;
int offset = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new SendOperation {
Event = @event,
Buffers = buffers,
BufferIndex = bufferIndex,
Offset = offset,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, SocketAsyncEvents.Write, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
bytesSent = operation.BytesTransferred;
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
bytesSent = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
bytesSent = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, int flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, int, SocketError> callback)
{
int bufferIndex = 0;
int offset = 0;
int bytesSent = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, int, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, 0, SocketError.Success);
}, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new SendOperation {
Callback = callback,
Buffers = buffers,
BufferIndex = bufferIndex,
Offset = offset,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, SocketAsyncEvents.Write, out isStopped))
{
if (isStopped)
{
// TODO: is this error code reasonable for a closed socket? Check with Winsock.
operation.ErrorCode = SocketError.Shutdown;
operation.QueueCompletionCallback();
return SocketError.Shutdown;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public unsafe void HandleEvents(SocketAsyncEvents events)
{
Debug.Assert(!Monitor.IsEntered(_queueLock) || Monitor.IsEntered(_closeLock), "Lock ordering violation");
lock (_closeLock)
{
if (_registeredEvents == (SocketAsyncEvents)(-1))
{
// This can happen if a previous attempt at unregistration did not succeed.
// Retry the unregistration.
lock (_queueLock)
{
Debug.Assert(_acceptOrConnectQueue.IsStopped, "{Accept,Connect} queue should be stopped before retrying unregistration");
Debug.Assert(_sendQueue.IsStopped, "Send queue should be stopped before retrying unregistration");
Debug.Assert(_receiveQueue.IsStopped, "Receive queue should be stopped before retrying unregistration");
Unregister();
return;
}
}
if ((events & SocketAsyncEvents.Error) != 0)
{
// Set the Read and Write flags as well; the processing for these events
// will pick up the error.
events |= SocketAsyncEvents.Read | SocketAsyncEvents.Write;
}
if ((events & SocketAsyncEvents.Close) != 0)
{
// Drain queues and unregister this fd, then return.
CloseInner();
return;
}
if ((events & SocketAsyncEvents.ReadClose) != 0)
{
// Drain read queue and unregister read operations
Debug.Assert(_acceptOrConnectQueue.IsEmpty, "{Accept,Connect} queue should be empty before ReadClose");
OperationQueue<TransferOperation> receiveQueue;
lock (_queueLock)
{
receiveQueue = _receiveQueue.Stop();
}
while (!receiveQueue.IsEmpty)
{
TransferOperation op = receiveQueue.Head;
bool completed = op.TryCompleteAsync(_fileDescriptor);
Debug.Assert(completed);
receiveQueue.Dequeue();
}
lock (_queueLock)
{
UnregisterRead();
}
// Any data left in the socket has been received above; skip further processing.
events &= ~SocketAsyncEvents.Read;
}
// TODO: optimize locking and completions:
// - Dequeues (and therefore locking) for multiple contiguous operations can be combined
// - Contiguous completions can happen in a single thread
if ((events & SocketAsyncEvents.Read) != 0)
{
AcceptOrConnectOperation acceptTail;
TransferOperation receiveTail;
lock (_queueLock)
{
acceptTail = _acceptOrConnectQueue.Tail as AcceptOperation;
_acceptOrConnectQueue.State = QueueState.Set;
receiveTail = _receiveQueue.Tail;
_receiveQueue.State = QueueState.Set;
}
if (acceptTail != null)
{
AcceptOrConnectOperation op;
do
{
op = _acceptOrConnectQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _acceptOrConnectQueue);
} while (op != acceptTail);
}
if (receiveTail != null)
{
TransferOperation op;
do
{
op = _receiveQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _receiveQueue);
} while (op != receiveTail);
}
}
if ((events & SocketAsyncEvents.Write) != 0)
{
AcceptOrConnectOperation connectTail;
SendOperation sendTail;
lock (_queueLock)
{
connectTail = _acceptOrConnectQueue.Tail as ConnectOperation;
_acceptOrConnectQueue.State = QueueState.Set;
sendTail = _sendQueue.Tail;
_sendQueue.State = QueueState.Set;
}
if (connectTail != null)
{
AcceptOrConnectOperation op;
do
{
op = _acceptOrConnectQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _acceptOrConnectQueue);
} while (op != connectTail);
}
if (sendTail != null)
{
SendOperation op;
do
{
op = _sendQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _sendQueue);
} while (op != sendTail);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: The boolean class serves as a wrapper for the primitive
** type boolean.
**
**
===========================================================*/
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean>
{
//
// Member Variables
//
private bool m_value; // Do not rename (binary serialization)
// The true value.
//
internal const int True = 1;
// The false value.
//
internal const int False = 0;
//
// Internal Constants are real consts for performance.
//
// The internal string representation of true.
//
internal const String TrueLiteral = "True";
// The internal string representation of false.
//
internal const String FalseLiteral = "False";
//
// Public Constants
//
// The public string representation of true.
//
public static readonly String TrueString = TrueLiteral;
// The public string representation of false.
//
public static readonly String FalseString = FalseLiteral;
//
// Overriden Instance Methods
//
/*=================================GetHashCode==================================
**Args: None
**Returns: 1 or 0 depending on whether this instance represents true or false.
**Exceptions: None
**Overriden From: Value
==============================================================================*/
// Provides a hash code for this instance.
public override int GetHashCode()
{
return (m_value) ? True : False;
}
/*===================================ToString===================================
**Args: None
**Returns: "True" or "False" depending on the state of the boolean.
**Exceptions: None.
==============================================================================*/
// Converts the boolean value of this instance to a String.
public override String ToString()
{
if (false == m_value)
{
return FalseLiteral;
}
return TrueLiteral;
}
public String ToString(IFormatProvider provider)
{
return ToString();
}
// Determines whether two Boolean objects are equal.
public override bool Equals(Object obj)
{
//If it's not a boolean, we're definitely not equal
if (!(obj is Boolean))
{
return false;
}
return (m_value == ((Boolean)obj).m_value);
}
[NonVersionable]
public bool Equals(Boolean obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship. For booleans, false sorts before true.
// null is considered to be less than any instance.
// If object is not of type boolean, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is Boolean))
{
throw new ArgumentException(SR.Arg_MustBeBoolean);
}
if (m_value == ((Boolean)obj).m_value)
{
return 0;
}
else if (m_value == false)
{
return -1;
}
return 1;
}
public int CompareTo(Boolean value)
{
if (m_value == value)
{
return 0;
}
else if (m_value == false)
{
return -1;
}
return 1;
}
//
// Static Methods
//
// Determines whether a String represents true or false.
//
public static Boolean Parse(String value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
Boolean result = false;
if (!TryParse(value, out result))
{
throw new FormatException(SR.Format_BadBoolean);
}
else
{
return result;
}
}
// Determines whether a String represents true or false.
//
public static Boolean TryParse(String value, out Boolean result)
{
result = false;
if (value == null)
{
return false;
}
// For perf reasons, let's first see if they're equal, then do the
// trim to get rid of white space, and check again.
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
return false;
}
private static String TrimWhiteSpaceAndNull(String value)
{
int start = 0;
int end = value.Length - 1;
char nullChar = (char)0x0000;
while (start < value.Length)
{
if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar)
{
break;
}
start++;
}
while (end >= start)
{
if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar)
{
break;
}
end--;
}
return value.Substring(start, end - start + 1);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Boolean;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return m_value;
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using NUnit.Framework;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
using Mono.Cecil.PE;
namespace Mono.Cecil.Tests {
[TestFixture]
public class PortablePdbTests : BaseTestFixture {
[Test]
public void SequencePoints ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var main = type.GetMethod ("Main");
AssertCode (@"
.locals init (System.Int32 a, System.String[] V_1, System.Int32 V_2, System.String arg)
.line 21,21:3,4 'C:\sources\PdbTarget\Program.cs'
IL_0000: nop
.line 22,22:4,11 'C:\sources\PdbTarget\Program.cs'
IL_0001: nop
.line 22,22:24,28 'C:\sources\PdbTarget\Program.cs'
IL_0002: ldarg.0
IL_0003: stloc.1
IL_0004: ldc.i4.0
IL_0005: stloc.2
.line hidden 'C:\sources\PdbTarget\Program.cs'
IL_0006: br.s IL_0017
.line 22,22:13,20 'C:\sources\PdbTarget\Program.cs'
IL_0008: ldloc.1
IL_0009: ldloc.2
IL_000a: ldelem.ref
IL_000b: stloc.3
.line 23,23:5,20 'C:\sources\PdbTarget\Program.cs'
IL_000c: ldloc.3
IL_000d: call System.Void System.Console::WriteLine(System.String)
IL_0012: nop
.line hidden 'C:\sources\PdbTarget\Program.cs'
IL_0013: ldloc.2
IL_0014: ldc.i4.1
IL_0015: add
IL_0016: stloc.2
.line 22,22:21,23 'C:\sources\PdbTarget\Program.cs'
IL_0017: ldloc.2
IL_0018: ldloc.1
IL_0019: ldlen
IL_001a: conv.i4
IL_001b: blt.s IL_0008
.line 25,25:4,22 'C:\sources\PdbTarget\Program.cs'
IL_001d: ldc.i4.1
IL_001e: ldc.i4.2
IL_001f: call System.Int32 System.Math::Min(System.Int32,System.Int32)
IL_0024: stloc.0
.line 26,26:3,4 'C:\sources\PdbTarget\Program.cs'
IL_0025: ret
", main);
});
}
[Test]
public void SequencePointsMultipleDocument ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.B");
var main = type.GetMethod (".ctor");
AssertCode (@"
.locals ()
.line 7,7:3,25 'C:\sources\PdbTarget\B.cs'
IL_0000: ldarg.0
IL_0001: ldstr """"
IL_0006: stfld System.String PdbTarget.B::s
.line 110,110:3,21 'C:\sources\PdbTarget\Program.cs'
IL_000b: ldarg.0
IL_000c: ldc.i4.2
IL_000d: stfld System.Int32 PdbTarget.B::a
.line 111,111:3,21 'C:\sources\PdbTarget\Program.cs'
IL_0012: ldarg.0
IL_0013: ldc.i4.3
IL_0014: stfld System.Int32 PdbTarget.B::b
.line 9,9:3,13 'C:\sources\PdbTarget\B.cs'
IL_0019: ldarg.0
IL_001a: call System.Void System.Object::.ctor()
IL_001f: nop
.line 10,10:3,4 'C:\sources\PdbTarget\B.cs'
IL_0020: nop
.line 11,11:4,19 'C:\sources\PdbTarget\B.cs'
IL_0021: ldstr ""B""
IL_0026: call System.Void System.Console::WriteLine(System.String)
IL_002b: nop
.line 12,12:3,4 'C:\sources\PdbTarget\B.cs'
IL_002c: ret
", main);
});
}
[Test]
public void LocalVariables ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var method = type.GetMethod ("Bar");
var debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
Assert.IsTrue (debug_info.Scope.HasScopes);
Assert.AreEqual (2, debug_info.Scope.Scopes.Count);
var scope = debug_info.Scope.Scopes [0];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasVariables);
Assert.AreEqual (1, scope.Variables.Count);
var variable = scope.Variables [0];
Assert.AreEqual ("s", variable.Name);
Assert.IsFalse (variable.IsDebuggerHidden);
Assert.AreEqual (2, variable.Index);
scope = debug_info.Scope.Scopes [1];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasVariables);
Assert.AreEqual (1, scope.Variables.Count);
variable = scope.Variables [0];
Assert.AreEqual ("s", variable.Name);
Assert.IsFalse (variable.IsDebuggerHidden);
Assert.AreEqual (3, variable.Index);
Assert.IsTrue (scope.HasScopes);
Assert.AreEqual (1, scope.Scopes.Count);
scope = scope.Scopes [0];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasVariables);
Assert.AreEqual (1, scope.Variables.Count);
variable = scope.Variables [0];
Assert.AreEqual ("u", variable.Name);
Assert.IsFalse (variable.IsDebuggerHidden);
Assert.AreEqual (5, variable.Index);
});
}
[Test]
public void LocalConstants ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var method = type.GetMethod ("Bar");
var debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
Assert.IsTrue (debug_info.Scope.HasScopes);
Assert.AreEqual (2, debug_info.Scope.Scopes.Count);
var scope = debug_info.Scope.Scopes [1];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasConstants);
Assert.AreEqual (2, scope.Constants.Count);
var constant = scope.Constants [0];
Assert.AreEqual ("b", constant.Name);
Assert.AreEqual (12, constant.Value);
Assert.AreEqual (MetadataType.Int32, constant.ConstantType.MetadataType);
constant = scope.Constants [1];
Assert.AreEqual ("c", constant.Name);
Assert.AreEqual ((decimal) 74, constant.Value);
Assert.AreEqual (MetadataType.ValueType, constant.ConstantType.MetadataType);
method = type.GetMethod ("Foo");
debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
Assert.IsTrue (debug_info.Scope.HasConstants);
Assert.AreEqual (4, debug_info.Scope.Constants.Count);
constant = debug_info.Scope.Constants [0];
Assert.AreEqual ("s", constant.Name);
Assert.AreEqual ("const string", constant.Value);
Assert.AreEqual (MetadataType.String, constant.ConstantType.MetadataType);
constant = debug_info.Scope.Constants [1];
Assert.AreEqual ("f", constant.Name);
Assert.AreEqual (1, constant.Value);
Assert.AreEqual (MetadataType.Int32, constant.ConstantType.MetadataType);
constant = debug_info.Scope.Constants [2];
Assert.AreEqual ("o", constant.Name);
Assert.AreEqual (null, constant.Value);
Assert.AreEqual (MetadataType.Object, constant.ConstantType.MetadataType);
constant = debug_info.Scope.Constants [3];
Assert.AreEqual ("u", constant.Name);
Assert.AreEqual (null, constant.Value);
Assert.AreEqual (MetadataType.String, constant.ConstantType.MetadataType);
});
}
[Test]
public void ImportScope ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var method = type.GetMethod ("Bar");
var debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
var import = debug_info.Scope.Import;
Assert.IsNotNull (import);
Assert.IsFalse (import.HasTargets);
Assert.IsNotNull (import.Parent);
import = import.Parent;
Assert.IsTrue (import.HasTargets);
Assert.AreEqual (9, import.Targets.Count);
var target = import.Targets [0];
Assert.AreEqual (ImportTargetKind.ImportAlias, target.Kind);
Assert.AreEqual ("XML", target.Alias);
target = import.Targets [1];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System", target.Namespace);
target = import.Targets [2];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System.Collections.Generic", target.Namespace);
target = import.Targets [3];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System.IO", target.Namespace);
target = import.Targets [4];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System.Threading.Tasks", target.Namespace);
target = import.Targets [5];
Assert.AreEqual (ImportTargetKind.ImportNamespaceInAssembly, target.Kind);
Assert.AreEqual ("System.Xml.Resolvers", target.Namespace);
Assert.AreEqual ("System.Xml", target.AssemblyReference.Name);
target = import.Targets [6];
Assert.AreEqual (ImportTargetKind.ImportType, target.Kind);
Assert.AreEqual ("System.Console", target.Type.FullName);
target = import.Targets [7];
Assert.AreEqual (ImportTargetKind.ImportType, target.Kind);
Assert.AreEqual ("System.Math", target.Type.FullName);
target = import.Targets [8];
Assert.AreEqual (ImportTargetKind.DefineTypeAlias, target.Kind);
Assert.AreEqual ("Foo", target.Alias);
Assert.AreEqual ("System.Xml.XmlDocumentType", target.Type.FullName);
Assert.IsNotNull (import.Parent);
import = import.Parent;
Assert.IsTrue (import.HasTargets);
Assert.AreEqual (1, import.Targets.Count);
Assert.IsNull (import.Parent);
target = import.Targets [0];
Assert.AreEqual (ImportTargetKind.DefineAssemblyAlias, target.Kind);
Assert.AreEqual ("XML", target.Alias);
Assert.AreEqual ("System.Xml", target.AssemblyReference.Name);
});
}
[Test]
public void StateMachineKickOff ()
{
TestPortablePdbModule (module => {
var state_machine = module.GetType ("PdbTarget.Program/<Baz>d__7");
var main = state_machine.GetMethod ("MoveNext");
var symbol = main.DebugInformation;
Assert.IsNotNull (symbol);
Assert.IsNotNull (symbol.StateMachineKickOffMethod);
Assert.AreEqual ("System.Threading.Tasks.Task PdbTarget.Program::Baz(System.IO.StreamReader)", symbol.StateMachineKickOffMethod.FullName);
});
}
[Test]
public void StateMachineCustomDebugInformation ()
{
TestPortablePdbModule (module => {
var state_machine = module.GetType ("PdbTarget.Program/<Baz>d__7");
var move_next = state_machine.GetMethod ("MoveNext");
Assert.IsTrue (move_next.HasCustomDebugInformations);
var state_machine_scope = move_next.CustomDebugInformations.OfType<StateMachineScopeDebugInformation> ().FirstOrDefault ();
Assert.IsNotNull (state_machine_scope);
Assert.AreEqual (3, state_machine_scope.Scopes.Count);
Assert.AreEqual (0, state_machine_scope.Scopes [0].Start.Offset);
Assert.IsTrue (state_machine_scope.Scopes [0].End.IsEndOfMethod);
Assert.AreEqual (0, state_machine_scope.Scopes [1].Start.Offset);
Assert.AreEqual (0, state_machine_scope.Scopes [1].End.Offset);
Assert.AreEqual (184, state_machine_scope.Scopes [2].Start.Offset);
Assert.AreEqual (343, state_machine_scope.Scopes [2].End.Offset);
var async_body = move_next.CustomDebugInformations.OfType<AsyncMethodBodyDebugInformation> ().FirstOrDefault ();
Assert.IsNotNull (async_body);
Assert.AreEqual (-1, async_body.CatchHandler.Offset);
Assert.AreEqual (2, async_body.Yields.Count);
Assert.AreEqual (61, async_body.Yields [0].Offset);
Assert.AreEqual (221, async_body.Yields [1].Offset);
Assert.AreEqual (2, async_body.Resumes.Count);
Assert.AreEqual (91, async_body.Resumes [0].Offset);
Assert.AreEqual (252, async_body.Resumes [1].Offset);
Assert.AreEqual (move_next, async_body.ResumeMethods [0]);
Assert.AreEqual (move_next, async_body.ResumeMethods [1]);
});
}
[Test]
public void EmbeddedCompressedPortablePdb ()
{
TestModule("EmbeddedCompressedPdbTarget.exe", module => {
Assert.IsTrue (module.HasDebugHeader);
var header = module.GetDebugHeader ();
Assert.IsNotNull (header);
Assert.IsTrue (header.Entries.Length >= 2);
int i = 0;
var cv = header.Entries [i++];
Assert.AreEqual (ImageDebugType.CodeView, cv.Directory.Type);
if (header.Entries.Length > 2) {
Assert.AreEqual (3, header.Entries.Length);
var pdbChecksum = header.Entries [i++];
Assert.AreEqual (ImageDebugType.PdbChecksum, pdbChecksum.Directory.Type);
}
var eppdb = header.Entries [i++];
Assert.AreEqual (ImageDebugType.EmbeddedPortablePdb, eppdb.Directory.Type);
Assert.AreEqual (0x0100, eppdb.Directory.MajorVersion);
Assert.AreEqual (0x0100, eppdb.Directory.MinorVersion);
}, symbolReaderProvider: typeof (EmbeddedPortablePdbReaderProvider), symbolWriterProvider: typeof (EmbeddedPortablePdbWriterProvider));
}
[Test]
public void EmbeddedCompressedPortablePdbFromStream ()
{
var bytes = File.ReadAllBytes (GetAssemblyResourcePath ("EmbeddedCompressedPdbTarget.exe"));
var parameters = new ReaderParameters {
ReadSymbols = true,
SymbolReaderProvider = new PdbReaderProvider ()
};
var module = ModuleDefinition.ReadModule (new MemoryStream(bytes), parameters);
Assert.IsTrue (module.HasDebugHeader);
var header = module.GetDebugHeader ();
Assert.IsNotNull (header);
Assert.AreEqual (2, header.Entries.Length);
var cv = header.Entries [0];
Assert.AreEqual (ImageDebugType.CodeView, cv.Directory.Type);
var eppdb = header.Entries [1];
Assert.AreEqual (ImageDebugType.EmbeddedPortablePdb, eppdb.Directory.Type);
Assert.AreEqual (0x0100, eppdb.Directory.MajorVersion);
Assert.AreEqual (0x0100, eppdb.Directory.MinorVersion);
}
void TestPortablePdbModule (Action<ModuleDefinition> test)
{
TestModule ("PdbTarget.exe", test, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
TestModule ("EmbeddedPdbTarget.exe", test, verify: !Platform.OnMono);
TestModule ("EmbeddedCompressedPdbTarget.exe", test, symbolReaderProvider: typeof(EmbeddedPortablePdbReaderProvider), symbolWriterProvider: typeof (EmbeddedPortablePdbWriterProvider));
}
[Test]
public void RoundTripCecilPortablePdb ()
{
TestModule ("cecil.dll", module => {
Assert.IsTrue (module.HasSymbols);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void RoundTripLargePortablePdb ()
{
TestModule ("Mono.Android.dll", module => {
Assert.IsTrue (module.HasSymbols);
}, verify: false, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void EmptyPortablePdb ()
{
TestModule ("EmptyPdb.dll", module => {
Assert.IsTrue (module.HasSymbols);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void NullClassConstant ()
{
TestModule ("xattr.dll", module => {
var type = module.GetType ("Library");
var method = type.GetMethod ("NullXAttributeConstant");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (1, symbol.Scope.Constants.Count);
var a = symbol.Scope.Constants [0];
Assert.AreEqual ("a", a.Name);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void InvalidConstantRecord ()
{
using (var module = GetResourceModule ("mylib.dll", new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
var type = module.GetType ("mylib.Say");
var method = type.GetMethod ("hello");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (0, symbol.Scope.Constants.Count);
}
}
[Test]
public void GenericInstConstantRecord ()
{
using (var module = GetResourceModule ("ReproConstGenericInst.dll", new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
var type = module.GetType ("ReproConstGenericInst.Program");
var method = type.GetMethod ("Main");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (1, symbol.Scope.Constants.Count);
var list = symbol.Scope.Constants [0];
Assert.AreEqual ("list", list.Name);
Assert.AreEqual ("System.Collections.Generic.List`1<System.String>", list.ConstantType.FullName);
}
}
[Test]
public void EmptyStringLocalConstant ()
{
TestModule ("empty-str-const.exe", module => {
var type = module.GetType ("<Program>$");
var method = type.GetMethod ("<Main>$");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (1, symbol.Scope.Constants.Count);
var a = symbol.Scope.Constants [0];
Assert.AreEqual ("value", a.Name);
Assert.AreEqual ("", a.Value);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void SourceLink ()
{
TestModule ("TargetLib.dll", module => {
Assert.IsTrue (module.HasCustomDebugInformations);
Assert.AreEqual (1, module.CustomDebugInformations.Count);
var source_link = module.CustomDebugInformations [0] as SourceLinkDebugInformation;
Assert.IsNotNull (source_link);
Assert.AreEqual ("{\"documents\":{\"C:\\\\tmp\\\\SourceLinkProblem\\\\*\":\"https://raw.githubusercontent.com/bording/SourceLinkProblem/197d965ee7f1e7f8bd3cea55b5f904aeeb8cd51e/*\"}}", source_link.Content);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void EmbeddedSource ()
{
TestModule ("embedcs.exe", module => {
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
TestModule ("embedcs.exe", module => {
var program = GetDocument (module.GetType ("Program"));
var program_src = GetSourceDebugInfo (program);
Assert.IsTrue (program_src.Compress);
var program_src_content = Encoding.UTF8.GetString (program_src.Content);
Assert.AreEqual (Normalize (@"using System;
class Program
{
static void Main()
{
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
Console.WriteLine(B.Do());
Console.WriteLine(A.Do());
}
}
"), Normalize (program_src_content));
var a = GetDocument (module.GetType ("A"));
var a_src = GetSourceDebugInfo (a);
Assert.IsFalse (a_src.Compress);
var a_src_content = Encoding.UTF8.GetString (a_src.Content);
Assert.AreEqual (Normalize (@"class A
{
public static string Do()
{
return ""A::Do"";
}
}"), Normalize (a_src_content));
var b = GetDocument(module.GetType ("B"));
var b_src = GetSourceDebugInfo (b);
Assert.IsFalse (b_src.compress);
var b_src_content = Encoding.UTF8.GetString (b_src.Content);
Assert.AreEqual (Normalize (@"class B
{
public static string Do()
{
return ""B::Do"";
}
}"), Normalize (b_src_content));
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
static Document GetDocument (TypeDefinition type)
{
foreach (var method in type.Methods) {
if (!method.HasBody)
continue;
foreach (var instruction in method.Body.Instructions) {
var sp = method.DebugInformation.GetSequencePoint (instruction);
if (sp != null && sp.Document != null)
return sp.Document;
}
}
return null;
}
static EmbeddedSourceDebugInformation GetSourceDebugInfo (Document document)
{
Assert.IsTrue (document.HasCustomDebugInformations);
Assert.AreEqual (1, document.CustomDebugInformations.Count);
var source = document.CustomDebugInformations [0] as EmbeddedSourceDebugInformation;
Assert.IsNotNull (source);
return source;
}
[Test]
public void PortablePdbLineInfo()
{
TestModule ("line.exe", module => {
var type = module.GetType ("Tests");
var main = type.GetMethod ("Main");
AssertCode (@"
.locals ()
.line 4,4:42,43 '/foo/bar.cs'
IL_0000: nop
.line 5,5:2,3 '/foo/bar.cs'
IL_0001: ret", main);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
public sealed class SymbolWriterProvider : ISymbolWriterProvider {
readonly DefaultSymbolWriterProvider writer_provider = new DefaultSymbolWriterProvider ();
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
return new SymbolWriter (writer_provider.GetSymbolWriter (module, fileName));
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
return new SymbolWriter (writer_provider.GetSymbolWriter (module, symbolStream));
}
}
public sealed class SymbolWriter : ISymbolWriter {
readonly ISymbolWriter symbol_writer;
public SymbolWriter (ISymbolWriter symbolWriter)
{
this.symbol_writer = symbolWriter;
}
public ImageDebugHeader GetDebugHeader ()
{
var header = symbol_writer.GetDebugHeader ();
if (!header.HasEntries)
return header;
for (int i = 0; i < header.Entries.Length; i++) {
header.Entries [i] = ProcessEntry (header.Entries [i]);
}
return header;
}
private static ImageDebugHeaderEntry ProcessEntry (ImageDebugHeaderEntry entry)
{
if (entry.Directory.Type != ImageDebugType.CodeView)
return entry;
var reader = new ByteBuffer (entry.Data);
var writer = new ByteBuffer ();
var sig = reader.ReadUInt32 ();
if (sig != 0x53445352)
return entry;
writer.WriteUInt32 (sig); // RSDS
writer.WriteBytes (reader.ReadBytes (16)); // MVID
writer.WriteUInt32 (reader.ReadUInt32 ()); // Age
var length = Array.IndexOf (entry.Data, (byte) 0, reader.position) - reader.position;
var fullPath = Encoding.UTF8.GetString (reader.ReadBytes (length));
writer.WriteBytes (Encoding.UTF8.GetBytes (Path.GetFileName (fullPath)));
writer.WriteByte (0);
var newData = new byte [writer.length];
Buffer.BlockCopy (writer.buffer, 0, newData, 0, writer.length);
var directory = entry.Directory;
directory.SizeOfData = newData.Length;
return new ImageDebugHeaderEntry (directory, newData);
}
public ISymbolReaderProvider GetReaderProvider ()
{
return symbol_writer.GetReaderProvider ();
}
public void Write (MethodDebugInformation info)
{
symbol_writer.Write (info);
}
public void Write ()
{
symbol_writer.Write ();
}
public void Dispose ()
{
symbol_writer.Dispose ();
}
}
static string GetDebugHeaderPdbPath (ModuleDefinition module)
{
var header = module.GetDebugHeader ();
var cv = Mixin.GetCodeViewEntry (header);
Assert.IsNotNull (cv);
var length = Array.IndexOf (cv.Data, (byte)0, 24) - 24;
var bytes = new byte [length];
Buffer.BlockCopy (cv.Data, 24, bytes, 0, length);
return Encoding.UTF8.GetString (bytes);
}
[Test]
public void UseCustomSymbolWriterToChangeDebugHeaderPdbPath ()
{
const string resource = "mylib.dll";
string debug_header_pdb_path;
string dest = Path.Combine (Path.GetTempPath (), resource);
using (var module = GetResourceModule (resource, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
debug_header_pdb_path = GetDebugHeaderPdbPath (module);
Assert.IsTrue (Path.IsPathRooted (debug_header_pdb_path));
module.Write (dest, new WriterParameters { SymbolWriterProvider = new SymbolWriterProvider () });
}
using (var module = ModuleDefinition.ReadModule (dest, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
var pdb_path = GetDebugHeaderPdbPath (module);
Assert.IsFalse (Path.IsPathRooted (pdb_path));
Assert.AreEqual (Path.GetFileName (debug_header_pdb_path), pdb_path);
}
}
[Test]
public void WriteAndReadAgainModuleWithDeterministicMvid ()
{
const string resource = "mylib.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, SymbolWriterProvider = new SymbolWriterProvider () });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
}
}
[Test]
public void DoubleWriteAndReadAgainModuleWithDeterministicMvid ()
{
Guid mvid1_in, mvid1_out, mvid2_in, mvid2_out;
{
const string resource = "foo.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { })) {
mvid1_in = module.Mvid;
module.Write (destination, new WriterParameters { DeterministicMvid = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { })) {
mvid1_out = module.Mvid;
}
}
{
const string resource = "hello2.exe";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { })) {
mvid2_in = module.Mvid;
module.Write (destination, new WriterParameters { DeterministicMvid = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { })) {
mvid2_out = module.Mvid;
}
}
Assert.AreNotEqual (mvid1_in, mvid2_in);
Assert.AreNotEqual (mvid1_out, mvid2_out);
}
[Test]
public void ClearSequencePoints ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var main = type.GetMethod ("Main");
main.DebugInformation.SequencePoints.Clear ();
var destination = Path.Combine (Path.GetTempPath (), "mylib.dll");
module.Write(destination, new WriterParameters { WriteSymbols = true });
Assert.Zero (main.DebugInformation.SequencePoints.Count);
using (var resultModule = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
type = resultModule.GetType ("PdbTarget.Program");
main = type.GetMethod ("Main");
Assert.Zero (main.DebugInformation.SequencePoints.Count);
}
});
}
[Test]
public void DoubleWriteAndReadWithDeterministicMvidAndVariousChanges ()
{
Guid mvidIn, mvidARM64Out, mvidX64Out;
const string resource = "mylib.dll";
{
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
mvidIn = module.Mvid;
module.Architecture = TargetArchitecture.ARM64; // Can't use I386 as it writes different import table size -> differnt MVID
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
mvidARM64Out = module.Mvid;
}
Assert.AreNotEqual (mvidIn, mvidARM64Out);
}
{
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
Assert.AreEqual (mvidIn, module.Mvid);
module.Architecture = TargetArchitecture.AMD64;
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
mvidX64Out = module.Mvid;
}
Assert.AreNotEqual (mvidARM64Out, mvidX64Out);
}
{
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
Assert.AreEqual (mvidIn, module.Mvid);
module.Architecture = TargetArchitecture.AMD64;
module.timestamp = 42;
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
Guid mvidDifferentTimeStamp;
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
mvidDifferentTimeStamp = module.Mvid;
}
Assert.AreNotEqual (mvidX64Out, mvidDifferentTimeStamp);
}
}
[Test]
public void ReadPortablePdbChecksum ()
{
const string resource = "PdbChecksumLib.dll";
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
GetPdbChecksumData (module.GetDebugHeader (), out string algorithmName, out byte [] checksum);
Assert.AreEqual ("SHA256", algorithmName);
GetCodeViewPdbId (module, out byte[] pdbId);
string pdbPath = Mixin.GetPdbFileName (module.FileName);
CalculatePdbChecksumAndId (pdbPath, out byte [] expectedChecksum, out byte [] expectedPdbId);
CollectionAssert.AreEqual (expectedChecksum, checksum);
CollectionAssert.AreEqual (expectedPdbId, pdbId);
}
}
[Test]
public void ReadEmbeddedPortablePdbChecksum ()
{
const string resource = "EmbeddedPdbChecksumLib.dll";
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
var debugHeader = module.GetDebugHeader ();
GetPdbChecksumData (debugHeader, out string algorithmName, out byte [] checksum);
Assert.AreEqual ("SHA256", algorithmName);
GetCodeViewPdbId (module, out byte [] pdbId);
GetEmbeddedPdb (debugHeader, out byte [] embeddedPdb);
CalculatePdbChecksumAndId (embeddedPdb, out byte [] expectedChecksum, out byte [] expectedPdbId);
CollectionAssert.AreEqual (expectedChecksum, checksum);
CollectionAssert.AreEqual (expectedPdbId, pdbId);
}
}
[Test]
public void WritePortablePdbChecksum ()
{
const string resource = "PdbChecksumLib.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
GetPdbChecksumData (module.GetDebugHeader (), out string algorithmName, out byte [] checksum);
Assert.AreEqual ("SHA256", algorithmName);
GetCodeViewPdbId (module, out byte [] pdbId);
string pdbPath = Mixin.GetPdbFileName (module.FileName);
CalculatePdbChecksumAndId (pdbPath, out byte [] expectedChecksum, out byte [] expectedPdbId);
CollectionAssert.AreEqual (expectedChecksum, checksum);
CollectionAssert.AreEqual (expectedPdbId, pdbId);
}
}
[Test]
public void WritePortablePdbToWriteOnlyStream ()
{
const string resource = "PdbChecksumLib.dll";
string destination = Path.GetTempFileName ();
// Note that the module stream already requires read access even on writing to be able to compute strong name
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true }))
using (var pdbStream = new FileStream (destination + ".pdb", FileMode.Create, FileAccess.Write)) {
module.Write (destination, new WriterParameters {
DeterministicMvid = true,
WriteSymbols = true,
SymbolWriterProvider = new PortablePdbWriterProvider (),
SymbolStream = pdbStream
});
}
}
[Test]
public void DoubleWritePortablePdbDeterministicPdbId ()
{
const string resource = "PdbChecksumLib.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
byte [] pdbIdOne;
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
string pdbPath = Mixin.GetPdbFileName (module.FileName);
CalculatePdbChecksumAndId (pdbPath, out byte [] expectedChecksum, out pdbIdOne);
}
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
byte [] pdbIdTwo;
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
string pdbPath = Mixin.GetPdbFileName (module.FileName);
CalculatePdbChecksumAndId (pdbPath, out byte [] expectedChecksum, out pdbIdTwo);
}
CollectionAssert.AreEqual (pdbIdOne, pdbIdTwo);
}
[Test]
public void WriteEmbeddedPortablePdbChecksum ()
{
const string resource = "EmbeddedPdbChecksumLib.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
var debugHeader = module.GetDebugHeader ();
GetPdbChecksumData (debugHeader, out string algorithmName, out byte [] checksum);
Assert.AreEqual ("SHA256", algorithmName);
GetCodeViewPdbId (module, out byte [] pdbId);
GetEmbeddedPdb (debugHeader, out byte [] embeddedPdb);
CalculatePdbChecksumAndId (embeddedPdb, out byte [] expectedChecksum, out byte [] expectedPdbId);
CollectionAssert.AreEqual (expectedChecksum, checksum);
CollectionAssert.AreEqual (expectedPdbId, pdbId);
}
}
[Test]
public void DoubleWriteEmbeddedPortablePdbChecksum ()
{
const string resource = "EmbeddedPdbChecksumLib.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
byte [] pdbIdOne;
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
var debugHeader = module.GetDebugHeader ();
GetEmbeddedPdb (debugHeader, out byte [] embeddedPdb);
CalculatePdbChecksumAndId (embeddedPdb, out byte [] expectedChecksum, out pdbIdOne);
}
using (var module = GetResourceModule (resource, new ReaderParameters { ReadSymbols = true })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, WriteSymbols = true });
}
byte [] pdbIdTwo;
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
var debugHeader = module.GetDebugHeader ();
GetEmbeddedPdb (debugHeader, out byte [] embeddedPdb);
CalculatePdbChecksumAndId (embeddedPdb, out byte [] expectedChecksum, out pdbIdTwo);
}
CollectionAssert.AreEqual (pdbIdOne, pdbIdTwo);
}
private void GetEmbeddedPdb (ImageDebugHeader debugHeader, out byte [] embeddedPdb)
{
var entry = Mixin.GetEmbeddedPortablePdbEntry (debugHeader);
Assert.IsNotNull (entry);
var compressed_stream = new MemoryStream (entry.Data);
var reader = new BinaryStreamReader (compressed_stream);
Assert.AreEqual (0x4244504D, reader.ReadInt32 ());
var length = reader.ReadInt32 ();
var decompressed_stream = new MemoryStream (length);
using (var deflate = new DeflateStream (compressed_stream, CompressionMode.Decompress, leaveOpen: true))
deflate.CopyTo (decompressed_stream);
embeddedPdb = decompressed_stream.ToArray ();
}
private void GetPdbChecksumData (ImageDebugHeader debugHeader, out string algorithmName, out byte [] checksum)
{
var entry = Mixin.GetPdbChecksumEntry (debugHeader);
Assert.IsNotNull (entry);
var length = Array.IndexOf (entry.Data, (byte)0, 0);
var bytes = new byte [length];
Buffer.BlockCopy (entry.Data, 0, bytes, 0, length);
algorithmName = Encoding.UTF8.GetString (bytes);
int checksumSize = 0;
switch (algorithmName) {
case "SHA256": checksumSize = 32; break;
case "SHA384": checksumSize = 48; break;
case "SHA512": checksumSize = 64; break;
}
checksum = new byte [checksumSize];
Buffer.BlockCopy (entry.Data, length + 1, checksum, 0, checksumSize);
}
private void CalculatePdbChecksumAndId (string filePath, out byte [] pdbChecksum, out byte [] pdbId)
{
using (var fs = File.OpenRead (filePath))
CalculatePdbChecksumAndId (fs, out pdbChecksum, out pdbId);
}
private void CalculatePdbChecksumAndId (byte [] data, out byte [] pdbChecksum, out byte [] pdbId)
{
using (var pdb = new MemoryStream (data))
CalculatePdbChecksumAndId (pdb, out pdbChecksum, out pdbId);
}
private void CalculatePdbChecksumAndId (Stream pdbStream, out byte [] pdbChecksum, out byte [] pdbId)
{
// Get the offset of the PDB heap (this requires parsing several headers
// so it's easier to use the ImageReader directly for this)
Image image = ImageReader.ReadPortablePdb (new Disposable<Stream> (pdbStream, false), "test.pdb", out uint pdbHeapOffset);
pdbId = new byte [20];
Array.Copy (image.PdbHeap.data, 0, pdbId, 0, 20);
pdbStream.Seek (0, SeekOrigin.Begin);
byte [] rawBytes = pdbStream.ReadAll ();
var bytes = new byte [rawBytes.Length];
Array.Copy (rawBytes, 0, bytes, 0, pdbHeapOffset);
// Zero out the PDB ID (20 bytes)
for (int i = 0; i < 20; bytes [i + pdbHeapOffset] = 0, i++) ;
Array.Copy (rawBytes, pdbHeapOffset + 20, bytes, pdbHeapOffset + 20, rawBytes.Length - pdbHeapOffset - 20);
var sha256 = SHA256.Create ();
pdbChecksum = sha256.ComputeHash (bytes);
}
static void GetCodeViewPdbId (ModuleDefinition module, out byte[] pdbId)
{
var header = module.GetDebugHeader ();
var cv = Mixin.GetCodeViewEntry (header);
Assert.IsNotNull (cv);
CollectionAssert.AreEqual (new byte [] { 0x52, 0x53, 0x44, 0x53 }, cv.Data.Take (4));
ByteBuffer buffer = new ByteBuffer (20);
buffer.WriteBytes (cv.Data.Skip (4).Take (16).ToArray ());
buffer.WriteInt32 (cv.Directory.TimeDateStamp);
pdbId = buffer.buffer;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
using System.Reflection;
#if CORECLR
// Use stubs for SystemException, SerializationInfo and SecurityPermissionAttribute
using Microsoft.PowerShell.CoreClr.Stubs;
#else
using System.Security.Permissions;
#endif
namespace System.Management.Automation.Runspaces
{
/// <summary>
/// Defines exception thrown when a PSSnapin was not able to load into current runspace.
/// </summary>
/// <!--
/// Implementation of PSSnapInException requires it to
/// 1. Implement IContainsErrorRecord,
/// 2. ISerializable
///
/// Basic information for this exception includes,
/// 1. PSSnapin name
/// 2. Inner exception.
/// -->
[Serializable]
public class PSSnapInException : RuntimeException
{
/// <summary>
/// Initiate an instance of PSSnapInException.
/// </summary>
/// <param name="PSSnapin">PSSnapin for the exception</param>
/// <param name="message">Message with load failure detail.</param>
internal PSSnapInException(string PSSnapin, string message)
: base()
{
_PSSnapin = PSSnapin;
_reason = message;
CreateErrorRecord();
}
/// <summary>
/// Initiate an instance of PSSnapInException.
/// </summary>
/// <param name="PSSnapin">PSSnapin for the exception</param>
/// <param name="message">Message with load failure detail.</param>
/// <param name="warning">Whether this is just a warning for PSSnapin load.</param>
internal PSSnapInException(string PSSnapin, string message, bool warning)
: base()
{
_PSSnapin = PSSnapin;
_reason = message;
_warning = warning;
CreateErrorRecord();
}
/// <summary>
/// Initiate an instance of PSSnapInException.
/// </summary>
/// <param name="PSSnapin">PSSnapin for the exception</param>
/// <param name="message">Message with load failure detail.</param>
/// <param name="exception">Exception for PSSnapin load failure</param>
internal PSSnapInException(string PSSnapin, string message, Exception exception)
: base(message, exception)
{
_PSSnapin = PSSnapin;
_reason = message;
CreateErrorRecord();
}
/// <summary>
/// Initiate an instance of PSSnapInException.
/// </summary>
public PSSnapInException() : base()
{
}
/// <summary>
/// Initiate an instance of PSSnapInException.
/// </summary>
/// <param name="message">Error message</param>
public PSSnapInException(string message)
: base(message)
{
}
/// <summary>
/// Initiate an instance of PSSnapInException.
/// </summary>
/// <param name="message">Error message</param>
/// <param name="innerException">Inner exception</param>
public PSSnapInException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Create the internal error record.
/// The ErrorRecord created will be stored in the _errorRecord member.
/// </summary>
private void CreateErrorRecord()
{
// if _PSSnapin or _reason is empty, this exception is created using default
// constructor. Don't create the error record since there is
// no useful information anyway.
if (!String.IsNullOrEmpty(_PSSnapin) && !String.IsNullOrEmpty(_reason))
{
Assembly currentAssembly = typeof(PSSnapInException).GetTypeInfo().Assembly;
if (_warning)
{
_errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "PSSnapInLoadWarning", ErrorCategory.ResourceUnavailable, null);
_errorRecord.ErrorDetails = new ErrorDetails(String.Format(ConsoleInfoErrorStrings.PSSnapInLoadWarning, _PSSnapin, _reason));
}
else
{
_errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "PSSnapInLoadFailure", ErrorCategory.ResourceUnavailable, null);
_errorRecord.ErrorDetails = new ErrorDetails(String.Format(ConsoleInfoErrorStrings.PSSnapInLoadFailure, _PSSnapin, _reason));
}
}
}
private bool _warning = false;
private ErrorRecord _errorRecord;
private bool _isErrorRecordOriginallyNull;
/// <summary>
/// Gets error record embedded in this exception.
/// </summary>
/// <!--
/// This property is required as part of IErrorRecordContainer
/// interface.
/// -->
public override ErrorRecord ErrorRecord
{
get
{
if (null == _errorRecord)
{
_isErrorRecordOriginallyNull = true;
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
"PSSnapInException",
ErrorCategory.NotSpecified,
null);
}
return _errorRecord;
}
}
private string _PSSnapin = "";
private string _reason = "";
/// <summary>
/// Gets message for this exception.
/// </summary>
public override string Message
{
get
{
if (_errorRecord != null && !_isErrorRecordOriginallyNull)
{
return _errorRecord.ToString();
}
return base.Message;
}
}
#region Serialization
/// <summary>
/// Initiate a PSSnapInException instance.
/// </summary>
/// <param name="info"> Serialization information </param>
/// <param name="context"> Streaming context </param>
protected PSSnapInException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_PSSnapin = info.GetString("PSSnapIn");
_reason = info.GetString("Reason");
CreateErrorRecord();
}
/// <summary>
/// Get object data from serizliation information.
/// </summary>
/// <param name="info"> Serialization information </param>
/// <param name="context"> Streaming context </param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw PSTraceSource.NewArgumentNullException("info");
}
base.GetObjectData(info, context);
info.AddValue("PSSnapIn", _PSSnapin);
info.AddValue("Reason", _reason);
}
#endregion Serialization
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Utils;
#if !FEATURE_CORE_DLR
namespace Microsoft.Scripting.Ast {
#else
namespace System.Linq.Expressions {
#endif
/// <summary>
/// Represents a constructor call.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.NewExpressionProxy))]
public class NewExpression : Expression, IArgumentProvider {
private readonly ConstructorInfo _constructor;
private IList<Expression> _arguments;
private readonly ReadOnlyCollection<MemberInfo> _members;
internal NewExpression(ConstructorInfo constructor, IList<Expression> arguments, ReadOnlyCollection<MemberInfo> members) {
_constructor = constructor;
_arguments = arguments;
_members = members;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type {
get { return _constructor.DeclaringType; }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType {
get { return ExpressionType.New; }
}
/// <summary>
/// Gets the called constructor.
/// </summary>
public ConstructorInfo Constructor {
get { return _constructor; }
}
/// <summary>
/// Gets the arguments to the constructor.
/// </summary>
public ReadOnlyCollection<Expression> Arguments {
get { return ReturnReadOnly(ref _arguments); }
}
Expression IArgumentProvider.GetArgument(int index) {
return _arguments[index];
}
int IArgumentProvider.ArgumentCount {
get {
return _arguments.Count;
}
}
/// <summary>
/// Gets the members that can retrieve the values of the fields that were initialized with constructor arguments.
/// </summary>
public ReadOnlyCollection<MemberInfo> Members {
get { return _members; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor) {
return visitor.VisitNew(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public NewExpression Update(IEnumerable<Expression> arguments) {
if (arguments == Arguments) {
return this;
}
if (Members != null) {
return Expression.New(Constructor, arguments, Members);
}
return Expression.New(Constructor, arguments);
}
}
internal class NewValueTypeExpression : NewExpression {
private readonly Type _valueType;
internal NewValueTypeExpression(Type type, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members)
: base(null, arguments, members) {
_valueType = type;
}
public sealed override Type Type {
get { return _valueType; }
}
}
public partial class Expression {
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> property set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor) {
return New(constructor, (IEnumerable<Expression>)null);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An array of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, params Expression[] arguments) {
return New(constructor, (IEnumerable<Expression>)arguments);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments) {
ContractUtils.RequiresNotNull(constructor, "constructor");
ContractUtils.RequiresNotNull(constructor.DeclaringType, "constructor.DeclaringType");
TypeUtils.ValidateType(constructor.DeclaringType);
var argList = arguments.ToReadOnly();
ValidateArgumentTypes(constructor, ExpressionType.New, ref argList);
return new NewExpression(constructor, argList, null);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <param name="members">An <see cref="IEnumerable{T}"/> of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members) {
ContractUtils.RequiresNotNull(constructor, "constructor");
var memberList = members.ToReadOnly();
var argList = arguments.ToReadOnly();
ValidateNewArgs(constructor, ref argList, ref memberList);
return new NewExpression(constructor, argList, memberList);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <param name="members">An Array of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo[] members) {
return New(constructor, arguments, (IEnumerable<MemberInfo>)members);
}
/// <summary>
/// Creates a <see cref="NewExpression"/> that represents calling the parameterless constructor of the specified type.
/// </summary>
/// <param name="type">A <see cref="Type"/> that has a constructor that takes no arguments. </param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to New and the Constructor property set to the ConstructorInfo that represents the parameterless constructor of the specified type.</returns>
public static NewExpression New(Type type) {
ContractUtils.RequiresNotNull(type, "type");
if (type == typeof(void)) {
throw Error.ArgumentCannotBeOfTypeVoid();
}
ConstructorInfo ci = null;
if (!type.IsValueType) {
ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, ReflectionUtils.EmptyTypes, null);
if (ci == null) {
throw Error.TypeMissingDefaultConstructor(type);
}
return New(ci);
}
return new NewValueTypeExpression(type, EmptyReadOnlyCollection<Expression>.Instance, null);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCollection<Expression> arguments, ref ReadOnlyCollection<MemberInfo> members) {
ParameterInfo[] pis;
if ((pis = constructor.GetParametersCached()).Length > 0) {
if (arguments.Count != pis.Length) {
throw Error.IncorrectNumberOfConstructorArguments();
}
if (arguments.Count != members.Count) {
throw Error.IncorrectNumberOfArgumentsForMembers();
}
Expression[] newArguments = null;
MemberInfo[] newMembers = null;
for (int i = 0, n = arguments.Count; i < n; i++) {
Expression arg = arguments[i];
RequiresCanRead(arg, "argument");
MemberInfo member = members[i];
ContractUtils.RequiresNotNull(member, "member");
if (!TypeUtils.AreEquivalent(member.DeclaringType, constructor.DeclaringType)) {
throw Error.ArgumentMemberNotDeclOnType(member.Name, constructor.DeclaringType.Name);
}
Type memberType;
ValidateAnonymousTypeMember(ref member, out memberType);
if (!TypeUtils.AreReferenceAssignable(memberType, arg.Type)) {
if (!TryQuote(memberType, ref arg)) {
throw Error.ArgumentTypeDoesNotMatchMember(arg.Type, memberType);
}
}
ParameterInfo pi = pis[i];
Type pType = pi.ParameterType;
if (pType.IsByRef) {
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) {
if (!TryQuote(pType, ref arg)) {
throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType);
}
}
if (newArguments == null && arg != arguments[i]) {
newArguments = new Expression[arguments.Count];
for (int j = 0; j < i; j++) {
newArguments[j] = arguments[j];
}
}
if (newArguments != null) {
newArguments[i] = arg;
}
if (newMembers == null && member != members[i]) {
newMembers = new MemberInfo[members.Count];
for (int j = 0; j < i; j++) {
newMembers[j] = members[j];
}
}
if (newMembers != null) {
newMembers[i] = member;
}
}
if (newArguments != null) {
arguments = new TrueReadOnlyCollection<Expression>(newArguments);
}
if (newMembers != null) {
members = new TrueReadOnlyCollection<MemberInfo>(newMembers);
}
} else if (arguments != null && arguments.Count > 0) {
throw Error.IncorrectNumberOfConstructorArguments();
} else if (members != null && members.Count > 0) {
throw Error.IncorrectNumberOfMembersForGivenConstructor();
}
}
private static void ValidateAnonymousTypeMember(ref MemberInfo member, out Type memberType) {
switch (member.MemberType) {
case MemberTypes.Field:
FieldInfo field = member as FieldInfo;
if (field.IsStatic) {
throw Error.ArgumentMustBeInstanceMember();
}
memberType = field.FieldType;
return;
case MemberTypes.Property:
PropertyInfo pi = member as PropertyInfo;
if (!pi.CanRead) {
throw Error.PropertyDoesNotHaveGetter(pi);
}
if (pi.GetGetMethod().IsStatic) {
throw Error.ArgumentMustBeInstanceMember();
}
memberType = pi.PropertyType;
return;
case MemberTypes.Method:
MethodInfo method = member as MethodInfo;
if (method.IsStatic) {
throw Error.ArgumentMustBeInstanceMember();
}
PropertyInfo prop = GetProperty(method);
member = prop;
memberType = prop.PropertyType;
return;
default:
throw Error.ArgumentMustBeFieldInfoOrPropertInfoOrMethod();
}
// don't add code here, we've already returned
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Cassandra.Data.Linq;
using Cassandra.IntegrationTests.SimulacronAPI;
using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder;
using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then;
using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.When;
using Cassandra.IntegrationTests.TestClusterManagement.Simulacron;
using Guid = System.Guid;
#pragma warning disable 618
namespace Cassandra.IntegrationTests.Linq.Structures
{
[AllowFiltering]
[Table(AllDataTypesEntity.TableName)]
public class AllDataTypesEntity : IAllDataTypesEntity
{
public const string TableName = "allDataTypes";
private static readonly IDictionary<string, Func<AllDataTypesEntity, object>> ColumnMappings =
new Dictionary<string, Func<AllDataTypesEntity, object>>
{
{ "boolean_type", entity => entity.BooleanType },
{ "date_time_offset_type", entity => entity.DateTimeOffsetType },
{ "date_time_type", entity => entity.DateTimeType },
{ "decimal_type", entity => entity.DecimalType },
{ "double_type", entity => entity.DoubleType },
{ "float_type", entity => entity.FloatType },
{ "guid_type", entity => entity.GuidType },
{ "int64_type", entity => entity.Int64Type },
{ "int_type", entity => entity.IntType },
{ "list_of_guids_type", entity => entity.ListOfGuidsType },
{ "list_of_strings_type", entity => entity.ListOfStringsType },
{ "map_type_string_long_type", entity => entity.DictionaryStringLongType },
{ "map_type_string_string_type", entity => entity.DictionaryStringStringType },
{ "nullable_date_time_type", entity => entity.NullableDateTimeType },
{ "nullable_int_type", entity => entity.NullableIntType },
{ "nullable_time_uuid_type", entity => entity.NullableTimeUuidType },
{ "string_type", entity => entity.StringType },
{ "time_uuid_type", entity => entity.TimeUuidType }
};
private static readonly IDictionary<string, DataType> ColumnnsToDataTypes =
new Dictionary<string, DataType>
{
{ "boolean_type", DataType.GetDataType(typeof(bool)) },
{ "date_time_offset_type", DataType.GetDataType(typeof(DateTimeOffset)) },
{ "date_time_type", DataType.GetDataType(typeof(DateTime)) },
{ "decimal_type", DataType.GetDataType(typeof(decimal)) },
{ "double_type", DataType.GetDataType(typeof(double)) },
{ "float_type", DataType.GetDataType(typeof(float)) },
{ "guid_type", DataType.GetDataType(typeof(Guid)) },
{ "int_type", DataType.GetDataType(typeof(int)) },
{ "int64_type", DataType.GetDataType(typeof(long)) },
{ "list_of_guids_type", DataType.GetDataType(typeof(List<Guid>)) },
{ "list_of_strings_type", DataType.GetDataType(typeof(List<string>)) },
{ "map_type_string_long_type", DataType.GetDataType(typeof(Dictionary<string, long>)) },
{ "map_type_string_string_type", DataType.GetDataType(typeof(Dictionary<string, string>)) },
{ "nullable_date_time_type", DataType.GetDataType(typeof(DateTime?)) },
{ "nullable_int_type", DataType.GetDataType(typeof(int?)) },
{ "nullable_time_uuid_type", DataType.GetDataType(typeof(TimeUuid?)) },
{ "string_type", DataType.GetDataType(typeof(string)) },
{ "time_uuid_type", DataType.GetDataType(typeof(TimeUuid)) }
};
public const int DefaultListLength = 5;
[PartitionKey]
[Column("string_type")]
public string StringType { get; set; }
[ClusteringKey(1)]
[Column("guid_type")]
public Guid GuidType { get; set; }
[Column("date_time_type")]
public DateTime DateTimeType { get; set; }
[Column("nullable_date_time_type")]
public DateTime? NullableDateTimeType { get; set; }
[Column("date_time_offset_type")]
public DateTimeOffset DateTimeOffsetType { get; set; }
[Column("boolean_type")]
public bool BooleanType { get; set; }
[Column("decimal_type")]
public Decimal DecimalType { get; set; }
[Column("double_type")]
public double DoubleType { get; set; }
[Column("float_type")]
public float FloatType { get; set; }
[Column("nullable_int_type")]
public int? NullableIntType { get; set; }
[Column("int_type")]
public int IntType { get; set; }
[Column("int64_type")]
public Int64 Int64Type { get; set; }
[Column("time_uuid_type")]
public TimeUuid TimeUuidType { get; set; }
[Column("nullable_time_uuid_type")]
public TimeUuid? NullableTimeUuidType { get; set; }
[Column("map_type_string_long_type")]
public Dictionary<string, long> DictionaryStringLongType { get; set; }
[Column("map_type_string_string_type")]
public Dictionary<string, string> DictionaryStringStringType { get; set; }
[Column("list_of_guids_type")]
public List<Guid> ListOfGuidsType { get; set; }
[Column("list_of_strings_type")]
public List<string> ListOfStringsType { get; set; }
public static AllDataTypesEntity GetRandomInstance()
{
AllDataTypesEntity adte = new AllDataTypesEntity();
return (AllDataTypesEntity)AllDataTypesEntityUtil.Randomize(adte);
}
public void AssertEquals(AllDataTypesEntity actualEntity)
{
AllDataTypesEntityUtil.AssertEquals(this, actualEntity);
}
public static List<AllDataTypesEntity> GetDefaultAllDataTypesList()
{
List<AllDataTypesEntity> objectList = new List<AllDataTypesEntity>();
for (int i = 0; i < AllDataTypesEntity.DefaultListLength; i++)
{
objectList.Add(AllDataTypesEntity.GetRandomInstance());
}
return objectList;
}
public static List<AllDataTypesEntity> SetupDefaultTable(ISession session)
{
// drop table if exists, re-create
var table = new Table<AllDataTypesEntity>(session, new Cassandra.Mapping.MappingConfiguration());
table.Create();
List<AllDataTypesEntity> allDataTypesRandomList = AllDataTypesEntity.GetDefaultAllDataTypesList();
//Insert some data
foreach (var allDataTypesEntity in allDataTypesRandomList)
table.Insert(allDataTypesEntity).Execute();
return allDataTypesRandomList;
}
public static (string, DataType)[] GetColumnsWithTypes()
{
return AllDataTypesEntity.ColumnMappings.Keys.Zip(AllDataTypesEntity.ColumnnsToDataTypes, (key, kvp) => (key, kvp.Value)).ToArray();
}
public static RowsResult GetEmptyRowsResult()
{
return new RowsResult(AllDataTypesEntity.GetColumnsWithTypes());
}
public RowsResult CreateRowsResult()
{
return AddRow(AllDataTypesEntity.GetEmptyRowsResult());
}
private IWhenQueryBuilder WithParams(IWhenQueryBuilder when, params string[] columns)
{
return columns.Aggregate(when, (current, c) => current.WithParam(AllDataTypesEntity.ColumnMappings[c](this)));
}
public const string SelectCql =
"SELECT \"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " +
"\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\", \"int64_type\", " +
"\"int_type\", \"list_of_guids_type\", \"list_of_strings_type\", \"map_type_string_long_type\"," +
" \"map_type_string_string_type\", \"nullable_date_time_type\", \"nullable_int_type\", " +
"\"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\" FROM \"allDataTypes\" " +
"WHERE \"string_type\" = ? " +
"ALLOW FILTERING";
public const string SelectCqlDefaultColumnsFormatStr =
"SELECT \"BooleanType\", \"DateTimeOffsetType\", \"DateTimeType\", \"DecimalType\", " +
"\"DictionaryStringLongType\", \"DictionaryStringStringType\", \"DoubleType\", " +
"\"FloatType\", \"GuidType\", \"Int64Type\", \"IntType\", \"ListOfGuidsType\", " +
"\"ListOfStringsType\", \"NullableDateTimeType\", \"NullableIntType\", " +
"\"NullableTimeUuidType\", \"StringType\", \"TimeUuidType\" FROM {0} " +
"WHERE \"StringType\" = ?";
public const string SelectRangeCql =
"SELECT " +
"\"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " +
"\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\"," +
" \"int64_type\", \"int_type\", \"list_of_guids_type\", \"list_of_strings_type\"," +
" \"map_type_string_long_type\", \"map_type_string_string_type\", \"nullable_date_time_type\"," +
" \"nullable_int_type\", \"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\" " +
"FROM \"allDataTypes\" " +
"ALLOW FILTERING";
public void PrimeSelect(SimulacronCluster testCluster)
{
testCluster.PrimeFluent(b => When(testCluster, b).ThenRowsSuccess(CreateRowsResult()));
}
public IWhenFluent When(SimulacronCluster testCluster, IPrimeRequestBuilder builder)
{
return builder.WhenQuery(
AllDataTypesEntity.SelectCql,
when => WithParams(when, "string_type"));
}
public const string InsertCqlDefaultColumnsFormatStr =
"INSERT INTO {0} (" +
"\"BooleanType\", \"DateTimeOffsetType\", \"DateTimeType\", \"DecimalType\", " +
"\"DictionaryStringLongType\", \"DictionaryStringStringType\", \"DoubleType\", " +
"\"FloatType\", \"GuidType\", \"Int64Type\", \"IntType\", \"ListOfGuidsType\", " +
"\"ListOfStringsType\", \"NullableDateTimeType\", \"NullableIntType\", " +
"\"NullableTimeUuidType\", \"StringType\", \"TimeUuidType\") " +
"VALUES (" +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
public const string InsertCqlFormatStr =
"INSERT INTO {0} (\"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " +
"\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\"," +
" \"int_type\", \"int64_type\", \"list_of_guids_type\", \"list_of_strings_type\"," +
" \"map_type_string_long_type\", \"map_type_string_string_type\", \"nullable_date_time_type\"," +
" \"nullable_int_type\", \"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\") " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
public const string InsertCql =
"INSERT INTO \"allDataTypes\" (\"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " +
"\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\"," +
" \"int_type\", \"int64_type\", \"list_of_guids_type\", \"list_of_strings_type\"," +
" \"map_type_string_long_type\", \"map_type_string_string_type\", \"nullable_date_time_type\"," +
" \"nullable_int_type\", \"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\") " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
public void PrimeQuery(SimulacronCluster testCluster, string cql, params string[] paramNames)
{
testCluster.PrimeFluent(
b => b.WhenQuery(cql, when => WithParams(when, paramNames))
.ThenRowsSuccess(CreateRowsResult()));
}
public RowsResult AddRow(RowsResult result)
{
return (RowsResult) result.WithRow(GetColumnValues());
}
public object[] GetColumnValues()
{
return AllDataTypesEntity.ColumnMappings.Values.Select(func => func(this)).ToArray();
}
public static (string, DataType)[] GetDefaultColumns()
{
return new []
{
(nameof(AllDataTypesEntity.BooleanType), DataType.GetDataType(typeof(bool))),
(nameof(AllDataTypesEntity.DateTimeOffsetType), DataType.GetDataType(typeof(DateTimeOffset))),
(nameof(AllDataTypesEntity.DateTimeType), DataType.GetDataType(typeof(DateTime))),
(nameof(AllDataTypesEntity.DecimalType), DataType.GetDataType(typeof(decimal))),
(nameof(AllDataTypesEntity.DictionaryStringLongType), DataType.GetDataType(typeof(Dictionary<string, long>))),
(nameof(AllDataTypesEntity.DictionaryStringStringType), DataType.GetDataType(typeof(Dictionary<string, string>))),
(nameof(AllDataTypesEntity.DoubleType), DataType.GetDataType(typeof(double))),
(nameof(AllDataTypesEntity.FloatType), DataType.GetDataType(typeof(float))),
(nameof(AllDataTypesEntity.GuidType), DataType.GetDataType(typeof(Guid))),
(nameof(AllDataTypesEntity.Int64Type), DataType.GetDataType(typeof(long))),
(nameof(AllDataTypesEntity.IntType), DataType.GetDataType(typeof(int))),
(nameof(AllDataTypesEntity.ListOfGuidsType), DataType.GetDataType(typeof(List<Guid>))),
(nameof(AllDataTypesEntity.ListOfStringsType), DataType.GetDataType(typeof(List<string>))),
(nameof(AllDataTypesEntity.NullableDateTimeType), DataType.GetDataType(typeof(DateTime?))),
(nameof(AllDataTypesEntity.NullableIntType), DataType.GetDataType(typeof(int?))),
(nameof(AllDataTypesEntity.NullableTimeUuidType), DataType.GetDataType(typeof(TimeUuid?))),
(nameof(AllDataTypesEntity.StringType), DataType.GetDataType(typeof(string))),
(nameof(AllDataTypesEntity.TimeUuidType), DataType.GetDataType(typeof(TimeUuid)))
};
}
public object[] GetColumnValuesForDefaultColumns()
{
return new object[]
{
BooleanType,
DateTimeOffsetType,
DateTimeType,
DecimalType,
DictionaryStringLongType,
DictionaryStringStringType,
DoubleType,
FloatType,
GuidType,
Int64Type,
IntType,
ListOfGuidsType,
ListOfStringsType,
NullableDateTimeType,
NullableIntType,
NullableTimeUuidType,
StringType,
TimeUuidType
};
}
public static RowsResult AddRows(IEnumerable<AllDataTypesEntity> data)
{
return data.Aggregate(AllDataTypesEntity.GetEmptyRowsResult(), (current, c) => c.AddRow(current));
}
public static void PrimeCountQuery(SimulacronCluster testCluster, long count)
{
testCluster.PrimeFluent(
b => b.WhenQuery("SELECT count(*) FROM \"allDataTypes\" ALLOW FILTERING")
.ThenRowsSuccess(new [] { "count" }, rows => rows.WithRow(count)));
}
public static void PrimeRangeSelect(SimulacronCluster testCluster, IEnumerable<AllDataTypesEntity> data)
{
testCluster.PrimeFluent(b => b.WhenQuery(AllDataTypesEntity.SelectRangeCql).ThenRowsSuccess(AllDataTypesEntity.AddRows(data)));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit.Abstractions;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Xsl;
using XmlCoreTest.Common;
using OLEDB.Test.ModuleCore;
using System.Runtime.Loader;
namespace System.Xml.Tests
{
public class XsltcTestCaseBase : CTestCase
{
// Generic data for all derived test cases
public String szDefaultNS = "urn:my-object";
public String szEmpty = "";
public String szInvalid = "*?%(){}[]&!@#$";
public String szLongNS = "http://www.microsoft.com/this/is/a/very/long/namespace/uri/to/do/the/api/testing/for/xslt/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/";
public String szLongString = "ThisIsAVeryLongStringToBeStoredAsAVariableToDetermineHowLargeThisBufferForAVariableNameCanBeAndStillFunctionAsExpected";
public String szSimple = "myArg";
public String[] szWhiteSpace = { " ", "\n", "\t", "\r", "\t\n \r\t" };
public String szXslNS = "http://www.w3.org/1999/XSL/Transform";
// Other global variables
protected bool _createFromInputFile = false; // This is intiialized from a parameter passed from LTM as a dimension, that dictates whether the variation is to be created using an input file.
protected bool _isInProc; // Is the current test run in proc or /Host None?
private static ITestOutputHelper s_output;
public XsltcTestCaseBase(ITestOutputHelper output)
{
s_output = output;
}
public static bool xsltcExeFound()
{
try
{
// Verify xsltc.exe is available
XmlCoreTest.Common.XsltVerificationLibrary.SearchPath("xsltc.exe");
}
catch (FileNotFoundException)
{
return false;
}
return true;
}
public override int Init(object objParam)
{
// initialize whether this run is in proc or not
string executionMode = "File";
_createFromInputFile = executionMode.Equals("File");
return 1;
}
protected static void CompareOutput(string expected, Stream actualStream)
{
using (var expectedStream = new MemoryStream(Encoding.UTF8.GetBytes(expected)))
{
CompareOutput(expectedStream, actualStream);
}
}
private static string NormalizeLineEndings(string s)
{
return s.Replace("\r\n", "\n").Replace("\r", "\n");
}
protected static void CompareOutput(Stream expectedStream, Stream actualStream, int count = 0)
{
actualStream.Seek(0, SeekOrigin.Begin);
using (var expectedReader = new StreamReader(expectedStream))
using (var actualReader = new StreamReader(actualStream))
{
for (int i = 0; i < count; i++)
{
actualReader.ReadLine();
expectedReader.ReadLine();
}
string actual = NormalizeLineEndings(actualReader.ReadToEnd());
string expected = NormalizeLineEndings(expectedReader.ReadToEnd());
if (actual.Equals(expected))
{
return;
}
throw new CTestFailedException("Output was not as expected.", actual, expected, null);
}
}
protected bool LoadPersistedTransformAssembly(string asmName, string typeName, string baselineFile, bool pdb)
{
var other = (AssemblyLoader)Activator.CreateInstance(typeof(AssemblyLoader), typeof(AssemblyLoader).FullName);
bool result = other.Verify(asmName, typeName, baselineFile, pdb);
return result;
}
protected string ReplaceCurrentWorkingDirectory(string commandLine)
{
return commandLine.Replace(@"$(CurrentWorkingDirectory)", XsltcModule.TargetDirectory);
}
protected bool ShouldSkip(object[] varParams)
{
// some test only applicable in English environment, so skip them if current cultral is not english
bool isCultralEnglish = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToLower() == "en";
if (isCultralEnglish)
{
return false;
}
// look up key word "EnglishOnly", if hit return true, otherwise false
return varParams != null && varParams.Any(o => o.ToString() == "EnglishOnly");
}
protected void VerifyTest(String cmdLine, String baselineFile, bool loadFromFile)
{
VerifyTest(cmdLine, String.Empty, false, String.Empty, baselineFile, loadFromFile);
}
protected void VerifyTest(String cmdLine, String asmName, bool asmCreated, String typeName, String baselineFile, bool loadFromFile)
{
VerifyTest(cmdLine, asmName, asmCreated, typeName, String.Empty, false, baselineFile, loadFromFile);
}
protected void VerifyTest(String cmdLine, String asmName, bool asmCreated, String typeName, String pdbName, bool pdbCreated, String baselineFile, bool loadFromFile)
{
VerifyTest(cmdLine, asmName, asmCreated, typeName, pdbName, pdbCreated, baselineFile, true, loadFromFile);
}
protected void VerifyTest(String cmdLine, String asmName, bool asmCreated, String typeName, String pdbName, bool pdbCreated, String baselineFile, bool runAssemblyVerification, bool loadFromFile)
{
string targetDirectory = XsltcModule.TargetDirectory;
string output = asmCreated ? TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, true, targetDirectory) : TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, false, targetDirectory);
//verify assembly file existence
if (asmName != null && String.CompareOrdinal(String.Empty, asmName) != 0)
{
if (File.Exists(GetPath(asmName)) != asmCreated)
{
throw new CTestFailedException("Assembly File Creation Check: FAILED");
}
}
//verify pdb existence
if (pdbName != null && String.CompareOrdinal(String.Empty, pdbName) != 0)
{
if (File.Exists(GetPath(pdbName)) != pdbCreated)
{
throw new CTestFailedException("PDB File Creation Check: FAILED");
}
}
if (asmCreated && !String.IsNullOrEmpty(typeName))
{
if (!LoadPersistedTransformAssembly(GetPath(asmName), typeName, baselineFile, pdbCreated))
{
throw new CTestFailedException("Assembly loaded failed");
}
}
else
{
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms) { AutoFlush = true })
using (var expected = new FileStream(GetPath(baselineFile), FileMode.Open, FileAccess.Read))
{
sw.Write(output);
CompareOutput(expected, ms, 4);
}
}
SafeDeleteFile(GetPath(pdbName));
SafeDeleteFile(GetPath(asmName));
return;
}
private static void SafeDeleteFile(string fileName)
{
try
{
var fileInfo = new FileInfo(fileName);
if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
{
fileInfo.Directory.Create();
}
if (fileInfo.Exists)
{
fileInfo.Delete();
}
}
catch (ArgumentException)
{
}
catch (PathTooLongException)
{
}
catch (Exception e)
{
s_output.WriteLine(e.Message);
}
}
// Used to generate a unique name for an input file, and write that file, based on a specified command line.
private string CreateInputFile(string commandLine)
{
string fileName = Path.Combine(XsltcModule.TargetDirectory, Guid.NewGuid() + ".ipf");
File.WriteAllText(fileName, commandLine);
return fileName;
}
private string GetPath(string fileName)
{
return XsltcModule.TargetDirectory + Path.DirectorySeparatorChar + fileName;
}
/// <summary>
/// Currently this method supports only 1 input file. For variations that require more than one input file to test
/// @file
/// functionality, custom-craft and write those input files in the body of the variation method, then pass an
/// appropriate
/// commandline such as @file1 @file2 @file3, along with createFromInputFile = false.
/// </summary>
/// <param name="commandLine"></param>
/// <param name="createFromInputFile"></param>
/// <param name="expectedToSucceed"></param>
/// <param name="targetDirectory"></param>
/// <returns></returns>
private string TryCreatePersistedTransformAssembly(string commandLine, bool createFromInputFile, bool expectedToSucceed, string targetDirectory)
{
// If createFromInputFile is specified, create an input file now that the compiler can consume.
string processArguments = createFromInputFile ? "@" + CreateInputFile(commandLine) : commandLine;
var processStartInfo = new ProcessStartInfo
{
FileName = XsltVerificationLibrary.SearchPath("xsltc.exe"),
Arguments = processArguments,
//WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = targetDirectory
};
// Call xsltc to create persistant assembly.
var compilerProcess = new Process
{
StartInfo = processStartInfo
};
compilerProcess.Start();
string output = compilerProcess.StandardOutput.ReadToEnd();
compilerProcess.WaitForExit();
if (createFromInputFile)
{
SafeDeleteFile(processArguments.Substring(1));
}
if (expectedToSucceed)
{
// The Assembly was created successfully
if (compilerProcess.ExitCode == 0)
{
return output;
}
throw new CTestFailedException("Failed to create assembly: " + output);
}
return output;
}
public class AssemblyLoader //: MarshalByRefObject
{
public AssemblyLoader(string asmName)
{
}
public bool Verify(string asmName, string typeName, string baselineFile, bool pdb)
{
try
{
var xslt = new XslCompiledTransform();
Assembly xsltasm = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(asmName));
if (xsltasm == null)
{
//_output.WriteLine("Could not load file");
return false;
}
Type t = xsltasm.GetType(typeName);
if (t == null)
{
//_output.WriteLine("No type loaded");
return false;
}
xslt.Load(t);
var inputXml = new XmlDocument();
using (var stream = new MemoryStream())
using (var sw = new StreamWriter(stream) { AutoFlush = true })
{
inputXml.LoadXml("<foo><bar>Hello, world!</bar></foo>");
xslt.Transform(inputXml, null, sw);
if (!XsltVerificationLibrary.CompareXml(Path.Combine(XsltcModule.TargetDirectory, baselineFile), stream))
{
//_output.WriteLine("Baseline file comparison failed");
return false;
}
}
return true;
}
catch (Exception e)
{
s_output.WriteLine(e.Message);
return false;
}
}
private static byte[] loadFile(string filename)
{
using (var fs = new FileStream(filename, FileMode.Open))
{
var buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
return buffer;
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System.Runtime.Serialization;
////using System.ServiceModel.Channels;
using System.Globalization;
using System.Runtime.Serialization.Diagnostics.Application;
namespace System.Xml
{
static class XmlExceptionHelper
{
static void ThrowXmlException(XmlDictionaryReader reader, string res)
{
ThrowXmlException(reader, res, null);
}
static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1)
{
ThrowXmlException(reader, res, arg1, null);
}
static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2)
{
ThrowXmlException(reader, res, arg1, arg2, null);
}
static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2, string arg3)
{
string s = SR.GetString(res, arg1, arg2, arg3);
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo != null && lineInfo.HasLineInfo())
{
s += " " + SR.GetString(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
}
if (TD.ReaderQuotaExceededIsEnabled())
{
TD.ReaderQuotaExceeded(s);
}
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s));
}
static public void ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
{
string s = exception.Message;
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo != null && lineInfo.HasLineInfo())
{
s += " " + SR.GetString(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
}
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s));
}
static string GetName(string prefix, string localName)
{
if (prefix.Length == 0)
return localName;
else
return string.Concat(prefix, ":", localName);
}
static string GetWhatWasFound(XmlDictionaryReader reader)
{
if (reader.EOF)
return SR.GetString(SR.XmlFoundEndOfFile);
switch (reader.NodeType)
{
case XmlNodeType.Element:
return SR.GetString(SR.XmlFoundElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
case XmlNodeType.EndElement:
return SR.GetString(SR.XmlFoundEndElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return SR.GetString(SR.XmlFoundText, reader.Value);
case XmlNodeType.Comment:
return SR.GetString(SR.XmlFoundComment, reader.Value);
case XmlNodeType.CDATA:
return SR.GetString(SR.XmlFoundCData, reader.Value);
}
return SR.GetString(SR.XmlFoundNodeType, reader.NodeType);
}
static public void ThrowStartElementExpected(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader));
}
static public void ThrowStartElementExpected(XmlDictionaryReader reader, string name)
{
ThrowXmlException(reader, SR.XmlStartElementNameExpected, name, GetWhatWasFound(reader));
}
static public void ThrowStartElementExpected(XmlDictionaryReader reader, string localName, string ns)
{
ThrowXmlException(reader, SR.XmlStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader));
}
static public void ThrowStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns)
{
ThrowStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns));
}
static public void ThrowFullStartElementExpected(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlFullStartElementExpected, GetWhatWasFound(reader));
}
static public void ThrowFullStartElementExpected(XmlDictionaryReader reader, string name)
{
ThrowXmlException(reader, SR.XmlFullStartElementNameExpected, name, GetWhatWasFound(reader));
}
static public void ThrowFullStartElementExpected(XmlDictionaryReader reader, string localName, string ns)
{
ThrowXmlException(reader, SR.XmlFullStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader));
}
static public void ThrowFullStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns)
{
ThrowFullStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns));
}
static public void ThrowEndElementExpected(XmlDictionaryReader reader, string localName, string ns)
{
ThrowXmlException(reader, SR.XmlEndElementExpected, localName, ns, GetWhatWasFound(reader));
}
static public void ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, int maxStringContentLength)
{
ThrowXmlException(reader, SR.XmlMaxStringContentLengthExceeded, maxStringContentLength.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowMaxArrayLengthExceeded(XmlDictionaryReader reader, int maxArrayLength)
{
ThrowXmlException(reader, SR.XmlMaxArrayLengthExceeded, maxArrayLength.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(XmlDictionaryReader reader, int maxQuota)
{
ThrowXmlException(reader, SR.XmlMaxArrayLengthOrMaxItemsQuotaExceeded, maxQuota.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowMaxDepthExceeded(XmlDictionaryReader reader, int maxDepth)
{
ThrowXmlException(reader, SR.XmlMaxDepthExceeded, maxDepth.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowMaxBytesPerReadExceeded(XmlDictionaryReader reader, int maxBytesPerRead)
{
ThrowXmlException(reader, SR.XmlMaxBytesPerReadExceeded, maxBytesPerRead.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowMaxNameTableCharCountExceeded(XmlDictionaryReader reader, int maxNameTableCharCount)
{
ThrowXmlException(reader, SR.XmlMaxNameTableCharCountExceeded, maxNameTableCharCount.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowBase64DataExpected(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlBase64DataExpected, GetWhatWasFound(reader));
}
static public void ThrowUndefinedPrefix(XmlDictionaryReader reader, string prefix)
{
ThrowXmlException(reader, SR.XmlUndefinedPrefix, prefix);
}
static public void ThrowProcessingInstructionNotSupported(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlProcessingInstructionNotSupported);
}
static public void ThrowInvalidXml(XmlDictionaryReader reader, byte b)
{
ThrowXmlException(reader, SR.XmlInvalidXmlByte, b.ToString("X2", CultureInfo.InvariantCulture));
}
static public void ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlUnexpectedEndOfFile, ((XmlBaseReader)reader).GetOpenElements());
}
static public void ThrowUnexpectedEndElement(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlUnexpectedEndElement);
}
static public void ThrowTokenExpected(XmlDictionaryReader reader, string expected, char found)
{
ThrowXmlException(reader, SR.XmlTokenExpected, expected, found.ToString());
}
static public void ThrowTokenExpected(XmlDictionaryReader reader, string expected, string found)
{
ThrowXmlException(reader, SR.XmlTokenExpected, expected, found);
}
static public void ThrowInvalidCharRef(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlInvalidCharRef);
}
static public void ThrowTagMismatch(XmlDictionaryReader reader, string expectedPrefix, string expectedLocalName, string foundPrefix, string foundLocalName)
{
ThrowXmlException(reader, SR.XmlTagMismatch, GetName(expectedPrefix, expectedLocalName), GetName(foundPrefix, foundLocalName));
}
static public void ThrowDuplicateXmlnsAttribute(XmlDictionaryReader reader, string localName, string ns)
{
string name;
if (localName.Length == 0)
name = "xmlns";
else
name = "xmlns:" + localName;
ThrowXmlException(reader, SR.XmlDuplicateAttribute, name, name, ns);
}
static public void ThrowDuplicateAttribute(XmlDictionaryReader reader, string prefix1, string prefix2, string localName, string ns)
{
ThrowXmlException(reader, SR.XmlDuplicateAttribute, GetName(prefix1, localName), GetName(prefix2, localName), ns);
}
static public void ThrowInvalidBinaryFormat(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlInvalidFormat);
}
static public void ThrowInvalidRootData(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlInvalidRootData);
}
static public void ThrowMultipleRootElements(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlMultipleRootElements);
}
static public void ThrowDeclarationNotFirst(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlDeclNotFirst);
}
static public void ThrowConversionOverflow(XmlDictionaryReader reader, string value, string type)
{
ThrowXmlException(reader, SR.XmlConversionOverflow, value, type);
}
static public void ThrowXmlDictionaryStringIDOutOfRange(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlDictionaryStringIDRange, XmlDictionaryString.MinKey.ToString(NumberFormatInfo.CurrentInfo), XmlDictionaryString.MaxKey.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowXmlDictionaryStringIDUndefinedStatic(XmlDictionaryReader reader, int key)
{
ThrowXmlException(reader, SR.XmlDictionaryStringIDUndefinedStatic, key.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowXmlDictionaryStringIDUndefinedSession(XmlDictionaryReader reader, int key)
{
ThrowXmlException(reader, SR.XmlDictionaryStringIDUndefinedSession, key.ToString(NumberFormatInfo.CurrentInfo));
}
static public void ThrowEmptyNamespace(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlEmptyNamespaceRequiresNullPrefix);
}
static public XmlException CreateConversionException(string value, string type, Exception exception)
{
return new XmlException(SR.GetString(SR.XmlInvalidConversion, value, type), exception);
}
static public XmlException CreateEncodingException(byte[] buffer, int offset, int count, Exception exception)
{
return CreateEncodingException(new System.Text.UTF8Encoding(false, false).GetString(buffer, offset, count), exception);
}
static public XmlException CreateEncodingException(string value, Exception exception)
{
return new XmlException(SR.GetString(SR.XmlInvalidUTF8Bytes, value), exception);
}
}
}
| |
// 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_WrongNestedThis:
codeStr = SR.WrongNestedThis;
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_ReturnNotLValue:
codeStr = SR.ReturnNotLValue;
break;
case ErrorCode.ERR_AssgReadonly2:
codeStr = SR.AssgReadonly2;
break;
case ErrorCode.ERR_AssgReadonlyStatic2:
codeStr = SR.AssgReadonlyStatic2;
break;
case ErrorCode.ERR_BadCtorArgCount:
codeStr = SR.BadCtorArgCount;
break;
case ErrorCode.ERR_NonInvocableMemberCalled:
codeStr = SR.NonInvocableMemberCalled;
break;
case ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument:
codeStr = SR.NamedArgumentSpecificationBeforeFixedArgument;
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;
default:
// means missing resources match the code entry
Debug.Assert(false, "Missing resources for the error " + code.ToString());
codeStr = null;
break;
}
return codeStr;
}
public static string GetMessage(MessageID id)
{
return id.ToString();
}
}
}
| |
using System;
using System.Net;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Owin {
public class InvalidRequestException : Exception {
public InvalidRequestException(string message) : base(message) { }
}
public class ParamsDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IDictionary<TKey, TValue> {
public ParamsDictionary() : base() { }
public TValue this[TKey key] {
get {
try {
return base[key];
} catch (KeyNotFoundException) {
return default(TValue);
}
}
set { base[key] = value; }
}
}
public class Request : IRequest {
static readonly List<string> FormDataMediaTypes = new List<string> { "application/x-www-form-urlencoded", "multipart/form-data" };
public IRequest InnerRequest;
public Request() { }
public Request(IRequest innerRequest) {
InnerRequest = innerRequest;
}
#region IRequest implementation which simply wraps InnerRequest
// It makes sense for Owin.Request to implement IRequest.
// We may eventually override some of the IRequest implementation
// but, for now, we simply proxy everything to the InnerRequest
public virtual string Method { get { return InnerRequest.Method; } }
public virtual string Uri { get { return InnerRequest.Uri; } }
public virtual IDictionary<string, IEnumerable<string>> Headers { get { return InnerRequest.Headers; } }
public virtual IDictionary<string, object> Items { get { return InnerRequest.Items; } }
public virtual IAsyncResult BeginReadBody(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
return InnerRequest.BeginReadBody(buffer, offset, count, callback, state);
}
public virtual int EndReadBody(IAsyncResult result) { return InnerRequest.EndReadBody(result); }
#endregion
public virtual string BasePath {
get { return InnerRequest.Items["owin.base_path"].ToString(); }
}
public virtual string Scheme {
get { return InnerRequest.Items["owin.url_scheme"].ToString(); }
}
public virtual string Host {
get { return StringItemOrNull("owin.server_name"); } // TODO return Host: header if definted?
}
public virtual int Port {
get {
string port = StringItemOrNull("owin.server_port");
return (port == null) ? 0 : int.Parse(port);
}
}
public virtual string Protocol {
get { return StringItemOrNull("owin.request_protocol"); }
}
public virtual IPEndPoint IPEndPoint {
get { return Items["owin.remote_endpoint"] as IPEndPoint; }
}
public virtual IPAddress IPAddress {
get { return IPEndPoint.Address; }
}
public virtual string PathInfo {
get {
if (Uri.Contains("?"))
return Uri.Substring(0, Uri.IndexOf("?")); // grab everything before a ?
else
return Uri;
}
}
public virtual string Path {
get { return BasePath + PathInfo; }
}
public virtual string Url {
get {
string url = Scheme + "://" + Host;
// If the port is non-standard, include it in the Url
if ((Scheme == "http" && Port != 80) || (Scheme == "https" && Port != 443))
url += ":" + Port.ToString();
url += BasePath + Uri;
return url;
}
}
/// <summary>Returns the first value of the given header or null if the header does not exist</summary>
public virtual string GetHeader(string key) {
key = key.ToLower(); // <--- instead of doing this everywhere, it would be ideal if the Headers IDictionary could do this by itself!
if (!Headers.ContainsKey(key))
return null;
else {
string value = null;
foreach (string headerValue in Headers[key]) {
value = headerValue;
break;
}
return value;
}
}
public virtual string ContentType {
get { return GetHeader("content-type"); }
}
public virtual bool HasFormData {
get {
if (FormDataMediaTypes.Contains(ContentType))
return true;
else if (Method == "POST" && ContentType == null)
return true;
else
return false;
}
}
public virtual bool IsGet { get { return Method.ToUpper() == "GET"; } }
public virtual bool IsPost { get { return Method.ToUpper() == "POST"; } }
public virtual bool IsPut { get { return Method.ToUpper() == "PUT"; } }
public virtual bool IsDelete { get { return Method.ToUpper() == "DELETE"; } }
public virtual bool IsHead { get { return Method.ToUpper() == "HEAD"; } }
/// <summary>Get the raw value of the QueryString</summary>
/// <remarks>
/// In OWIN, we include the QueryString in the Uri if it was provided.
///
/// This grabs the QueryString from the Uri unless the server provides
/// us with a QUERY_STRING.
/// </remarks>
public virtual string QueryString {
get { return new Uri(Url).Query.Replace("?", ""); }
}
// alias to Params
public virtual string this[string key] {
get { return Params[key]; }
}
public virtual IDictionary<string, string> Params {
get {
Dictionary<string, string> getAndPost = new ParamsDictionary<string, string>();
foreach (KeyValuePair<string, string> item in GET)
getAndPost.Add(item.Key, item.Value);
foreach (KeyValuePair<string, string> item in POST)
getAndPost.Add(item.Key, item.Value);
return getAndPost;
}
}
public virtual IDictionary<string, string> GET {
get {
IDictionary<string, string> get = new ParamsDictionary<string, string>();
NameValueCollection queryStrings = HttpUtility.ParseQueryString(QueryString);
foreach (string key in queryStrings)
get.Add(key, queryStrings[key]);
return get;
}
}
public virtual IDictionary<string, string> POST {
get {
IDictionary<string, string> post = new ParamsDictionary<string, string>();
if (!HasFormData) return post;
NameValueCollection postVariables = HttpUtility.ParseQueryString(Body);
foreach (string key in postVariables)
if (key != null)
post.Add(key, postVariables[key]);
return post;
}
}
// blocks while it gets the full body
public virtual string Body {
get { return Encoding.UTF8.GetString(BodyBytes); } // TODO should be able to change the encoding used (?)
}
// blocks while it gets the full body
public virtual byte[] BodyBytes {
get { return GetAllBodyBytes(); }
}
public virtual byte[] GetAllBodyBytes() {
return GetAllBodyBytes(1000); // how many bytes to get per call to BeginReadBody
}
public virtual byte[] GetAllBodyBytes(int batchSize) {
List<byte> allBytes = new List<byte>();
bool done = false;
int offset = 0;
while (!done) {
byte[] buffer = new byte[batchSize];
IAsyncResult result = InnerRequest.BeginReadBody(buffer, offset, batchSize, null, null);
int bytesRead = InnerRequest.EndReadBody(result);
if (bytesRead == 0)
done = true;
else {
offset += batchSize;
allBytes.AddRange(buffer);
}
}
return RemoveTrainingBytes(allBytes.ToArray());
}
// private
byte[] RemoveTrainingBytes(byte[] bytes) {
if (bytes.Length == 0)
return bytes;
int i = bytes.Length - 1;
while (bytes[i] == 0)
i--;
if (i == 0)
return bytes;
else {
byte[] newBytes = new byte[i + 1];
Array.Copy(bytes, newBytes, i + 1);
return newBytes;
}
}
string StringItemOrNull(string key) {
if (InnerRequest.Items.ContainsKey(key)) {
return InnerRequest.Items[key].ToString();
} else
return null;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BaseCodeDomTreeGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/**********************************************
Class hierarchy:
BaseCodeDomTreeGenerator
BaseTemplateCodeDomTreeGenerator
TemplateControlCodeDomTreeGenerator
PageCodeDomTreeGenerator
UserControlCodeDomTreeGenerator
PageThemeCodeDomTreeGenerator
ApplicationFileCodeDomTreeGenerator
***********************************************/
namespace System.Web.Compilation {
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.IO;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.Web.Caching;
using System.Web.Util;
using System.Web.UI;
using System.Web.SessionState;
using System.CodeDom;
using System.CodeDom.Compiler;
using Util = System.Web.UI.Util;
using System.Web.Hosting;
using System.Web.Profile;
using System.Web.Configuration;
using System.Globalization;
internal abstract class BaseCodeDomTreeGenerator {
protected CodeDomProvider _codeDomProvider;
protected CodeCompileUnit _codeCompileUnit;
private CodeNamespace _sourceDataNamespace;
protected CodeTypeDeclaration _sourceDataClass;
protected CodeTypeDeclaration _intermediateClass;
private CompilerParameters _compilParams;
protected StringResourceBuilder _stringResourceBuilder;
protected bool _usingVJSCompiler;
private static IDictionary _generatedColumnOffsetDictionary;
private VirtualPath _virtualPath;
// The constructors
protected CodeConstructor _ctor;
protected CodeTypeReferenceExpression _classTypeExpr;
internal const string defaultNamespace = "ASP";
// Used for things that we don't want the user to see
internal const string internalAspNamespace = "__ASP";
private const string initializedFieldName = "__initialized";
private const string _dummyVariable = "__dummyVar";
private const int _defaultColumnOffset = 4;
private TemplateParser _parser;
TemplateParser Parser { get { return _parser; } }
// We generate different code for the designer
protected bool _designerMode;
internal void SetDesignerMode() { _designerMode = true; }
private IDictionary _linePragmasTable;
internal IDictionary LinePragmasTable { get { return _linePragmasTable; } }
// Used to generate indexed into the LinePragmasTable
private int _pragmaIdGenerator=1;
private static bool _urlLinePragmas;
static BaseCodeDomTreeGenerator() {
CompilationSection config = MTConfigUtil.GetCompilationAppConfig();
_urlLinePragmas = config.UrlLinePragmas;
}
#if DBG
private bool _addedDebugComment;
#endif
#if DBG
protected void AppendDebugComment(CodeStatementCollection statements) {
if (!_addedDebugComment) {
_addedDebugComment = true;
StringBuilder debugComment = new StringBuilder();
debugComment.Append("\r\n");
debugComment.Append("** DEBUG INFORMATION **");
debugComment.Append("\r\n");
statements.Add(new CodeCommentStatement(debugComment.ToString()));
}
}
#endif
internal /*public*/ CodeCompileUnit GetCodeDomTree(CodeDomProvider codeDomProvider,
StringResourceBuilder stringResourceBuilder, VirtualPath virtualPath) {
Debug.Assert(_codeDomProvider == null && _stringResourceBuilder == null);
_codeDomProvider = codeDomProvider;
_stringResourceBuilder = stringResourceBuilder;
_virtualPath = virtualPath;
// Build the data tree that needs to be compiled
if (!BuildSourceDataTree())
return null;
// Tell the root builder that the CodeCompileUnit is now fully complete
if (Parser.RootBuilder != null) {
Parser.RootBuilder.OnCodeGenerationComplete();
}
return _codeCompileUnit;
}
protected /*public*/ CompilerParameters CompilParams { get { return _compilParams; } }
internal string GetInstantiatableFullTypeName() {
// In updatable mode, we never build the final type, so return null
if (PrecompilingForUpdatableDeployment)
return null;
return Util.MakeFullTypeName(_sourceDataNamespace.Name, _sourceDataClass.Name);
}
internal string GetIntermediateFullTypeName() {
return Util.MakeFullTypeName(Parser.BaseTypeNamespace, _intermediateClass.Name);
}
/*
* Set some fields that are needed for code generation
*/
protected BaseCodeDomTreeGenerator(TemplateParser parser) {
_parser = parser;
Debug.Assert(Parser.BaseType != null);
}
protected void ApplyEditorBrowsableCustomAttribute(CodeTypeMember member) {
Debug.Assert(_designerMode, "This method should only be used in design mode.");
// Generate EditorBrowsableAttribute to hide the generated methods from the tool
// [EditorBrowsable(EditorBrowsableState.Never)]
CodeAttributeDeclaration editorBrowsableAttribute = new CodeAttributeDeclaration();
editorBrowsableAttribute.Name = typeof(EditorBrowsableAttribute).FullName;
editorBrowsableAttribute.Arguments.Add(new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), "Never")));
member.CustomAttributes.Add(editorBrowsableAttribute);
}
/// <devdoc>
/// Create a name for the generated class
/// </devdoc>
protected virtual string GetGeneratedClassName() {
string className;
// If the user specified the class name, just use that
if (Parser.GeneratedClassName != null)
return Parser.GeneratedClassName;
// Use the input file name to generate the class name
className = _virtualPath.FileName;
// Prepend the class name with the directory path within the app (DevDiv 42063)
string appRelVirtualDir = _virtualPath.Parent.AppRelativeVirtualPathStringOrNull;
if (appRelVirtualDir != null) {
Debug.Assert(UrlPath.IsAppRelativePath(appRelVirtualDir));
className = appRelVirtualDir.Substring(2) + className;
}
// Change invalid chars to underscores
className = Util.MakeValidTypeNameFromString(className);
// Make it lower case to make it more predictable (VSWhidbey 503369)
className = className.ToLowerInvariant();
// If it's the same as the base type name, prepend it with an underscore to prevent
// a compile error.
string baseTypeName = Parser.BaseTypeName != null ? Parser.BaseTypeName : Parser.BaseType.Name;
if (StringUtil.EqualsIgnoreCase(className, baseTypeName)) {
className = "_" + className;
}
return className;
}
internal static bool IsAspNetNamespace(string ns) {
return (ns == defaultNamespace);
}
private bool PrecompilingForUpdatableDeployment {
get {
// For global.asax, this never applies
if (IsGlobalAsaxGenerator)
return false;
return BuildManager.PrecompilingForUpdatableDeployment;
}
}
private bool BuildSourceDataTree() {
_compilParams = Parser.CompilParams;
_codeCompileUnit = new CodeCompileUnit();
_codeCompileUnit.UserData["AllowLateBound"] = !Parser.FStrict;
_codeCompileUnit.UserData["RequireVariableDeclaration"] = Parser.FExplicit;
// Set a flag indicating if we're using the VJS compiler. See comment in BuildExtractMethod for more information.
_usingVJSCompiler = (_codeDomProvider.FileExtension == ".jsl");
_sourceDataNamespace = new CodeNamespace(Parser.GeneratedNamespace);
string generatedClassName = GetGeneratedClassName();
if (Parser.BaseTypeName != null) {
Debug.Assert(Parser.CodeFileVirtualPath != null);
// This is the case where the page has a CodeFile attribute
CodeNamespace intermediateNamespace = new CodeNamespace(Parser.BaseTypeNamespace);
_codeCompileUnit.Namespaces.Add(intermediateNamespace);
_intermediateClass = new CodeTypeDeclaration(Parser.BaseTypeName);
// Specify the base class in the UserData in case the CodeDom provider needs
// to reflect on it when generating code from the CodeCompileUnit (VSWhidbey 475294)
// In design mode, use the default base type (e.g. Page or UserControl) to avoid
// ending up with a type that can't be serialized to the Venus domain (VSWhidbey 545535)
if (_designerMode)
_intermediateClass.UserData["BaseClassDefinition"] = Parser.DefaultBaseType;
else
_intermediateClass.UserData["BaseClassDefinition"] = Parser.BaseType;
intermediateNamespace.Types.Add(_intermediateClass);
// Generate a partial class
_intermediateClass.IsPartial = true;
// Unless we're precompiling for updatable deployment, create the derived class
if (!PrecompilingForUpdatableDeployment) {
_sourceDataClass = new CodeTypeDeclaration(generatedClassName);
// VSWhidbey 411701. Always use global type reference for the baseType
// when codefile is present.
_sourceDataClass.BaseTypes.Add(CodeDomUtility.BuildGlobalCodeTypeReference(
Util.MakeFullTypeName(Parser.BaseTypeNamespace, Parser.BaseTypeName)));
_sourceDataNamespace.Types.Add(_sourceDataClass);
}
}
else {
// The page is not using code besides
_intermediateClass = new CodeTypeDeclaration(generatedClassName);
_intermediateClass.BaseTypes.Add(CodeDomUtility.BuildGlobalCodeTypeReference(Parser.BaseType));
_sourceDataNamespace.Types.Add(_intermediateClass);
// There is only one class, so make both fields point to the same thing
_sourceDataClass = _intermediateClass;
}
// Add the derived class namespace after the base partial class so C# parser
// can still parse the code correctly in case the derived class contains error.
// VSWhidbey 397646
_codeCompileUnit.Namespaces.Add(_sourceDataNamespace);
// We don't generate any code during updatable precompilation of a single (inline) page,
// except for global.asax
if (PrecompilingForUpdatableDeployment && Parser.CodeFileVirtualPath == null)
return false;
// Add metadata attributes to the class
GenerateClassAttributes();
// In VB, always import Microsoft.VisualBasic (VSWhidbey 256475)
if (_codeDomProvider is Microsoft.VisualBasic.VBCodeProvider)
_sourceDataNamespace.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
// Add all the namespaces
if (Parser.NamespaceEntries != null) {
foreach (NamespaceEntry entry in Parser.NamespaceEntries.Values) {
// Create a line pragma if available
CodeLinePragma linePragma;
if (entry.VirtualPath != null) {
linePragma = CreateCodeLinePragma(entry.VirtualPath, entry.Line);
}
else {
linePragma = null;
}
CodeNamespaceImport nsi = new CodeNamespaceImport(entry.Namespace);
nsi.LinePragma = linePragma;
_sourceDataNamespace.Imports.Add(nsi);
}
}
if (_sourceDataClass != null) {
// We need to generate a global reference to avoid ambiguities (VSWhidbey 284936)
string fullClassName = Util.MakeFullTypeName(_sourceDataNamespace.Name, _sourceDataClass.Name);
CodeTypeReference classTypeRef = CodeDomUtility.BuildGlobalCodeTypeReference(fullClassName);
// Since this is needed in several places, store it in a member variable
_classTypeExpr = new CodeTypeReferenceExpression(classTypeRef);
}
// Add the implemented interfaces
GenerateInterfaces();
// Build various properties, fields, methods
BuildMiscClassMembers();
// Build the default constructors
if (!_designerMode && _sourceDataClass != null) {
_ctor = new CodeConstructor();
AddDebuggerNonUserCodeAttribute(_ctor);
_sourceDataClass.Members.Add(_ctor);
BuildDefaultConstructor();
}
return true;
}
/*
* Add metadata attributes to the class
*/
protected virtual void GenerateClassAttributes() {
// If this is a debuggable page, generate a
// CompilerGlobalScopeAttribute attribute (ASURT 33027)
if (CompilParams.IncludeDebugInformation && _sourceDataClass != null) {
CodeAttributeDeclaration attribDecl = new CodeAttributeDeclaration(
"System.Runtime.CompilerServices.CompilerGlobalScopeAttribute");
_sourceDataClass.CustomAttributes.Add(attribDecl);
}
}
/*
* Generate the list of implemented interfaces
*/
protected virtual void GenerateInterfaces() {
if (Parser.ImplementedInterfaces != null) {
foreach (Type t in Parser.ImplementedInterfaces) {
_intermediateClass.BaseTypes.Add(new CodeTypeReference(t));
}
}
}
/*
* Build first-time intialization statements
*/
protected virtual void BuildInitStatements(CodeStatementCollection trueStatements, CodeStatementCollection topLevelStatements) {
}
/*
* Build the default constructor
*/
protected virtual void BuildDefaultConstructor() {
_ctor.Attributes &= ~MemberAttributes.AccessMask;
_ctor.Attributes |= MemberAttributes.Public;
// private static bool __initialized;
CodeMemberField initializedField = new CodeMemberField(typeof(bool), initializedFieldName);
initializedField.Attributes |= MemberAttributes.Static;
_sourceDataClass.Members.Add(initializedField);
// if (__intialized == false)
CodeConditionStatement initializedCondition = new CodeConditionStatement();
initializedCondition.Condition = new CodeBinaryOperatorExpression(
new CodeFieldReferenceExpression(
_classTypeExpr,
initializedFieldName),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(false));
this.BuildInitStatements(initializedCondition.TrueStatements, _ctor.Statements);
initializedCondition.TrueStatements.Add(new CodeAssignStatement(
new CodeFieldReferenceExpression(
_classTypeExpr,
initializedFieldName),
new CodePrimitiveExpression(true)));
// i.e. __intialized = true;
_ctor.Statements.Add(initializedCondition);
}
/*
* Build various properties, fields, methods
*/
protected virtual void BuildMiscClassMembers() {
// Build the Profile property
if (NeedProfileProperty)
BuildProfileProperty();
// Skip the rest if we're only generating the intermediate class
if (_sourceDataClass == null)
return;
// Build the injected properties from the global.asax <object> tags
BuildApplicationObjectProperties();
BuildSessionObjectProperties();
// Build the injected properties for objects scoped to the page
BuildPageObjectProperties();
// Add all the <script runat=server> code blocks
foreach (ScriptBlockData script in Parser.ScriptList) {
// Pad the code block so its generated offset matches the aspx
string code = script.Script;
code = code.PadLeft(code.Length + script.Column - 1);
CodeSnippetTypeMember literal = new CodeSnippetTypeMember(code);
literal.LinePragma = CreateCodeLinePragma(script.VirtualPath, script.Line,
script.Column, script.Column, script.Script.Length, false);
_sourceDataClass.Members.Add(literal);
}
}
/*
* Build the Profile property
*/
private void BuildProfileProperty() {
if (!ProfileManager.Enabled)
return;
CodeMemberProperty prop;
string typeName = ProfileBase.GetProfileClassName();
prop = new CodeMemberProperty();
prop.Attributes &= ~MemberAttributes.AccessMask;
prop.Attributes &= ~MemberAttributes.ScopeMask;
prop.Attributes |= MemberAttributes.Final | MemberAttributes.Family;
prop.Name = "Profile";
if (_designerMode) {
ApplyEditorBrowsableCustomAttribute(prop);
}
//if (ProfileBase.GetPropertiesForCompilation().Count == 0)
// typeName = "System.Web.Profile.DefaultProfile";
//else
// typeName = "ASP.Profile";
prop.Type = new CodeTypeReference(typeName);
CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(), "Context");
propRef = new CodePropertyReferenceExpression(propRef, "Profile");
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
typeName, propRef)));
_intermediateClass.Members.Add(prop);
}
// By default, we build the Profile property
protected virtual bool NeedProfileProperty { get { return true; } }
protected void BuildAccessorProperty(string propName, CodeFieldReferenceExpression fieldRef,
Type propType, MemberAttributes attributes, CodeAttributeDeclarationCollection attrDeclarations) {
// e.g.
// [attrDeclaration]
// public SomeType SomeProp {
// get {
// return this.__SomeProp;
// }
// }
CodeMemberProperty prop = new CodeMemberProperty();
prop.Attributes = attributes;
prop.Name = propName;
prop.Type = new CodeTypeReference(propType);
prop.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
prop.SetStatements.Add(new CodeAssignStatement(
fieldRef, new CodePropertySetValueReferenceExpression()));
if (attrDeclarations != null) {
prop.CustomAttributes = attrDeclarations;
}
_sourceDataClass.Members.Add(prop);
}
protected void BuildFieldAndAccessorProperty(string propName, string fieldName,
Type propType, bool fStatic, CodeAttributeDeclarationCollection attrDeclarations) {
// e.g. private SomeType __SomeProp;
CodeMemberField field = new CodeMemberField(propType, fieldName);
if (fStatic) {
field.Attributes |= MemberAttributes.Static;
}
_sourceDataClass.Members.Add(field);
CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), fieldName);
BuildAccessorProperty(propName, fieldRef, propType, MemberAttributes.Public, attrDeclarations);
}
/*
* Helper method used to build the properties of injected
* global.asax properties. These look like:
* PropType __propName;
* protected PropType propName
* {
* get
* {
* if (__propName == null)
* __propName = [some expression];
*
* return __propName;
* }
* }
*/
private void BuildInjectedGetPropertyMethod(string propName,
Type propType,
CodeExpression propertyInitExpression,
bool fPublicProp) {
string fieldName = "cached" + propName;
CodeExpression fieldAccess = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
// Add a private field for the object
_sourceDataClass.Members.Add(new CodeMemberField(propType, fieldName));
CodeMemberProperty prop = new CodeMemberProperty();
if (fPublicProp) {
prop.Attributes &= ~MemberAttributes.AccessMask;
prop.Attributes |= MemberAttributes.Public;
}
prop.Name = propName;
prop.Type = new CodeTypeReference(propType);
CodeConditionStatement ifStmt = new CodeConditionStatement();
ifStmt.Condition = new CodeBinaryOperatorExpression(fieldAccess, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
ifStmt.TrueStatements.Add(new CodeAssignStatement(fieldAccess, propertyInitExpression));
prop.GetStatements.Add(ifStmt);
prop.GetStatements.Add(new CodeMethodReturnStatement(fieldAccess));
_sourceDataClass.Members.Add(prop);
}
/*
* Helper method for building application and session scope injected
* properties. If useApplicationState, build application properties, otherwise
* build session properties.
*/
private void BuildObjectPropertiesHelper(IDictionary objects, bool useApplicationState) {
IDictionaryEnumerator en = objects.GetEnumerator();
while (en.MoveNext()) {
HttpStaticObjectsEntry entry = (HttpStaticObjectsEntry)en.Value;
// e.g. (PropType)Session.StaticObjects["PropName"]
// Use the appropriate collection
CodePropertyReferenceExpression stateObj = new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),
useApplicationState ? "Application" : "Session"),
"StaticObjects");
CodeMethodInvokeExpression getObject = new CodeMethodInvokeExpression(stateObj, "GetObject");
getObject.Parameters.Add(new CodePrimitiveExpression(entry.Name));
Type declaredType = entry.DeclaredType;
Debug.Assert(!Util.IsLateBoundComClassicType(declaredType));
if (useApplicationState) {
// for application state use property that does caching in a member
BuildInjectedGetPropertyMethod(entry.Name, declaredType,
new CodeCastExpression(declaredType, getObject),
false /*fPublicProp*/);
}
else {
// for session state use lookup every time, as one application instance deals with many sessions
CodeMemberProperty prop = new CodeMemberProperty();
prop.Name = entry.Name;
prop.Type = new CodeTypeReference(declaredType);
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(declaredType, getObject)));
_sourceDataClass.Members.Add(prop);
}
}
}
/*
* Build the injected properties from the global.asax <object> tags
* declared with scope=application
*/
private void BuildApplicationObjectProperties() {
if (Parser.ApplicationObjects != null)
BuildObjectPropertiesHelper(Parser.ApplicationObjects.Objects, true);
}
/*
* Build the injected properties from the global.asax <object> tags
* declared with scope=session
*/
private void BuildSessionObjectProperties() {
if (Parser.SessionObjects != null)
BuildObjectPropertiesHelper(Parser.SessionObjects.Objects, false);
}
protected virtual bool IsGlobalAsaxGenerator { get { return false; } }
/*
* Build the injected properties from the global.asax <object> tags
* declared with scope=appinstance, or the aspx/ascx tags with scope=page.
*/
private void BuildPageObjectProperties() {
if (Parser.PageObjectList == null) return;
foreach (ObjectTagBuilder obj in Parser.PageObjectList) {
CodeExpression propertyInitExpression;
if (obj.Progid != null) {
// If we are dealing with a COM classic object that hasn't been tlbreg'ed,
// we need to call HttpServerUtility.CreateObject(progid) to create it
CodeMethodInvokeExpression createObjectCall = new CodeMethodInvokeExpression();
createObjectCall.Method.TargetObject = new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(), "Server");
createObjectCall.Method.MethodName = "CreateObject";
createObjectCall.Parameters.Add(new CodePrimitiveExpression(obj.Progid));
propertyInitExpression = createObjectCall;
}
else if (obj.Clsid != null) {
// Same as previous case, but with a clsid instead of a progId
CodeMethodInvokeExpression createObjectCall = new CodeMethodInvokeExpression();
createObjectCall.Method.TargetObject = new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(), "Server");
createObjectCall.Method.MethodName = "CreateObjectFromClsid";
createObjectCall.Parameters.Add(new CodePrimitiveExpression(obj.Clsid));
propertyInitExpression = createObjectCall;
}
else {
propertyInitExpression = new CodeObjectCreateExpression(obj.ObjectType);
}
// Make the appinstance properties public for global.asax (ASURT 63253)
BuildInjectedGetPropertyMethod(obj.ID, obj.DeclaredType,
propertyInitExpression, IsGlobalAsaxGenerator /*fPublicProp*/);
}
}
protected CodeLinePragma CreateCodeLinePragma(ControlBuilder builder) {
string virtualPath = builder.PageVirtualPath;
int line = builder.Line;
int column = 1;
int generatedColumn = 1;
int codeLength = -1;
CodeBlockBuilder codeBlockBuilder = builder as CodeBlockBuilder;
if (codeBlockBuilder != null) {
column = codeBlockBuilder.Column;
codeLength = codeBlockBuilder.Content.Length;
if (codeBlockBuilder.BlockType == CodeBlockType.Code) {
// If it's a <% ... %> block, the generated column is the same as the source
generatedColumn = column;
}
else {
// If it's a <%= ... %> block, we always generate '__o = expr' is
// designer mode, so the column is fixed
//
generatedColumn = BaseTemplateCodeDomTreeGenerator.tempObjectVariable.Length +
GetGeneratedColumnOffset(_codeDomProvider);
}
}
return CreateCodeLinePragma(virtualPath, line, column, generatedColumn, codeLength);
}
internal static int GetGeneratedColumnOffset(CodeDomProvider codeDomProvider) {
object o = null;
if (_generatedColumnOffsetDictionary == null) {
_generatedColumnOffsetDictionary = new ListDictionary();
}
else {
o = _generatedColumnOffsetDictionary[codeDomProvider.GetType()];
}
if (o == null) {
CodeCompileUnit ccu = new CodeCompileUnit();
CodeNamespace cnamespace = new CodeNamespace("ASP");
ccu.Namespaces.Add(cnamespace);
CodeTypeDeclaration type = new CodeTypeDeclaration("ColumnOffsetCalculator");
type.IsClass = true;
cnamespace.Types.Add(type);
CodeMemberMethod method = new CodeMemberMethod();
method.ReturnType = new CodeTypeReference(typeof(void));
method.Name = "GenerateMethod";
type.Members.Add(method);
CodeStatement simpleAssignment = new CodeAssignStatement(
new CodeVariableReferenceExpression(BaseTemplateCodeDomTreeGenerator.tempObjectVariable),
new CodeSnippetExpression(_dummyVariable));
method.Statements.Add(simpleAssignment);
StringBuilder sb = new StringBuilder();
StringWriter w = new StringWriter(sb, CultureInfo.InvariantCulture);
codeDomProvider.GenerateCodeFromCompileUnit(ccu, w, null);
StringReader reader = new StringReader(sb.ToString());
String line = null;
int offset = _defaultColumnOffset;
while ((line = reader.ReadLine()) != null) {
int index = 0;
line = line.TrimStart();
if ((index = line.IndexOf(_dummyVariable, StringComparison.Ordinal)) != -1) {
offset = index - BaseTemplateCodeDomTreeGenerator.tempObjectVariable.Length + 1;
}
}
// Save the offset per type.
_generatedColumnOffsetDictionary[codeDomProvider.GetType()] = offset;
return offset;
}
return (int)o;
}
protected CodeLinePragma CreateCodeLinePragma(string virtualPath, int lineNumber) {
return CreateCodeLinePragma(virtualPath, lineNumber, 1, 1, -1, true);
}
protected CodeLinePragma CreateCodeLinePragma(string virtualPath, int lineNumber,
int column, int generatedColumn, int codeLength) {
return CreateCodeLinePragma(virtualPath, lineNumber, column, generatedColumn, codeLength, true);
}
protected CodeLinePragma CreateCodeLinePragma(string virtualPath, int lineNumber,
int column, int generatedColumn, int codeLength, bool isCodeNugget) {
// Return null if we're not supposed to generate line pragmas
if (!Parser.FLinePragmas)
return null;
// The problem with disabling pragmas in non-debug is that we no longer
// get line information on compile errors, while in v1 we did. So
// unless we find a better solution, don't disable pragmas in non-debug
/*
// Also, don't bother with pragmas unless we're compiling for debugging
if (!CompilParams.IncludeDebugInformation)
return null;
*/
if (String.IsNullOrEmpty(virtualPath))
return null;
if (_designerMode) {
// Only generate pragmas for code blocks in designer mode
if (codeLength < 0)
return null;
LinePragmaCodeInfo codeInfo = new LinePragmaCodeInfo();
codeInfo._startLine = lineNumber;
codeInfo._startColumn = column;
codeInfo._startGeneratedColumn = generatedColumn;
codeInfo._codeLength = codeLength;
codeInfo._isCodeNugget = isCodeNugget;
lineNumber = _pragmaIdGenerator++;
if (_linePragmasTable == null)
_linePragmasTable = new Hashtable();
_linePragmasTable[lineNumber] = codeInfo;
}
return CreateCodeLinePragmaHelper(virtualPath, lineNumber);
}
internal static CodeLinePragma CreateCodeLinePragmaHelper(string virtualPath, int lineNumber) {
string pragmaFile = null;
if (UrlPath.IsAbsolutePhysicalPath(virtualPath)) {
// Due to config system limitations, we can end up with virtualPath
// actually being a physical path. If that's the case, just use it as is.
//
pragmaFile = virtualPath;
}
else {
if (_urlLinePragmas) {
// If specified in config, generate URL's for the line pragmas
// instead of physical path. This is used for VS debugging.
// We don't know the server name, so we just used a fixed one. This should be
// fine, as VS will ignore the server name.
pragmaFile = ErrorFormatter.MakeHttpLinePragma(virtualPath);
}
else {
try {
// Try using the physical path for the line pragma
pragmaFile = HostingEnvironment.MapPathInternal(virtualPath);
// If the physical path doesn't exist, use the URL instead.
// This can happen when using a VirtualPathProvider (VSWhidbey 272259)
if (!File.Exists(pragmaFile)) {
pragmaFile = ErrorFormatter.MakeHttpLinePragma(virtualPath);
}
}
catch {
// If MapPath failed, use the URL instead
pragmaFile = ErrorFormatter.MakeHttpLinePragma(virtualPath);
}
}
}
return new CodeLinePragma(pragmaFile, lineNumber);
}
// Adds [DebuggerNonUserCode] to the method to prevent debugger from stepping into generated code
protected void AddDebuggerNonUserCodeAttribute(CodeMemberMethod method) {
if (method == null) return;
// If LinePragmas is false, the user might want to debug generated code, so we do not add the attribute
if (!Parser.FLinePragmas) return;
CodeAttributeDeclaration attributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute)));
method.CustomAttributes.Add(attributeDeclaration);
}
}
}
| |
using System;
using System.IO;
using Helsenorge.Registries;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Helsenorge.Registries.Mocks;
using Microsoft.Extensions.Logging;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Linq;
using Helsenorge.Messaging.Abstractions;
using Helsenorge.Messaging.Security;
using Helsenorge.Messaging.Tests.Mocks;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Helsenorge.Registries.Abstractions;
using System.Threading.Tasks;
namespace Helsenorge.Messaging.Tests
{
[TestClass]
[DeploymentItem(@"Files", @"Files")]
public class BaseTest
{
//public const int MyHerId = 93238;
///public const int OhterHerId = 93252;
public Guid CpaId = new Guid("49391409-e528-4919-b4a3-9ccdab72c8c1");
public const int DefaultOtherHerId = 93252;
protected AddressRegistryMock AddressRegistry { get; private set; }
protected CollaborationProtocolRegistryMock CollaborationRegistry { get; private set; }
protected ILoggerFactory LoggerFactory { get; private set; }
internal ILogger Logger { get; private set; }
protected MessagingClient Client { get; set; }
protected MessagingServer Server { get; set; }
protected MessagingSettings Settings { get; set; }
internal MockFactory MockFactory { get; set; }
internal MockLoggerProvider MockLoggerProvider { get; set; }
internal MockCertificateValidator CertificateValidator { get; set; }
protected XDocument GenericMessage => new XDocument(new XElement("SomeDummyXmlUsedForTesting"));
protected XDocument GenericResponse => new XDocument(new XElement("SomeDummyXmlResponseUsedForTesting"));
protected XDocument SoapFault => XDocument.Load(File.OpenRead(@"Files\SoapFault.xml"));
[TestInitialize]
public virtual void Setup()
{
SetupInternal(DefaultOtherHerId);
}
internal void SetupInternal(int otherHerId)
{
var addressRegistrySettings = new AddressRegistrySettings()
{
UserName = "username",
Password = "password",
EndpointName = "SomeEndpointName",
WcfConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),
CachingInterval = TimeSpan.FromSeconds(5)
};
var collaborationRegistrySettings = new CollaborationProtocolRegistrySettings()
{
UserName = "username",
Password = "password",
EndpointName = "SomeEndpointName",
WcfConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),
CachingInterval = TimeSpan.FromSeconds(5)
};
LoggerFactory = new LoggerFactory();
MockLoggerProvider = new MockLoggerProvider(null);
LoggerFactory.AddProvider(MockLoggerProvider);
Logger = LoggerFactory.CreateLogger<BaseTest>();
var distributedCache = DistributedCacheFactory.Create();
AddressRegistry = new AddressRegistryMock(addressRegistrySettings, distributedCache);
AddressRegistry.SetupFindCommunicationPartyDetails(i =>
{
var file = Path.Combine("Files", $"CommunicationDetails_{i}.xml");
return File.Exists(file) == false ? null : XElement.Load(file);
});
AddressRegistry.SetupGetCertificateDetailsForEncryption(i =>
{
var path = Path.Combine("Files", $"GetCertificateDetailsForEncryption_{i}.xml");
return File.Exists(path) == false ? null : XElement.Load(path);
});
AddressRegistry.SetupGetCertificateDetailsForValidatingSignature(i =>
{
var path = Path.Combine("Files", $"GetCertificateDetailsForValidatingSignature_{i}.xml");
return File.Exists(path) == false ? null : XElement.Load(path);
});
CollaborationRegistry = new CollaborationProtocolRegistryMock(collaborationRegistrySettings, distributedCache, AddressRegistry);
CollaborationRegistry.SetupFindProtocolForCounterparty(i =>
{
var file = Path.Combine("Files", $"CPP_{i}.xml");
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
CollaborationRegistry.SetupFindAgreementForCounterparty(i =>
{
var file = Path.Combine("Files", $"CPA_{i}.xml");
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
CollaborationRegistry.SetupFindAgreementById(i =>
{
var file = Path.Combine("Files", $"CPA_{i:D}.xml");
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
Settings = new MessagingSettings()
{
MyHerId = MockFactory.HelsenorgeHerId,
SigningCertificate = new CertificateSettings()
{
Certificate = TestCertificates.HelsenorgePrivateSigntature
},
DecryptionCertificate = new CertificateSettings()
{
Certificate = TestCertificates.HelsenorgePrivateEncryption
}
};
Settings.ServiceBus.ConnectionString = "connection string";
Settings.ServiceBus.Synchronous.ReplyQueueMapping.Add(Environment.MachineName.ToLower(), "RepliesGoHere");
// make things easier by only having one processing task per queue
Settings.ServiceBus.Asynchronous.ProcessingTasks = 1;
Settings.ServiceBus.Synchronous.ProcessingTasks = 1;
Settings.ServiceBus.Error.ProcessingTasks = 1;
MockFactory = new MockFactory(otherHerId);
CertificateValidator = new MockCertificateValidator();
Client = new MessagingClient(Settings, CollaborationRegistry, AddressRegistry)
{
DefaultMessageProtection = new NoMessageProtection(), // disable protection for most tests
DefaultCertificateValidator = CertificateValidator
};
Client.ServiceBus.RegisterAlternateMessagingFactory(MockFactory);
Server = new MessagingServer(Settings, Logger, LoggerFactory, CollaborationRegistry, AddressRegistry)
{
DefaultMessageProtection = new NoMessageProtection(), // disable protection for most tests
DefaultCertificateValidator = CertificateValidator
};
Server.ServiceBus.RegisterAlternateMessagingFactory(MockFactory);
}
internal MockMessage CreateMockMessage(OutgoingMessage message)
{
return new MockMessage(GenericResponse)
{
MessageFunction = message.MessageFunction,
ApplicationTimestamp = DateTime.Now,
ContentType = ContentType.SignedAndEnveloped,
MessageId = Guid.NewGuid().ToString("D"),
CorrelationId = message.MessageId,
FromHerId = MockFactory.OtherHerId,
ToHerId = MockFactory.HelsenorgeHerId,
ScheduledEnqueueTimeUtc = DateTime.UtcNow,
TimeToLive = TimeSpan.FromSeconds(15),
};
}
protected void RunAndHandleException(Task task)
{
try
{
Task.WaitAll(task);
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
}
protected void RunAndHandleMessagingException(Task task, EventId id)
{
try
{
Task.WaitAll(task);
}
catch (AggregateException ex)
{
if ((ex.InnerException is MessagingException messagingException) && (messagingException.EventId.Id == id.Id))
{
throw ex.InnerException;
}
throw new InvalidOperationException("Expected a messaging exception");
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmDesign
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmDesign() : base()
{
Load += frmDesign_Load;
KeyPress += frmDesign_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdnew;
public System.Windows.Forms.Button cmdnew {
get { return withEventsField_cmdnew; }
set {
if (withEventsField_cmdnew != null) {
withEventsField_cmdnew.Click -= cmdNew_Click;
}
withEventsField_cmdnew = value;
if (withEventsField_cmdnew != null) {
withEventsField_cmdnew.Click += cmdNew_Click;
}
}
}
public System.Windows.Forms.RadioButton _Option1_1;
public System.Windows.Forms.RadioButton _Option1_2;
private System.Windows.Forms.Button withEventsField_cmdexit;
public System.Windows.Forms.Button cmdexit {
get { return withEventsField_cmdexit; }
set {
if (withEventsField_cmdexit != null) {
withEventsField_cmdexit.Click -= cmdExit_Click;
}
withEventsField_cmdexit = value;
if (withEventsField_cmdexit != null) {
withEventsField_cmdexit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdnext;
public System.Windows.Forms.Button cmdnext {
get { return withEventsField_cmdnext; }
set {
if (withEventsField_cmdnext != null) {
withEventsField_cmdnext.Click -= cmdNext_Click;
}
withEventsField_cmdnext = value;
if (withEventsField_cmdnext != null) {
withEventsField_cmdnext.Click += cmdNext_Click;
}
}
}
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
}
}
}
public System.Windows.Forms.Label Label1;
//Public WithEvents Option1 As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmDesign));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdnew = new System.Windows.Forms.Button();
this._Option1_1 = new System.Windows.Forms.RadioButton();
this._Option1_2 = new System.Windows.Forms.RadioButton();
this.cmdexit = new System.Windows.Forms.Button();
this.cmdnext = new System.Windows.Forms.Button();
this.DataList1 = new myDataGridView();
this.Label1 = new System.Windows.Forms.Label();
//Me.Option1 = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components)
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
//CType(Me.Option1, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Barcode Design";
this.ClientSize = new System.Drawing.Size(425, 383);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmDesign";
this.cmdnew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdnew.Text = "N&ew";
this.cmdnew.Size = new System.Drawing.Size(81, 33);
this.cmdnew.Location = new System.Drawing.Point(168, 344);
this.cmdnew.TabIndex = 6;
this.cmdnew.BackColor = System.Drawing.SystemColors.Control;
this.cmdnew.CausesValidation = true;
this.cmdnew.Enabled = true;
this.cmdnew.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdnew.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdnew.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdnew.TabStop = true;
this.cmdnew.Name = "cmdnew";
this._Option1_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._Option1_1.Text = "&Shelf Talker";
this._Option1_1.Size = new System.Drawing.Size(113, 33);
this._Option1_1.Location = new System.Drawing.Point(144, 32);
this._Option1_1.Appearance = System.Windows.Forms.Appearance.Button;
this._Option1_1.TabIndex = 5;
this._Option1_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._Option1_1.BackColor = System.Drawing.SystemColors.Control;
this._Option1_1.CausesValidation = true;
this._Option1_1.Enabled = true;
this._Option1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_1.TabStop = true;
this._Option1_1.Checked = false;
this._Option1_1.Visible = true;
this._Option1_1.Name = "_Option1_1";
this._Option1_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._Option1_2.Text = "Stock &Barcode";
this._Option1_2.Size = new System.Drawing.Size(129, 33);
this._Option1_2.Location = new System.Drawing.Point(8, 32);
this._Option1_2.Appearance = System.Windows.Forms.Appearance.Button;
this._Option1_2.TabIndex = 4;
this._Option1_2.Checked = true;
this._Option1_2.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._Option1_2.BackColor = System.Drawing.SystemColors.Control;
this._Option1_2.CausesValidation = true;
this._Option1_2.Enabled = true;
this._Option1_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_2.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_2.TabStop = true;
this._Option1_2.Visible = true;
this._Option1_2.Name = "_Option1_2";
this.cmdexit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdexit.Text = "E&xit";
this.cmdexit.Size = new System.Drawing.Size(81, 33);
this.cmdexit.Location = new System.Drawing.Point(8, 344);
this.cmdexit.TabIndex = 2;
this.cmdexit.BackColor = System.Drawing.SystemColors.Control;
this.cmdexit.CausesValidation = true;
this.cmdexit.Enabled = true;
this.cmdexit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdexit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdexit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdexit.TabStop = true;
this.cmdexit.Name = "cmdexit";
this.cmdnext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdnext.Text = "&Next";
this.cmdnext.Size = new System.Drawing.Size(81, 33);
this.cmdnext.Location = new System.Drawing.Point(336, 344);
this.cmdnext.TabIndex = 1;
this.cmdnext.BackColor = System.Drawing.SystemColors.Control;
this.cmdnext.CausesValidation = true;
this.cmdnext.Enabled = true;
this.cmdnext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdnext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdnext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdnext.TabStop = true;
this.cmdnext.Name = "cmdnext";
//'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(409, 264);
this.DataList1.Location = new System.Drawing.Point(8, 72);
this.DataList1.TabIndex = 0;
this.DataList1.Name = "DataList1";
this.Label1.Text = "Please select the Stock Barcode you wish to modify";
this.Label1.Size = new System.Drawing.Size(353, 25);
this.Label1.Location = new System.Drawing.Point(8, 8);
this.Label1.TabIndex = 3;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = false;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Controls.Add(cmdnew);
this.Controls.Add(_Option1_1);
this.Controls.Add(_Option1_2);
this.Controls.Add(cmdexit);
this.Controls.Add(cmdnext);
this.Controls.Add(DataList1);
this.Controls.Add(Label1);
//Me.Option1.SetIndex(_Option1_1, CType(1, Short))
//Me.Option1.SetIndex(_Option1_2, CType(2, Short))
//CType(Me.Option1, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Dynamic.Utils;
using AstUtils = System.Linq.Expressions.Interpreter.Utils;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Interpreter
{
internal sealed class ExplicitBox : IStrongBox
{
public object Value { get; set; }
public ExplicitBox()
{
}
public ExplicitBox(object value)
{
this.Value = value;
}
}
internal static partial class DelegateHelpers
{
private const int MaximumArity = 17;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal static Type MakeDelegate(Type[] types)
{
Debug.Assert(types != null && types.Length > 0);
// Can only used predefined delegates if we have no byref types and
// the arity is small enough to fit in Func<...> or Action<...>
if (types.Length > MaximumArity || types.Any(t => t.IsByRef))
{
throw Assert.Unreachable;
}
Type returnType = types[types.Length - 1];
if (returnType == typeof(void))
{
Array.Resize(ref types, types.Length - 1);
switch (types.Length)
{
case 0: return typeof(Action);
case 1: return typeof(Action<>).MakeGenericType(types);
case 2: return typeof(Action<,>).MakeGenericType(types);
case 3: return typeof(Action<,,>).MakeGenericType(types);
case 4: return typeof(Action<,,,>).MakeGenericType(types);
case 5: return typeof(Action<,,,,>).MakeGenericType(types);
case 6: return typeof(Action<,,,,,>).MakeGenericType(types);
case 7: return typeof(Action<,,,,,,>).MakeGenericType(types);
case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types);
case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types);
case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types);
case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types);
case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types);
case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types);
case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types);
case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types);
case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types);
}
}
else
{
switch (types.Length)
{
case 1: return typeof(Func<>).MakeGenericType(types);
case 2: return typeof(Func<,>).MakeGenericType(types);
case 3: return typeof(Func<,,>).MakeGenericType(types);
case 4: return typeof(Func<,,,>).MakeGenericType(types);
case 5: return typeof(Func<,,,,>).MakeGenericType(types);
case 6: return typeof(Func<,,,,,>).MakeGenericType(types);
case 7: return typeof(Func<,,,,,,>).MakeGenericType(types);
case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types);
case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types);
case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types);
case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types);
case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types);
case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types);
case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types);
case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types);
case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types);
case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types);
}
}
throw Assert.Unreachable;
}
}
internal class ScriptingRuntimeHelpers
{
public static object Int32ToObject(int i)
{
return i;
}
public static object BooleanToObject(bool b)
{
return b ? True : False;
}
internal static object True = true;
internal static object False = false;
internal static object GetPrimitiveDefaultValue(Type type)
{
switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type))
{
case TypeCode.Boolean: return ScriptingRuntimeHelpers.False;
case TypeCode.SByte: return default(SByte);
case TypeCode.Byte: return default(Byte);
case TypeCode.Char: return default(Char);
case TypeCode.Int16: return default(Int16);
case TypeCode.Int32: return ScriptingRuntimeHelpers.Int32ToObject(0);
case TypeCode.Int64: return default(Int64);
case TypeCode.UInt16: return default(UInt16);
case TypeCode.UInt32: return default(UInt32);
case TypeCode.UInt64: return default(UInt64);
case TypeCode.Single: return default(Single);
case TypeCode.Double: return default(Double);
// case TypeCode.DBNull: return default(DBNull);
case TypeCode.DateTime: return default(DateTime);
case TypeCode.Decimal: return default(Decimal);
default: return null;
}
}
}
/// <summary>
/// Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate.
/// The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them.
/// </summary>
internal sealed class ArgumentArray
{
private readonly object[] _arguments;
// the index of the first item _arguments that represents an argument:
private readonly int _first;
// the number of items in _arguments that represent the arguments:
private readonly int _count;
internal ArgumentArray(object[] arguments, int first, int count)
{
_arguments = arguments;
_first = first;
_count = count;
}
public int Count
{
get { return _count; }
}
public object GetArgument(int index)
{
return _arguments[_first + index];
}
public static object GetArg(ArgumentArray array, int index)
{
return array._arguments[array._first + index];
}
}
internal static class ExceptionHelpers
{
private const string prevStackTraces = "PreviousStackTraces";
/// <summary>
/// Updates an exception before it's getting re-thrown so
/// we can present a reasonable stack trace to the user.
/// </summary>
public static Exception UpdateForRethrow(Exception rethrow)
{
#if FEATURE_STACK_TRACES
List<StackTrace> prev;
// we don't have any dynamic stack trace data, capture the data we can
// from the raw exception object.
StackTrace st = new StackTrace(rethrow, true);
if (!TryGetAssociatedStackTraces(rethrow, out prev))
{
prev = new List<StackTrace>();
AssociateStackTraces(rethrow, prev);
}
prev.Add(st);
#endif // FEATURE_STACK_TRACES
return rethrow;
}
#if FEATURE_STACK_TRACES
/// <summary>
/// Returns all the stack traces associates with an exception
/// </summary>
public static IList<StackTrace> GetExceptionStackTraces(Exception rethrow)
{
List<StackTrace> result;
return TryGetAssociatedStackTraces(rethrow, out result) ? result : null;
}
private static void AssociateStackTraces(Exception e, List<StackTrace> traces)
{
e.Data[prevStackTraces] = traces;
}
private static bool TryGetAssociatedStackTraces(Exception e, out List<StackTrace> traces)
{
traces = e.Data[prevStackTraces] as List<StackTrace>;
return traces != null;
}
#endif // FEATURE_STACK_TRACES
}
/// <summary>
/// A hybrid dictionary which compares based upon object identity.
/// </summary>
internal class HybridReferenceDictionary<TKey, TValue> where TKey : class
{
private KeyValuePair<TKey, TValue>[] _keysAndValues;
private Dictionary<TKey, TValue> _dict;
private int _count;
private const int _arraySize = 10;
public HybridReferenceDictionary()
{
}
public HybridReferenceDictionary(int initialCapicity)
{
if (initialCapicity > _arraySize)
{
_dict = new Dictionary<TKey, TValue>(initialCapicity);
}
else
{
_keysAndValues = new KeyValuePair<TKey, TValue>[initialCapicity];
}
}
public bool TryGetValue(TKey key, out TValue value)
{
Debug.Assert(key != null);
if (_dict != null)
{
return _dict.TryGetValue(key, out value);
}
else if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
value = _keysAndValues[i].Value;
return true;
}
}
}
value = default(TValue);
return false;
}
public bool Remove(TKey key)
{
Debug.Assert(key != null);
if (_dict != null)
{
return _dict.Remove(key);
}
else if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
_keysAndValues[i] = new KeyValuePair<TKey, TValue>();
_count--;
return true;
}
}
}
return false;
}
public bool ContainsKey(TKey key)
{
Debug.Assert(key != null);
if (_dict != null)
{
return _dict.ContainsKey(key);
}
else if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
return true;
}
}
}
return false;
}
public int Count
{
get
{
if (_dict != null)
{
return _dict.Count;
}
return _count;
}
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
if (_dict != null)
{
return _dict.GetEnumerator();
}
return GetEnumeratorWorker();
}
private IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorWorker()
{
if (_keysAndValues != null)
{
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key != null)
{
yield return _keysAndValues[i];
}
}
}
}
public TValue this[TKey key]
{
get
{
Debug.Assert(key != null);
TValue res;
if (TryGetValue(key, out res))
{
return res;
}
throw new KeyNotFoundException();
}
set
{
Debug.Assert(key != null);
if (_dict != null)
{
_dict[key] = value;
}
else
{
int index;
if (_keysAndValues != null)
{
index = -1;
for (int i = 0; i < _keysAndValues.Length; i++)
{
if (_keysAndValues[i].Key == key)
{
_keysAndValues[i] = new KeyValuePair<TKey, TValue>(key, value);
return;
}
else if (_keysAndValues[i].Key == null)
{
index = i;
}
}
}
else
{
_keysAndValues = new KeyValuePair<TKey, TValue>[_arraySize];
index = 0;
}
if (index != -1)
{
_count++;
_keysAndValues[index] = new KeyValuePair<TKey, TValue>(key, value);
}
else
{
_dict = new Dictionary<TKey, TValue>();
for (int i = 0; i < _keysAndValues.Length; i++)
{
_dict[_keysAndValues[i].Key] = _keysAndValues[i].Value;
}
_keysAndValues = null;
_dict[key] = value;
}
}
}
}
}
/// <summary>
/// Provides a dictionary-like object used for caches which holds onto a maximum
/// number of elements specified at construction time.
///
/// This class is not thread safe.
/// </summary>
internal class CacheDict<TKey, TValue>
{
private readonly Dictionary<TKey, KeyInfo> _dict = new Dictionary<TKey, KeyInfo>();
private readonly LinkedList<TKey> _list = new LinkedList<TKey>();
private readonly int _maxSize;
/// <summary>
/// Creates a dictionary-like object used for caches.
/// </summary>
/// <param name="maxSize">The maximum number of elements to store.</param>
public CacheDict(int maxSize)
{
_maxSize = maxSize;
}
/// <summary>
/// Tries to get the value associated with 'key', returning true if it's found and
/// false if it's not present.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
KeyInfo storedValue;
if (_dict.TryGetValue(key, out storedValue))
{
LinkedListNode<TKey> node = storedValue.List;
if (node.Previous != null)
{
// move us to the head of the list...
_list.Remove(node);
_list.AddFirst(node);
}
value = storedValue.Value;
return true;
}
value = default(TValue);
return false;
}
/// <summary>
/// Adds a new element to the cache, replacing and moving it to the front if the
/// element is already present.
/// </summary>
public void Add(TKey key, TValue value)
{
KeyInfo keyInfo;
if (_dict.TryGetValue(key, out keyInfo))
{
// remove original entry from the linked list
_list.Remove(keyInfo.List);
}
else if (_list.Count == _maxSize)
{
// we've reached capacity, remove the last used element...
LinkedListNode<TKey> node = _list.Last;
_list.RemoveLast();
bool res = _dict.Remove(node.Value);
Debug.Assert(res);
}
// add the new entry to the head of the list and into the dictionary
LinkedListNode<TKey> listNode = new LinkedListNode<TKey>(key);
_list.AddFirst(listNode);
_dict[key] = new CacheDict<TKey, TValue>.KeyInfo(value, listNode);
}
/// <summary>
/// Returns the value associated with the given key, or throws KeyNotFoundException
/// if the key is not present.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public TValue this[TKey key]
{
get
{
TValue res;
if (TryGetValue(key, out res))
{
return res;
}
throw new KeyNotFoundException();
}
set
{
Add(key, value);
}
}
private struct KeyInfo
{
internal readonly TValue Value;
internal readonly LinkedListNode<TKey> List;
internal KeyInfo(TValue value, LinkedListNode<TKey> list)
{
Value = value;
List = list;
}
}
}
internal static class Assert
{
internal static Exception Unreachable
{
get
{
Debug.Assert(false, "Unreachable");
return new InvalidOperationException("Code supposed to be unreachable");
}
}
[Conditional("DEBUG")]
public static void NotNull(object var)
{
Debug.Assert(var != null);
}
[Conditional("DEBUG")]
public static void NotNull(object var1, object var2)
{
Debug.Assert(var1 != null && var2 != null);
}
[Conditional("DEBUG")]
public static void NotNull(object var1, object var2, object var3)
{
Debug.Assert(var1 != null && var2 != null && var3 != null);
}
[Conditional("DEBUG")]
public static void NotNullItems<T>(IEnumerable<T> items) where T : class
{
Debug.Assert(items != null);
foreach (object item in items)
{
Debug.Assert(item != null);
}
}
[Conditional("DEBUG")]
public static void NotEmpty(string str)
{
Debug.Assert(!String.IsNullOrEmpty(str));
}
}
[Flags]
internal enum ExpressionAccess
{
None = 0,
Read = 1,
Write = 2,
ReadWrite = Read | Write,
}
internal static class Utils
{
private static readonly DefaultExpression s_voidInstance = Expression.Empty();
public static DefaultExpression Empty()
{
return s_voidInstance;
}
}
internal sealed class ListEqualityComparer<T> : EqualityComparer<ICollection<T>>
{
internal static readonly ListEqualityComparer<T> Instance = new ListEqualityComparer<T>();
private ListEqualityComparer() { }
// EqualityComparer<T> handles null and object identity for us
public override bool Equals(ICollection<T> x, ICollection<T> y)
{
return x.ListEquals(y);
}
public override int GetHashCode(ICollection<T> obj)
{
return obj.ListHashCode();
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Reflection;
using Gallio.Common;
using Gallio.Common.Reflection;
using Gallio.Common.Reflection.Impl;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Build;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Caches;
using Gallio.Common.Collections;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Impl.Caches2;
using JetBrains.ReSharper.Psi.Impl.Special;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.DocumentModel;
using ReSharperDocumentRange = JetBrains.DocumentModel.DocumentRange;
using JetBrains.Metadata.Utils;
namespace Gallio.ReSharperRunner.Reflection
{
/// <summary>
/// Wraps ReSharper code model objects using the reflection adapter interfaces.
/// </summary>
public class PsiReflectionPolicy : ReSharperReflectionPolicy
{
private readonly PsiManager psiManager;
private KeyedMemoizer<IModule, StaticAssemblyWrapper> assemblyMemoizer = new KeyedMemoizer<IModule, StaticAssemblyWrapper>();
private KeyedMemoizer<IType, StaticTypeWrapper> typeMemoizer = new KeyedMemoizer<IType, StaticTypeWrapper>();
private KeyedMemoizer<ITypeElement, StaticDeclaredTypeWrapper> typeWithoutSubstitutionMemoizer = new KeyedMemoizer<ITypeElement, StaticDeclaredTypeWrapper>();
private KeyedMemoizer<IDeclaredType, StaticDeclaredTypeWrapper> declaredTypeMemoizer = new KeyedMemoizer<IDeclaredType, StaticDeclaredTypeWrapper>();
/// <summary>
/// Creates a reflector with the specified PSI manager.
/// </summary>
/// <param name="psiManager">The PSI manager.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="psiManager"/> is null.</exception>
public PsiReflectionPolicy(PsiManager psiManager)
{
if (psiManager == null)
throw new ArgumentNullException("psiManager");
this.psiManager = psiManager;
}
#region Wrapping
/// <summary>
/// Obtains a reflection wrapper for a declared element.
/// </summary>
/// <param name="target">The element, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public ICodeElementInfo Wrap(IDeclaredElement target)
{
if (target == null)
return null;
ITypeElement typeElement = target as ITypeElement;
if (typeElement != null)
return Wrap(typeElement);
IFunction function = target as IFunction;
if (function != null)
return Wrap(function);
IProperty property = target as IProperty;
if (property != null)
return Wrap(property);
IField field = target as IField;
if (field != null)
return Wrap(field);
IEvent @event = target as IEvent;
if (@event != null)
return Wrap(@event);
IParameter parameter = target as IParameter;
if (parameter != null)
return Wrap(parameter);
INamespace @namespace = target as INamespace;
if (@namespace != null)
return Reflector.WrapNamespace(@namespace.QualifiedName);
return null;
}
/// <summary>
/// Obtains a reflection wrapper for a type.
/// </summary>
/// <param name="target">The type, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticTypeWrapper Wrap(ITypeElement target)
{
return target != null ? MakeTypeWithoutSubstitution(target) : null;
}
/// <summary>
/// Obtains a reflection wrapper for a function.
/// </summary>
/// <param name="target">The function, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticFunctionWrapper Wrap(IFunction target)
{
if (target == null)
return null;
IConstructor constructor = target as IConstructor;
if (constructor != null)
return Wrap(constructor);
IMethod method = target as IMethod;
if (method != null)
return Wrap(method);
IOperator @operator = target as IOperator;
if (@operator != null)
return Wrap(@operator);
throw new NotSupportedException("Unsupported declared element type: " + target);
}
/// <summary>
/// Obtains a reflection wrapper for a constructor.
/// </summary>
/// <param name="target">The constructor, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticConstructorWrapper Wrap(IConstructor target)
{
if (target == null)
return null;
StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
return new StaticConstructorWrapper(this, target, declaringType);
}
/// <summary>
/// Obtains a reflection wrapper for a method.
/// </summary>
/// <param name="target">The method, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticMethodWrapper Wrap(IMethod target)
{
if (target == null)
return null;
StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
return new StaticMethodWrapper(this, target, declaringType, declaringType, declaringType.Substitution);
}
/// <summary>
/// Obtains a reflection wrapper for an operator.
/// </summary>
/// <param name="target">The method, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticMethodWrapper Wrap(IOperator target)
{
if (target == null)
return null;
StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
return new StaticMethodWrapper(this, target, declaringType, declaringType, declaringType.Substitution);
}
/// <summary>
/// Obtains a reflection wrapper for a property.
/// </summary>
/// <param name="target">The property, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticPropertyWrapper Wrap(IProperty target)
{
if (target == null)
return null;
StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
return new StaticPropertyWrapper(this, target, declaringType, declaringType);
}
/// <summary>
/// Obtains a reflection wrapper for a field.
/// </summary>
/// <param name="target">The field, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticFieldWrapper Wrap(IField target)
{
if (target == null)
return null;
StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
return new StaticFieldWrapper(this, target, declaringType, declaringType);
}
/// <summary>
/// Obtains a reflection wrapper for an event.
/// </summary>
/// <param name="target">The event, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticEventWrapper Wrap(IEvent target)
{
if (target == null)
return null;
StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
return new StaticEventWrapper(this, target, declaringType, declaringType);
}
/// <summary>
/// Obtains a reflection wrapper for a parameter.
/// </summary>
/// <param name="target">The parameter, or null if none.</param>
/// <returns>The reflection wrapper, or null if none.</returns>
public StaticParameterWrapper Wrap(IParameter target)
{
if (target == null)
return null;
var member = (StaticMemberWrapper) Wrap(target.ContainingParametersOwner);
if (member == null)
return null;
return new StaticParameterWrapper(this, target, member);
}
#endregion
#region Assemblies
protected override IAssemblyInfo LoadAssemblyImpl(AssemblyName assemblyName)
{
foreach (IProject project in psiManager.Solution.GetAllProjects())
{
try
{
var assemblyFile = project.GetOutputAssemblyFile();
if (assemblyFile != null && IsMatchingAssemblyName(assemblyName, new AssemblyName(assemblyFile.AssemblyName.FullName)))
{
return WrapModule(project);
}
}
catch (InvalidOperationException)
{
// May be thrown if build settings are not available for the project.
}
}
foreach (IAssembly assembly in psiManager.Solution.GetAllAssemblies())
{
if (IsMatchingAssemblyName(assemblyName, new AssemblyName(assembly.AssemblyName.FullName)))
{
return WrapModule(assembly);
}
}
throw new ArgumentException(String.Format("Could not find assembly '{0}' in the ReSharper code cache.",
assemblyName.FullName));
}
protected override IAssemblyInfo LoadAssemblyFromImpl(string assemblyFile)
{
throw new NotSupportedException("The PSI metadata policy does not support loading assemblies from files.");
}
protected override IEnumerable<StaticAttributeWrapper> GetAssemblyCustomAttributes(StaticAssemblyWrapper assembly)
{
IModule moduleHandle = (IModule) assembly.Handle;
CacheManagerEx cacheManager = CacheManagerEx.GetInstance(psiManager.Solution);
IPsiModule psiModule = GetPsiModule(moduleHandle);
if (psiModule != null)
{
foreach (IAttributeInstance attrib in cacheManager.GetModuleAttributes(psiModule).GetAttributeInstances(false))
{
if (IsAttributeInstanceValid(attrib))
yield return new StaticAttributeWrapper(this, attrib);
}
}
}
protected override AssemblyName GetAssemblyName(StaticAssemblyWrapper assembly)
{
IModule moduleHandle = (IModule) assembly.Handle;
return GetAssemblyName(moduleHandle);
}
protected override string GetAssemblyPath(StaticAssemblyWrapper assembly)
{
IModule moduleHandle = (IModule)assembly.Handle;
IAssemblyFile assemblyFile = GetAssemblyFile(moduleHandle);
if (assemblyFile == null)
return @"unknown";
return assemblyFile.Location.FullPath;
}
protected override IList<AssemblyName> GetAssemblyReferences(StaticAssemblyWrapper assembly)
{
IProject projectHandle = assembly.Handle as IProject;
if (projectHandle != null)
{
if (projectHandle.IsValid())
{
var moduleRefs = projectHandle.GetModuleReferences();
return GenericCollectionUtils.ConvertAllToArray(moduleRefs, moduleRef =>
GetAssemblyName(moduleRef.ResolveReferencedModule()));
}
}
// FIXME! Don't know how to handle referenced assemblies for assemblies without loading them.
//IAssembly assemblyHandle = (IAssembly)assembly.Handle;
//return assembly.Resolve(true).GetReferencedAssemblies();
return EmptyArray<AssemblyName>.Instance;
}
protected override IList<StaticDeclaredTypeWrapper> GetAssemblyExportedTypes(StaticAssemblyWrapper assembly)
{
IModule moduleHandle = (IModule)assembly.Handle;
return GetAssemblyTypes(moduleHandle, false);
}
protected override IList<StaticDeclaredTypeWrapper> GetAssemblyTypes(StaticAssemblyWrapper assembly)
{
IModule moduleHandle = (IModule)assembly.Handle;
return GetAssemblyTypes(moduleHandle, true);
}
protected override StaticDeclaredTypeWrapper GetAssemblyType(StaticAssemblyWrapper assembly, string typeName)
{
IModule moduleHandle = (IModule)assembly.Handle;
IDeclarationsCache cache = GetAssemblyDeclarationsCache(moduleHandle);
if (cache == null)
return null;
ITypeElement typeHandle = cache.GetTypeElementByCLRName(typeName);
return typeHandle != null && typeHandle.IsValid() ?
MakeDeclaredTypeWithoutSubstitution(typeHandle) : null;
}
private static bool IsMatchingAssemblyName(AssemblyName desiredAssemblyName, AssemblyName candidateAssemblyName)
{
bool haveDesiredFullName = desiredAssemblyName.Name != desiredAssemblyName.FullName;
bool haveCandidateFullName = candidateAssemblyName.Name != candidateAssemblyName.FullName;
if (haveDesiredFullName && haveCandidateFullName)
return desiredAssemblyName.FullName == candidateAssemblyName.FullName;
return desiredAssemblyName.Name == candidateAssemblyName.Name;
}
// note: result may be null
private static IAssemblyFile GetAssemblyFile(IModule moduleHandle)
{
IProject projectHandle = moduleHandle as IProject;
if (projectHandle != null)
return GetAssemblyFile(projectHandle);
IAssembly assemblyHandle = (IAssembly) moduleHandle;
IAssemblyFile[] files = assemblyHandle.GetFiles();
return files[0];
}
// note: result may be null
private static IAssemblyFile GetAssemblyFile(IProject projectHandle)
{
return BuildSettingsManager.GetInstance(projectHandle).GetOutputAssemblyFile();
}
private static AssemblyName GetAssemblyName(IModule moduleHandle)
{
IProject projectHandle = moduleHandle as IProject;
if (projectHandle != null)
{
IAssemblyFile assemblyFile = GetAssemblyFile(projectHandle);
AssemblyName name;
if (assemblyFile == null)
{
name = new AssemblyName(moduleHandle.Name);
}
else
{
AssemblyNameInfo assemblyNameInfo = assemblyFile.AssemblyName;
if ( assemblyNameInfo == null )
assemblyNameInfo = assemblyFile.Assembly.AssemblyName;
name = new AssemblyName(assemblyNameInfo.FullName);
}
if (name.Version == null)
{
name = (AssemblyName) name.Clone();
name.Version = new Version(0, 0, 0, 0);
}
return name;
}
IAssembly assemblyHandle = (IAssembly) moduleHandle;
return new AssemblyName(assemblyHandle.AssemblyName.FullName);
}
private IList<StaticDeclaredTypeWrapper> GetAssemblyTypes(IModule moduleHandle, bool includeNonPublicTypes)
{
IDeclarationsCache cache = GetAssemblyDeclarationsCache(moduleHandle);
if (cache == null)
return EmptyArray<StaticDeclaredTypeWrapper>.Instance;
INamespace namespaceHandle = cache.GetNamespace("");
List<StaticDeclaredTypeWrapper> types = new List<StaticDeclaredTypeWrapper>();
PopulateAssemblyTypes(types, namespaceHandle, cache, includeNonPublicTypes);
return types;
}
private void PopulateAssemblyTypes(List<StaticDeclaredTypeWrapper> types, INamespace namespaceHandle,
IDeclarationsCache cache, bool includeNonPublicTypes)
{
if (namespaceHandle == null || ! namespaceHandle.IsValid())
return;
foreach (IDeclaredElement elementHandle in namespaceHandle.GetNestedElements(cache))
{
ITypeElement typeHandle = elementHandle as ITypeElement;
if (typeHandle != null)
{
PopulateAssemblyTypes(types, typeHandle, includeNonPublicTypes);
}
else
{
INamespace nestedNamespace = elementHandle as INamespace;
if (nestedNamespace != null)
PopulateAssemblyTypes(types, nestedNamespace, cache, includeNonPublicTypes);
}
}
}
private void PopulateAssemblyTypes(List<StaticDeclaredTypeWrapper> types, ITypeElement typeHandle, bool includeNonPublicTypes)
{
if (!typeHandle.IsValid())
return;
IModifiersOwner modifiers = typeHandle as IModifiersOwner;
if (modifiers != null && (includeNonPublicTypes || modifiers.GetAccessRights() == AccessRights.PUBLIC))
{
types.Add(MakeDeclaredTypeWithoutSubstitution(typeHandle));
foreach (ITypeElement nestedType in typeHandle.NestedTypes)
PopulateAssemblyTypes(types, nestedType, includeNonPublicTypes);
}
}
private IDeclarationsCache GetAssemblyDeclarationsCache(IModule moduleHandle)
{
IPsiModule psiModule = GetPsiModule(moduleHandle);
if (psiModule == null)
return null;
return psiManager.GetDeclarationsCache(DeclarationsScopeFactory.ModuleScope(psiModule, false), true);
}
private IPsiModule GetPsiModule(IModule moduleHandle)
{
var moduleManager = PsiModuleManager.GetInstance(psiManager.Solution);
return moduleManager.GetPrimaryPsiModule(moduleHandle);
}
private StaticAssemblyWrapper WrapModule(IModule module)
{
return assemblyMemoizer.Memoize(module, () => new StaticAssemblyWrapper(this, module));
}
#endregion
#region Attributes
protected override StaticConstructorWrapper GetAttributeConstructor(StaticAttributeWrapper attribute)
{
IAttributeInstance attributeHandle = (IAttributeInstance)attribute.Handle;
IDeclaredType declaredTypeHandle = attributeHandle.AttributeType;
IConstructor constructorHandle = attributeHandle.Constructor;
return new StaticConstructorWrapper(this, constructorHandle, MakeDeclaredType(declaredTypeHandle));
}
protected override ConstantValue[] GetAttributeConstructorArguments(StaticAttributeWrapper attribute)
{
IAttributeInstance attributeHandle = (IAttributeInstance)attribute.Handle;
IList<IParameter> parameters = attributeHandle.Constructor.Parameters;
if (parameters.Count == 0)
return EmptyArray<ConstantValue>.Instance;
List<ConstantValue> values = new List<ConstantValue>();
for (int i = 0; ; i++)
{
#if RESHARPER_50_OR_NEWER
if (i == attributeHandle.PositionParameterCount)
break;
#endif
ConstantValue? value = GetAttributePositionParameter(attributeHandle, i);
if (value.HasValue)
values.Add(value.Value);
else
break;
}
int lastParameterIndex = parameters.Count - 1;
IParameter lastParameter = parameters[lastParameterIndex];
if (!lastParameter.IsParameterArray)
return values.ToArray();
// Note: When presented with a constructor that accepts a variable number of
// arguments, ReSharper treats them as a sequence of normal parameter
// values. So we we need to map them back into a params array appropriately.
ConstantValue[] args = new ConstantValue[parameters.Count];
values.CopyTo(0, args, 0, lastParameterIndex);
int varArgsCount = values.Count - lastParameterIndex;
ConstantValue[] varArgs = new ConstantValue[varArgsCount];
for (int i = 0; i < varArgsCount; i++)
varArgs[i] = values[lastParameterIndex + i];
args[lastParameterIndex] = new ConstantValue(MakeType(lastParameter.Type), varArgs);
return args;
}
protected override IEnumerable<KeyValuePair<StaticFieldWrapper, ConstantValue>> GetAttributeFieldArguments(StaticAttributeWrapper attribute)
{
IAttributeInstance attributeHandle = (IAttributeInstance)attribute.Handle;
foreach (StaticFieldWrapper field in attribute.Type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
if (ReflectorAttributeUtils.IsAttributeField(field))
{
ConstantValue? value = GetAttributeNamedParameter(attributeHandle, (IField)field.Handle);
if (value.HasValue)
yield return new KeyValuePair<StaticFieldWrapper, ConstantValue>(field, value.Value);
}
}
}
protected override IEnumerable<KeyValuePair<StaticPropertyWrapper, ConstantValue>> GetAttributePropertyArguments(StaticAttributeWrapper attribute)
{
IAttributeInstance attributeHandle = (IAttributeInstance)attribute.Handle;
foreach (StaticPropertyWrapper property in attribute.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (ReflectorAttributeUtils.IsAttributeProperty(property))
{
ConstantValue? value = GetAttributeNamedParameter(attributeHandle, (IProperty) property.Handle);
if (value.HasValue)
yield return new KeyValuePair<StaticPropertyWrapper, ConstantValue>(property, value.Value);
}
}
}
private ConstantValue? GetAttributeNamedParameter(IAttributeInstance attributeHandle, ITypeMember memberHandle)
{
#if RESHARPER_31
ConstantValue2 rawValue = GetAttributeNamedParameterHack(attributeHandle, memberHandle);
return rawValue.IsBadValue() ? (ConstantValue?)null : ConvertConstantValue(rawValue.Value);
#else
AttributeValue rawValue = attributeHandle.NamedParameter(memberHandle);
return rawValue.IsBadValue ? (ConstantValue?) null : ConvertConstantValue(rawValue);
#endif
}
private ConstantValue? GetAttributePositionParameter(IAttributeInstance attributeHandle, int index)
{
#if RESHARPER_31
ConstantValue2 rawValue = GetAttributePositionParameterHack(attributeHandle, index);
return rawValue.IsBadValue() ? (ConstantValue?)null : ConvertConstantValue(rawValue.Value);
#else
AttributeValue rawValue = attributeHandle.PositionParameter(index);
return rawValue.IsBadValue ? (ConstantValue?) null : ConvertConstantValue(rawValue);
#endif
}
#if RESHARPER_31
private ConstantValue ConvertConstantValue(object value)
{
return ConvertConstantValue<IType>(value, delegate(IType type) { return MakeType(type); });
}
#else
private ConstantValue ConvertConstantValue(AttributeValue value)
{
if (value.IsConstant)
return new ConstantValue(MakeType(value.ConstantValue.Type), value.ConstantValue.Value);
if (value.IsType)
return new ConstantValue(Reflector.Wrap(typeof(Type)), MakeType(value.TypeValue));
if (value.IsArray)
return new ConstantValue(MakeType(value.ArrayType),
GenericCollectionUtils.ConvertAllToArray<AttributeValue, ConstantValue>(value.ArrayValue, ConvertConstantValue));
throw new ReflectionResolveException("Unsupported attribute value type.");
}
#endif
#endregion
#region Members
protected override IEnumerable<StaticAttributeWrapper> GetMemberCustomAttributes(StaticMemberWrapper member)
{
IAttributesOwner memberHandle = (IAttributesOwner)member.Handle;
return GetAttributesForAttributeOwner(memberHandle);
}
protected override string GetMemberName(StaticMemberWrapper member)
{
IDeclaredElement memberHandle = (IDeclaredElement)member.Handle;
string shortName = memberHandle.ShortName;
if (shortName == "get_this")
shortName = "get_Item";
else if (shortName == "set_this")
shortName = "set_Item";
IOverridableMember overridableMemberHandle = memberHandle as IOverridableMember;
if (overridableMemberHandle != null && overridableMemberHandle.IsExplicitImplementation)
return overridableMemberHandle.ExplicitImplementations[0].DeclaringType.GetCLRName().Replace('+', '.') + "." + shortName;
return shortName;
}
protected override CodeLocation GetMemberSourceLocation(StaticMemberWrapper member)
{
IDeclaredElement memberHandle = (IDeclaredElement)member.Handle;
return GetDeclaredElementSourceLocation(memberHandle);
}
#endregion
#region Events
protected override EventAttributes GetEventAttributes(StaticEventWrapper @event)
{
return EventAttributes.None;
}
protected override StaticMethodWrapper GetEventAddMethod(StaticEventWrapper @event)
{
IEvent eventHandle = (IEvent)@event.Handle;
if (!eventHandle.IsValid())
return null;
IAccessor accessorHandle = eventHandle.Adder;
return accessorHandle != null && accessorHandle.IsValid() ? WrapAccessor(accessorHandle, @event) : null;
}
protected override StaticMethodWrapper GetEventRaiseMethod(StaticEventWrapper @event)
{
IEvent eventHandle = (IEvent)@event.Handle;
if (!eventHandle.IsValid())
return null;
IAccessor accessorHandle = eventHandle.Raiser;
return accessorHandle != null && accessorHandle.IsValid() ? WrapAccessor(accessorHandle, @event) : null;
}
protected override StaticMethodWrapper GetEventRemoveMethod(StaticEventWrapper @event)
{
IEvent eventHandle = (IEvent)@event.Handle;
if (!eventHandle.IsValid())
return null;
IAccessor accessorHandle = eventHandle.Remover;
return accessorHandle != null && accessorHandle.IsValid() ? WrapAccessor(accessorHandle, @event) : null;
}
protected override StaticTypeWrapper GetEventHandlerType(StaticEventWrapper @event)
{
IEvent eventHandle = (IEvent)@event.Handle;
return MakeType(eventHandle.Type);
}
#endregion
#region Fields
protected override FieldAttributes GetFieldAttributes(StaticFieldWrapper field)
{
IField fieldHandle = (IField)field.Handle;
FieldAttributes flags = 0;
switch (fieldHandle.GetAccessRights())
{
case AccessRights.PUBLIC:
flags |= FieldAttributes.Public;
break;
case AccessRights.PRIVATE:
flags |= FieldAttributes.Private;
break;
case AccessRights.NONE:
case AccessRights.INTERNAL:
flags |= FieldAttributes.Assembly;
break;
case AccessRights.PROTECTED:
flags |= FieldAttributes.Family;
break;
case AccessRights.PROTECTED_AND_INTERNAL:
flags |= FieldAttributes.FamANDAssem;
break;
case AccessRights.PROTECTED_OR_INTERNAL:
flags |= FieldAttributes.FamORAssem;
break;
}
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, FieldAttributes.Static, fieldHandle.IsStatic);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, FieldAttributes.InitOnly, fieldHandle.IsReadonly && ! fieldHandle.IsConstant);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, FieldAttributes.Literal | FieldAttributes.HasDefault, fieldHandle.IsConstant);
return flags;
}
protected override StaticTypeWrapper GetFieldType(StaticFieldWrapper field)
{
IField fieldHandle = (IField)field.Handle;
return MakeType(fieldHandle.Type);
}
#endregion
#region Properties
protected override PropertyAttributes GetPropertyAttributes(StaticPropertyWrapper property)
{
// Note: There don't seem to be any usable property attributes.
return 0;
}
protected override StaticTypeWrapper GetPropertyType(StaticPropertyWrapper property)
{
IProperty propertyHandle = (IProperty)property.Handle;
return MakeType(propertyHandle.Type);
}
protected override StaticMethodWrapper GetPropertyGetMethod(StaticPropertyWrapper property)
{
IProperty propertyHandle = (IProperty)property.Handle;
if (!propertyHandle.IsValid())
return null;
#if RESHARPER_31
IAccessor accessorHandle = propertyHandle.Getter(false);
#else
IAccessor accessorHandle = propertyHandle.Getter;
#endif
return accessorHandle != null && accessorHandle.IsValid() ? WrapAccessor(accessorHandle, property) : null;
}
protected override StaticMethodWrapper GetPropertySetMethod(StaticPropertyWrapper property)
{
IProperty propertyHandle = (IProperty)property.Handle;
if (!propertyHandle.IsValid())
return null;
#if RESHARPER_31
IAccessor accessorHandle = propertyHandle.Setter(false);
#else
IAccessor accessorHandle = propertyHandle.Setter;
#endif
return accessorHandle != null && accessorHandle.IsValid() ? WrapAccessor(accessorHandle, property) : null;
}
#endregion
#region Functions
protected override MethodAttributes GetFunctionAttributes(StaticFunctionWrapper function)
{
IFunction functionHandle = (IFunction)function.Handle;
AccessRights accessRights = functionHandle.GetAccessRights();
if (functionHandle is DefaultConstructor && function.DeclaringType.IsAbstract)
accessRights = AccessRights.PROTECTED;
MethodAttributes flags = 0;
switch (accessRights)
{
case AccessRights.PUBLIC:
flags |= MethodAttributes.Public;
break;
case AccessRights.NONE:
case AccessRights.PRIVATE:
flags |= MethodAttributes.Private;
break;
case AccessRights.INTERNAL:
flags |= MethodAttributes.Assembly;
break;
case AccessRights.PROTECTED:
flags |= MethodAttributes.Family;
break;
case AccessRights.PROTECTED_AND_INTERNAL:
flags |= MethodAttributes.FamANDAssem;
break;
case AccessRights.PROTECTED_OR_INTERNAL:
flags |= MethodAttributes.FamORAssem;
break;
}
bool isVirtual = functionHandle.IsVirtual || functionHandle.IsAbstract || functionHandle.IsOverride;
if (!isVirtual)
{
IOverridableMember overridableMember = functionHandle as IOverridableMember;
if (overridableMember != null && overridableMember.IsExplicitImplementation)
isVirtual = true;
}
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, MethodAttributes.Abstract, functionHandle.IsAbstract);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, MethodAttributes.Final, isVirtual && ! CanBeOverriden(functionHandle));
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, MethodAttributes.Static, functionHandle.IsStatic);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, MethodAttributes.Virtual, isVirtual);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, MethodAttributes.NewSlot, isVirtual && !functionHandle.IsOverride);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, MethodAttributes.HideBySig, true); //FIXME unreliable: functionHandle.HidePolicy == MemberHidePolicy.HIDE_BY_SIGNATURE);
return flags;
}
private static bool CanBeOverriden(IFunction functionHandle)
{
#if RESHARPER_31
return functionHandle.CanBeOverriden;
#else
return functionHandle.CanBeOverriden();
#endif
}
protected override CallingConventions GetFunctionCallingConvention(StaticFunctionWrapper function)
{
IFunction functionHandle = (IFunction)function.Handle;
// FIXME: No way to determine VarArgs convention.
CallingConventions flags = CallingConventions.Standard;
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, CallingConventions.HasThis, !functionHandle.IsStatic);
return flags;
}
protected override IList<StaticParameterWrapper> GetFunctionParameters(StaticFunctionWrapper function)
{
IFunction functionHandle = (IFunction)function.Handle;
if (!functionHandle.IsValid())
return EmptyArray<StaticParameterWrapper>.Instance;
return GenericCollectionUtils.ConvertAllToArray<IParameter, StaticParameterWrapper>(functionHandle.Parameters, delegate(IParameter parameter)
{
return new StaticParameterWrapper(this, parameter, function);
});
}
#endregion
#region Methods
protected override IList<StaticGenericParameterWrapper> GetMethodGenericParameters(StaticMethodWrapper method)
{
IFunction methodHandle = (IFunction)method.Handle;
if (!methodHandle.IsValid())
return EmptyArray<StaticGenericParameterWrapper>.Instance;
ITypeParameter[] parameterHandles = methodHandle.GetSignature(methodHandle.IdSubstitution).GetTypeParameters();
return Array.ConvertAll<ITypeParameter, StaticGenericParameterWrapper>(parameterHandles, delegate(ITypeParameter parameter)
{
return StaticGenericParameterWrapper.CreateGenericMethodParameter(this, parameter, method);
});
}
protected override StaticParameterWrapper GetMethodReturnParameter(StaticMethodWrapper method)
{
IFunction methodHandle = (IFunction)method.Handle;
if (!methodHandle.IsValid())
return null;
// TODO: This won't provide access to any parameter attributes. How should we retrieve them?
IType type = methodHandle.ReturnType;
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
if (type == null || ! type.IsValid)
#else
if (type == null || ! type.IsValid())
#endif
return null;
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
var parameter = new Parameter(methodHandle, type, null);
#else
var parameter = new Parameter(methodHandle, 0, type, null);
#endif
return new StaticParameterWrapper(this, parameter, method);
}
#endregion
#region Parameters
protected override ParameterAttributes GetParameterAttributes(StaticParameterWrapper parameter)
{
IParameter parameterHandle = (IParameter)parameter.Handle;
ParameterAttributes flags = 0;
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, ParameterAttributes.HasDefault, !parameterHandle.GetDefaultValue().IsBadValue());
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, ParameterAttributes.In, parameterHandle.Kind == ParameterKind.REFERENCE);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, ParameterAttributes.Out, parameterHandle.Kind == ParameterKind.OUTPUT || parameterHandle.Kind == ParameterKind.REFERENCE);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, ParameterAttributes.Optional, parameterHandle.IsOptional);
return flags;
}
protected override IEnumerable<StaticAttributeWrapper> GetParameterCustomAttributes(StaticParameterWrapper parameter)
{
IParameter parameterHandle = (IParameter)parameter.Handle;
return GetAttributesForAttributeOwner(parameterHandle);
}
protected override string GetParameterName(StaticParameterWrapper parameter)
{
IParameter parameterHandle = (IParameter)parameter.Handle;
return parameterHandle.ShortName;
}
protected override int GetParameterPosition(StaticParameterWrapper parameter)
{
IParameter parameterHandle = (IParameter)parameter.Handle;
int parameterIndex = parameterHandle.ContainingParametersOwner.Parameters.IndexOf(parameterHandle);
return parameterIndex;
}
protected override StaticTypeWrapper GetParameterType(StaticParameterWrapper parameter)
{
IParameter parameterHandle = (IParameter)parameter.Handle;
StaticTypeWrapper parameterType = MakeType(parameterHandle.Type);
if (parameterHandle.Kind != ParameterKind.VALUE)
parameterType = parameterType.MakeByRefType();
return parameterType;
}
#endregion
#region Types
protected override TypeAttributes GetTypeAttributes(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement) type.Handle;
TypeAttributes flags = 0;
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, TypeAttributes.Interface, typeHandle is IInterface);
IModifiersOwner modifiers = typeHandle as IModifiersOwner;
if (modifiers != null)
{
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, TypeAttributes.Abstract, modifiers.IsAbstract);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, TypeAttributes.Sealed, modifiers.IsSealed);
bool isNested = typeHandle.GetContainingType() != null;
switch (modifiers.GetAccessRights())
{
case AccessRights.PUBLIC:
flags |= isNested ? TypeAttributes.NestedPublic : TypeAttributes.Public;
break;
case AccessRights.PRIVATE:
flags |= isNested ? TypeAttributes.NestedPrivate : TypeAttributes.NotPublic;
break;
case AccessRights.NONE:
case AccessRights.INTERNAL:
flags |= isNested ? TypeAttributes.NestedAssembly : TypeAttributes.NotPublic;
break;
case AccessRights.PROTECTED:
flags |= isNested ? TypeAttributes.NestedFamily : TypeAttributes.NotPublic;
break;
case AccessRights.PROTECTED_AND_INTERNAL:
flags |= isNested ? TypeAttributes.NestedFamANDAssem : TypeAttributes.NotPublic;
break;
case AccessRights.PROTECTED_OR_INTERNAL:
flags |= isNested ? TypeAttributes.NestedFamORAssem : TypeAttributes.NotPublic;
break;
}
}
if (typeHandle is IDelegate || typeHandle is IEnum || typeHandle is IStruct)
flags |= TypeAttributes.Sealed;
return flags;
}
protected override StaticAssemblyWrapper GetTypeAssembly(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
return WrapModule(GetModule(typeHandle));
}
private IModule GetModule(IDeclaredElement declaredElement)
{
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
return declaredElement.Module;
#else
return declaredElement.Module.ContainingProjectModule;
#endif
}
protected override string GetTypeNamespace(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
return "";
return typeHandle.GetContainingNamespace().QualifiedName;
}
protected override StaticDeclaredTypeWrapper GetTypeBaseType(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
return null;
if (!(typeHandle is IInterface))
{
foreach (IDeclaredType superTypeHandle in SafeGetSuperTypes(typeHandle))
{
IClass @class = superTypeHandle.GetTypeElement() as IClass;
if (@class != null)
{
StaticDeclaredTypeWrapper baseType = MakeDeclaredType(superTypeHandle);
// Handles an edge case where the base type is also the containing type of the original type.
// This can occur when the original type is nested within its own basetype.
// In that case, the containing type should be parameterized by the generic type parameters
// of the nested that apply to it.
int containingTypeParamCount = baseType.GenericArguments.Count;
if (containingTypeParamCount != 0 && IsContainingType(@class, typeHandle))
{
var containingTypeArgs = new ITypeInfo[containingTypeParamCount];
IList<ITypeInfo> genericArgs = type.GenericArguments;
for (int i = 0; i < containingTypeParamCount; i++)
containingTypeArgs[i] = genericArgs[i];
baseType = baseType.MakeGenericType(containingTypeArgs);
}
return baseType;
}
}
}
return null;
}
protected override IList<StaticDeclaredTypeWrapper> GetTypeInterfaces(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
return EmptyArray<StaticDeclaredTypeWrapper>.Instance;
List<StaticDeclaredTypeWrapper> interfaces = new List<StaticDeclaredTypeWrapper>();
foreach (IDeclaredType superTypeHandle in SafeGetSuperTypes(typeHandle))
{
IInterface @interface = superTypeHandle.GetTypeElement() as IInterface;
if (@interface != null)
interfaces.Add(MakeDeclaredType(superTypeHandle));
}
return interfaces;
}
private static bool IsContainingType(ITypeElement candidateContainingType, ITypeElement type)
{
ITypeElement containingType = type;
for (; ; )
{
containingType = containingType.GetContainingType();
if (containingType == null)
return false;
if (containingType.Equals(candidateContainingType))
return true;
}
}
/// <summary>
/// It is possible for GetSuperTypes to return types that would form a cycle
/// if the user typed in something like "class A : A" (even accidentally).
/// This will cause big problems down the line so we drop supertypes with cycles.
/// </summary>
private static IEnumerable<IDeclaredType> SafeGetSuperTypes(ITypeElement typeElement)
{
if (!typeElement.IsValid())
yield break;
IList<IDeclaredType> superTypes = typeElement.GetSuperTypes();
if (superTypes.Count == 0)
yield break;
foreach (IDeclaredType superType in typeElement.GetSuperTypes())
{
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
if (superType.IsValid)
#else
if (superType.IsValid())
#endif
{
ITypeElement superTypeElement = superType.GetTypeElement();
if (superTypeElement.IsValid())
{
if (!HasSuperTypeCycle(superTypeElement))
yield return superType;
}
}
}
}
private static bool HasSuperTypeCycle(ITypeElement typeElement)
{
var visitedSet = new Gallio.Common.Collections.HashSet<ITypeElement>();
var queue = new Queue<ITypeElement>();
queue.Enqueue(typeElement);
while (queue.Count > 0)
{
ITypeElement currentTypeElement = queue.Dequeue();
if (visitedSet.Contains(currentTypeElement))
continue;
visitedSet.Add(currentTypeElement);
foreach (IDeclaredType superType in currentTypeElement.GetSuperTypes())
{
ITypeElement superTypeElement = superType.GetTypeElement();
if (superTypeElement == typeElement)
return true;
queue.Enqueue(superTypeElement);
}
}
return false;
}
protected override IList<StaticGenericParameterWrapper> GetTypeGenericParameters(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
return EmptyArray<StaticGenericParameterWrapper>.Instance;
var genericParameters = new List<StaticGenericParameterWrapper>();
BuildTypeGenericParameters(type, typeHandle, genericParameters);
return genericParameters;
}
private void BuildTypeGenericParameters(StaticDeclaredTypeWrapper ownerType, ITypeElement typeHandle, List<StaticGenericParameterWrapper> genericParameters)
{
ITypeElement declaringType = typeHandle.GetContainingType();
if (declaringType != null)
BuildTypeGenericParameters(ownerType, declaringType, genericParameters);
foreach (ITypeParameter parameterHandle in typeHandle.TypeParameters)
genericParameters.Add(StaticGenericParameterWrapper.CreateGenericTypeParameter(this, parameterHandle, ownerType));
}
protected override IEnumerable<StaticConstructorWrapper> GetTypeConstructors(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
yield break;
bool foundDefault = false;
foreach (IConstructor constructorHandle in typeHandle.Constructors)
{
if (constructorHandle.IsValid())
{
if (constructorHandle.IsDefault)
{
if (typeHandle is IStruct)
continue; // Note: Default constructors for structs are not visible via reflection
foundDefault = true;
}
yield return new StaticConstructorWrapper(this, constructorHandle, type);
}
}
if (!foundDefault)
{
IClass classHandle = typeHandle as IClass;
if (classHandle != null && !classHandle.IsStatic)
yield return new StaticConstructorWrapper(this, new DefaultConstructor(typeHandle), type);
IDelegate delegateHandle = typeHandle as IDelegate;
if (delegateHandle != null)
yield return new StaticConstructorWrapper(this, new DelegateConstructor(delegateHandle), type);
}
}
protected override IEnumerable<StaticMethodWrapper> GetTypeMethods(StaticDeclaredTypeWrapper type,
StaticDeclaredTypeWrapper reflectedType)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
yield break;
foreach (IMethod methodHandle in typeHandle.Methods)
{
if (methodHandle.IsValid())
yield return new StaticMethodWrapper(this, methodHandle, type, reflectedType, type.Substitution);
}
foreach (IOperator operatorHandle in typeHandle.Operators)
{
if (operatorHandle.IsValid())
yield return new StaticMethodWrapper(this, operatorHandle, type, reflectedType, type.Substitution);
}
foreach (StaticPropertyWrapper property in GetTypeProperties(type, reflectedType))
{
if (property.GetMethod != null)
yield return property.GetMethod;
if (property.SetMethod != null)
yield return property.SetMethod;
}
foreach (StaticEventWrapper @event in GetTypeEvents(type, reflectedType))
{
if (@event.AddMethod != null)
yield return @event.AddMethod;
if (@event.RemoveMethod != null)
yield return @event.RemoveMethod;
if (@event.RaiseMethod != null)
yield return @event.RaiseMethod;
}
}
protected override IEnumerable<StaticPropertyWrapper> GetTypeProperties(StaticDeclaredTypeWrapper type,
StaticDeclaredTypeWrapper reflectedType)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
yield break;
foreach (IProperty propertyHandle in typeHandle.Properties)
{
if (propertyHandle.IsValid())
yield return new StaticPropertyWrapper(this, propertyHandle, type, reflectedType);
}
}
protected override IEnumerable<StaticFieldWrapper> GetTypeFields(StaticDeclaredTypeWrapper type,
StaticDeclaredTypeWrapper reflectedType)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
yield break;
IClass classHandle = typeHandle as IClass;
if (classHandle != null)
{
foreach (IField fieldHandle in classHandle.Fields)
{
if (fieldHandle.IsValid())
yield return new StaticFieldWrapper(this, fieldHandle, type, reflectedType);
}
foreach (IField fieldHandle in classHandle.Constants)
{
if (fieldHandle.IsValid())
yield return new StaticFieldWrapper(this, fieldHandle, type, reflectedType);
}
}
else
{
IStruct structHandle = typeHandle as IStruct;
if (structHandle != null)
{
foreach (IField fieldHandle in structHandle.Fields)
{
if (fieldHandle.IsValid())
yield return new StaticFieldWrapper(this, fieldHandle, type, reflectedType);
}
foreach (IField fieldHandle in structHandle.Constants)
{
if (fieldHandle.IsValid())
yield return new StaticFieldWrapper(this, fieldHandle, type, reflectedType);
}
}
}
}
protected override IEnumerable<StaticEventWrapper> GetTypeEvents(StaticDeclaredTypeWrapper type,
StaticDeclaredTypeWrapper reflectedType)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
yield break;
foreach (IEvent eventHandle in typeHandle.Events)
{
if (eventHandle.IsValid())
yield return new StaticEventWrapper(this, eventHandle, type, reflectedType);
}
}
protected override IEnumerable<StaticTypeWrapper> GetTypeNestedTypes(StaticDeclaredTypeWrapper type)
{
ITypeElement typeHandle = (ITypeElement)type.Handle;
if (!typeHandle.IsValid())
yield break;
foreach (ITypeElement nestedTypeHandle in typeHandle.NestedTypes)
{
if (nestedTypeHandle.IsValid())
yield return new StaticDeclaredTypeWrapper(this, nestedTypeHandle, type, type.Substitution);
}
}
private StaticTypeWrapper MakeType(IType typeHandle)
{
return typeMemoizer.Memoize(typeHandle, () =>
{
IDeclaredType declaredTypeHandle = typeHandle as IDeclaredType;
if (declaredTypeHandle != null)
return MakeType(declaredTypeHandle);
IArrayType arrayTypeHandle = typeHandle as IArrayType;
if (arrayTypeHandle != null)
return MakeArrayType(arrayTypeHandle);
IPointerType pointerTypeHandle = typeHandle as IPointerType;
if (pointerTypeHandle != null)
return MakePointerType(pointerTypeHandle);
throw new NotSupportedException("Unsupported type: " + typeHandle);
});
}
private StaticTypeWrapper MakeType(IDeclaredType typeHandle)
{
ITypeParameter typeParameterHandle = typeHandle.GetTypeElement() as ITypeParameter;
if (typeParameterHandle != null)
return MakeGenericParameterType(typeParameterHandle);
return MakeDeclaredType(typeHandle);
}
private StaticTypeWrapper MakeTypeWithoutSubstitution(ITypeElement typeElementHandle)
{
ITypeParameter typeParameterHandle = typeElementHandle as ITypeParameter;
if (typeParameterHandle != null)
return MakeGenericParameterType(typeParameterHandle);
return MakeDeclaredTypeWithoutSubstitution(typeElementHandle);
}
private StaticDeclaredTypeWrapper MakeDeclaredTypeWithoutSubstitution(ITypeElement typeElementHandle)
{
return typeWithoutSubstitutionMemoizer.Memoize(typeElementHandle, () =>
{
return MakeDeclaredType(typeElementHandle, typeElementHandle.IdSubstitution);
});
}
private StaticDeclaredTypeWrapper MakeDeclaredType(IDeclaredType typeHandle)
{
return declaredTypeMemoizer.Memoize(typeHandle, () =>
{
ITypeElement typeElement = typeHandle.GetTypeElement();
if (typeElement == null)
throw new ReflectionResolveException(
String.Format(
"Cannot obtain type element for type '{0}' possibly because its source code is not available.",
typeHandle.GetCLRName()));
return MakeDeclaredType(typeElement, typeHandle.GetSubstitution());
});
}
private StaticDeclaredTypeWrapper MakeDeclaredType(ITypeElement typeElementHandle, ISubstitution substitutionHandle)
{
if (typeElementHandle is ITypeParameter)
throw new ArgumentException("This method should never be called with a generic parameter as input.",
"typeElementHandle");
ITypeElement declaringTypeElementHandle = typeElementHandle.GetContainingType();
StaticDeclaredTypeWrapper type;
if (declaringTypeElementHandle != null)
{
StaticDeclaredTypeWrapper declaringType = MakeDeclaredType(declaringTypeElementHandle,
substitutionHandle);
type = new StaticDeclaredTypeWrapper(this, typeElementHandle, declaringType, declaringType.Substitution);
}
else
{
type = new StaticDeclaredTypeWrapper(this, typeElementHandle, null, StaticTypeSubstitution.Empty);
}
#if ! RESHARPER_50_OR_NEWER
var typeParameterHandles = new List<ITypeParameter>(typeElementHandle.AllTypeParameters);
#else
var typeParameterHandles = new List<ITypeParameter>(typeElementHandle.GetAllTypeParameters());
#endif
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
if (substitutionHandle.IsIdempotent(typeParameterHandles))
#else
if (substitutionHandle.IsIdempotentAll(typeParameterHandles))
#endif
{
return type;
}
ITypeInfo[] genericArguments = GenericCollectionUtils.ConvertAllToArray<ITypeParameter, ITypeInfo>(typeParameterHandles, delegate(ITypeParameter typeParameterHandle)
{
IType substitutedType = substitutionHandle.Apply(typeParameterHandle);
if (substitutedType.IsUnknown)
return MakeGenericParameterType(typeParameterHandle);
return MakeType(substitutedType);
});
return type.MakeGenericType(genericArguments);
}
private StaticArrayTypeWrapper MakeArrayType(IArrayType arrayTypeHandle)
{
return MakeType(arrayTypeHandle.ElementType).MakeArrayType(arrayTypeHandle.Rank);
}
private StaticPointerTypeWrapper MakePointerType(IPointerType pointerTypeHandle)
{
return MakeType(pointerTypeHandle.ElementType).MakePointerType();
}
private StaticGenericParameterWrapper MakeGenericParameterType(ITypeParameter typeParameterHandle)
{
ITypeElement declaringTypeHandle = typeParameterHandle.OwnerType;
if (declaringTypeHandle != null)
{
return StaticGenericParameterWrapper.CreateGenericTypeParameter(this, typeParameterHandle, MakeDeclaredTypeWithoutSubstitution(declaringTypeHandle));
}
else
{
return StaticGenericParameterWrapper.CreateGenericMethodParameter(this, typeParameterHandle, Wrap(typeParameterHandle.OwnerMethod));
}
}
#endregion
#region Generic Parameters
protected override GenericParameterAttributes GetGenericParameterAttributes(StaticGenericParameterWrapper genericParameter)
{
ITypeParameter genericParameterHandle = (ITypeParameter)genericParameter.Handle;
GenericParameterAttributes flags = 0;
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, GenericParameterAttributes.NotNullableValueTypeConstraint, genericParameterHandle.IsValueType);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, GenericParameterAttributes.ReferenceTypeConstraint, genericParameterHandle.IsClassType);
ReflectorFlagsUtils.AddFlagIfTrue(ref flags, GenericParameterAttributes.DefaultConstructorConstraint, genericParameterHandle.HasDefaultConstructor);
return flags;
}
protected override int GetGenericParameterPosition(StaticGenericParameterWrapper genericParameter)
{
ITypeParameter genericParameterHandle = (ITypeParameter)genericParameter.Handle;
int parameterIndex = genericParameterHandle.Index;
// Must also factor in generic parameters of declaring types.
for (ITypeElement declaringType = genericParameterHandle.OwnerType; declaringType != null; )
{
declaringType = declaringType.GetContainingType();
if (declaringType == null)
break;
parameterIndex += declaringType.TypeParameters.Length;
}
return parameterIndex;
}
protected override IList<StaticTypeWrapper> GetGenericParameterConstraints(StaticGenericParameterWrapper genericParameter)
{
ITypeParameter genericParameterHandle = (ITypeParameter)genericParameter.Handle;
return GenericCollectionUtils.ConvertAllToArray<IType, StaticTypeWrapper>(genericParameterHandle.TypeConstraints, MakeType);
}
#endregion
#region GetDeclaredElementResolver and GetProject
protected override IDeclaredElementResolver GetDeclaredElementResolver(StaticWrapper element)
{
IDeclaredElement declaredElement = GetDeclaredElement(element);
return new DeclaredElementResolver(declaredElement);
}
protected override IProject GetProject(StaticWrapper element)
{
IProject project = element.Handle as IProject;
if (project != null)
return project;
IDeclaredElement declaredElement = GetDeclaredElement(element);
return declaredElement != null && declaredElement.IsValid() ? GetModule(declaredElement) as IProject : null;
}
private IDeclaredElement GetDeclaredElement(StaticWrapper element)
{
return element.Handle as IDeclaredElement;
}
private sealed class DeclaredElementResolver : IDeclaredElementResolver
{
private readonly IDeclaredElement declaredElement;
public DeclaredElementResolver(IDeclaredElement declaredElement)
{
this.declaredElement = declaredElement;
}
public IDeclaredElement ResolveDeclaredElement()
{
return declaredElement;
}
}
#endregion
#region Misc
private IEnumerable<StaticAttributeWrapper> GetAttributesForAttributeOwner(IAttributesOwner owner)
{
if (!owner.IsValid())
yield break;
foreach (IAttributeInstance attribute in owner.GetAttributeInstances(false))
{
if (IsAttributeInstanceValid(attribute))
yield return new StaticAttributeWrapper(this, attribute);
}
}
private StaticMethodWrapper WrapAccessor(IAccessor accessorHandle, StaticMemberWrapper member)
{
return accessorHandle != null ? new StaticMethodWrapper(this, accessorHandle, member.DeclaringType, member.ReflectedType, member.Substitution) : null;
}
#endregion
#region HACKS
#if RESHARPER_31
private static FieldInfo CSharpAttributeInstanceMyAttributeField;
private ConstantValue2 GetAttributePositionParameterHack(IAttributeInstance attributeInstance, int index)
{
IAttribute attribute = GetCSharpAttributeHack(attributeInstance);
if (attribute != null)
{
IList<ICSharpArgument> arguments = attribute.Arguments;
if (index >= arguments.Count)
return ConstantValue2.BAD_VALUE;
ICSharpExpression expression = arguments[index].Value;
IList<IParameter> parameters = attributeInstance.Constructor.Parameters;
int lastParameterIndex = parameters.Count - 1;
if (index >= lastParameterIndex && parameters[lastParameterIndex].IsParameterArray)
return GetCSharpConstantValueHack(expression, ((IArrayType)parameters[lastParameterIndex].Type).ElementType);
return GetCSharpConstantValueHack(arguments[index].Value, parameters[index].Type);
}
return attributeInstance.PositionParameter(index);
}
private ConstantValue2 GetAttributeNamedParameterHack(IAttributeInstance attributeInstance, ITypeMember typeMember)
{
IAttribute attribute = GetCSharpAttributeHack(attributeInstance);
if (attribute != null)
{
foreach (IPropertyAssignmentNode propertyAssignmentNode in attribute.ToTreeNode().PropertyAssignments)
{
IPropertyAssignment propertyAssignment = propertyAssignmentNode;
if (propertyAssignment.Reference.Resolve().DeclaredElement == typeMember)
{
IType propertyType = ((ITypeOwner)typeMember).Type;
ICSharpExpression expression = propertyAssignment.Source;
return GetCSharpConstantValueHack(expression, propertyType);
}
}
return ConstantValue2.BAD_VALUE;
}
return attributeInstance.NamedParameter(typeMember);
}
private IAttribute GetCSharpAttributeHack(IAttributeInstance attributeInstance)
{
if (attributeInstance.GetType().Name != "CSharpAttributeInstance")
return null;
if (CSharpAttributeInstanceMyAttributeField == null)
CSharpAttributeInstanceMyAttributeField = attributeInstance.GetType().GetField("myAttribute",
BindingFlags.Instance | BindingFlags.NonPublic);
if (CSharpAttributeInstanceMyAttributeField == null)
return null;
return (IAttribute) CSharpAttributeInstanceMyAttributeField.GetValue(attributeInstance);
}
private ConstantValue2 GetCSharpConstantValueHack(ICSharpExpression expression, IType type)
{
if (expression == null)
return ConstantValue2.NOT_COMPILE_TIME_CONSTANT;
IArrayCreationExpression arrayExpression = expression as IArrayCreationExpression;
if (arrayExpression != null)
{
int[] dimensions = arrayExpression.Dimensions;
int rank = dimensions.Length;
for (int i = 0; i < rank; i++)
if (dimensions[i] != 1)
return ConstantValue2.NOT_COMPILE_TIME_CONSTANT;
IArrayType arrayType = arrayExpression.Type() as IArrayType;
if (arrayType == null)
return ConstantValue2.NOT_COMPILE_TIME_CONSTANT;
IArrayInitializer arrayInitializer = arrayExpression.Initializer;
if (arrayInitializer == null)
return ConstantValue2.NOT_COMPILE_TIME_CONSTANT;
IType elementType = arrayType.ElementType;
Type resolvedScalarType = MakeType(arrayType.GetScalarType()).Resolve(true);
if (resolvedScalarType == typeof(Type))
resolvedScalarType = typeof(IType);
Type resolvedElementType = rank == 1 ? resolvedScalarType : rank == 2 ? resolvedScalarType.MakeArrayType() : resolvedScalarType.MakeArrayType(rank - 1);
IList<IVariableInitializer> elementInitializers = arrayInitializer.ElementInitializers;
int length = elementInitializers.Count;
Array array = Array.CreateInstance(resolvedElementType, length);
for (int i = 0; i < length; i++)
{
IExpressionInitializer initializer = elementInitializers[i] as IExpressionInitializer;
if (initializer == null)
return ConstantValue2.NOT_COMPILE_TIME_CONSTANT;
ConstantValue2 elementValue = GetCSharpConstantValueHack(initializer.Value, elementType);
if (elementValue.IsBadValue())
return ConstantValue2.NOT_COMPILE_TIME_CONSTANT;
array.SetValue(elementValue.Value, i);
}
return new ConstantValue2(array, arrayType, type.GetManager().Solution);
}
ITypeofExpression typeExpression = expression as ITypeofExpression;
if (typeExpression != null)
{
return new ConstantValue2(typeExpression.ArgumentType, type, type.GetManager().Solution);
}
return expression.ConstantCalculator.ToTypeImplicit(expression.CompileTimeConstantValue(), type);
}
#endif
#endregion
private bool IsAttributeInstanceValid(IAttributeInstance attrib)
{
return attrib.Constructor != null && attrib.AttributeType != null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting.Indentation;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation
{
internal partial class CSharpIndentationService
{
internal class Indenter : AbstractIndenter
{
public Indenter(Document document, IEnumerable<IFormattingRule> rules, OptionSet optionSet, ITextSnapshotLine line, CancellationToken cancellationToken) :
base(document, rules, optionSet, line, cancellationToken)
{
}
public override IndentationResult? GetDesiredIndentation()
{
var indentStyle = OptionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp);
if (indentStyle == FormattingOptions.IndentStyle.None)
{
return null;
}
// find previous line that is not blank
var previousLine = GetPreviousNonBlankOrPreprocessorLine();
// it is beginning of the file, there is no previous line exists.
// in that case, indentation 0 is our base indentation.
if (previousLine == null)
{
return IndentFromStartOfLine(0);
}
// okay, now see whether previous line has anything meaningful
var lastNonWhitespacePosition = previousLine.GetLastNonWhitespacePosition();
if (!lastNonWhitespacePosition.HasValue)
{
return null;
}
// there is known parameter list "," parse bug. if previous token is "," from parameter list,
// FindToken will not be able to find them.
var token = Tree.GetRoot(CancellationToken).FindToken(lastNonWhitespacePosition.Value);
if (token.IsKind(SyntaxKind.None) || indentStyle == FormattingOptions.IndentStyle.Block)
{
return GetIndentationOfLine(previousLine);
}
// okay, now check whether the text we found is trivia or actual token.
if (token.Span.Contains(lastNonWhitespacePosition.Value))
{
// okay, it is a token case, do special work based on type of last token on previous line
return GetIndentationBasedOnToken(token);
}
else
{
// there must be trivia that contains or touch this position
Contract.Assert(token.FullSpan.Contains(lastNonWhitespacePosition.Value));
// okay, now check whether the trivia is at the beginning of the line
var firstNonWhitespacePosition = previousLine.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return IndentFromStartOfLine(0);
}
var trivia = Tree.GetRoot(CancellationToken).FindTrivia(firstNonWhitespacePosition.Value, findInsideTrivia: true);
if (trivia.Kind() == SyntaxKind.None || this.LineToBeIndented.LineNumber > previousLine.LineNumber + 1)
{
// If the token belongs to the next statement and is also the first token of the statement, then it means the user wants
// to start type a new statement. So get indentation from the start of the line but not based on the token.
// Case:
// static void Main(string[] args)
// {
// // A
// // B
//
// $$
// return;
// }
var containingStatement = token.GetAncestor<StatementSyntax>();
if (containingStatement != null && containingStatement.GetFirstToken() == token)
{
var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start);
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
// If the token previous of the base token happens to be a Comma from a separation list then we need to handle it different
// Case:
// var s = new List<string>
// {
// """",
// """",/*sdfsdfsdfsdf*/
// // dfsdfsdfsdfsdf
//
// $$
// };
var previousToken = token.GetPreviousToken();
if (previousToken.IsKind(SyntaxKind.CommaToken))
{
return GetIndentationFromCommaSeparatedList(previousToken);
}
else if (!previousToken.IsKind(SyntaxKind.None))
{
// okay, beginning of the line is not trivia, use the last token on the line as base token
return GetIndentationBasedOnToken(token);
}
}
// this case we will keep the indentation of this trivia line
// this trivia can't be preprocessor by the way.
return GetIndentationOfLine(previousLine);
}
}
private IndentationResult? GetIndentationBasedOnToken(SyntaxToken token)
{
Contract.ThrowIfNull(LineToBeIndented);
Contract.ThrowIfNull(Tree);
Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None);
// special cases
// case 1: token belongs to verbatim token literal
// case 2: $@"$${0}"
// case 3: $@"Comment$$ inbetween{0}"
// case 4: $@"{0}$$"
if (token.IsVerbatimStringLiteral() ||
token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) ||
token.IsKind(SyntaxKind.InterpolatedStringTextToken) ||
(token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation)))
{
return IndentFromStartOfLine(0);
}
// if previous statement belong to labeled statement, don't follow label's indentation
// but its previous one.
if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement())
{
token = token.GetAncestor<LabeledStatementSyntax>().GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true);
}
var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start);
// first check operation service to see whether we can determine indentation from it
var indentation = Finder.FromIndentBlockOperations(Tree, token, position, CancellationToken);
if (indentation.HasValue)
{
return IndentFromStartOfLine(indentation.Value);
}
var alignmentTokenIndentation = Finder.FromAlignTokensOperations(Tree, token);
if (alignmentTokenIndentation.HasValue)
{
return IndentFromStartOfLine(alignmentTokenIndentation.Value);
}
// if we couldn't determine indentation from the service, use heuristic to find indentation.
var snapshot = LineToBeIndented.Snapshot;
// If this is the last token of an embedded statement, walk up to the top-most parenting embedded
// statement owner and use its indentation.
//
// cases:
// if (true)
// if (false)
// Foo();
//
// if (true)
// { }
if (token.IsSemicolonOfEmbeddedStatement() ||
token.IsCloseBraceOfEmbeddedBlock())
{
Contract.Requires(
token.Parent != null &&
(token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax));
var embeddedStatementOwner = token.Parent.Parent;
while (embeddedStatementOwner.IsEmbeddedStatement())
{
embeddedStatementOwner = embeddedStatementOwner.Parent;
}
return GetIndentationOfLine(snapshot.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart));
}
switch (token.Kind())
{
case SyntaxKind.SemicolonToken:
{
// special cases
if (token.IsSemicolonInForStatement())
{
return GetDefaultIndentationFromToken(token);
}
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
case SyntaxKind.CloseBraceToken:
{
if (token.Parent.IsKind(SyntaxKind.AccessorList) &&
token.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration))
{
if (token.GetNextToken().IsEqualsTokenInAutoPropertyInitializers())
{
return GetDefaultIndentationFromToken(token);
}
}
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
case SyntaxKind.OpenBraceToken:
{
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
case SyntaxKind.ColonToken:
{
var nonTerminalNode = token.Parent;
Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???");
if (nonTerminalNode is SwitchLabelSyntax)
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language));
}
// default case
return GetDefaultIndentationFromToken(token);
}
case SyntaxKind.CloseBracketToken:
{
var nonTerminalNode = token.Parent;
Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???");
// if this is closing an attribute, we shouldn't indent.
if (nonTerminalNode is AttributeListSyntax)
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart));
}
// default case
return GetDefaultIndentationFromToken(token);
}
case SyntaxKind.XmlTextLiteralToken:
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(token.SpanStart));
}
case SyntaxKind.CommaToken:
{
return GetIndentationFromCommaSeparatedList(token);
}
default:
{
return GetDefaultIndentationFromToken(token);
}
}
}
private IndentationResult? GetIndentationFromCommaSeparatedList(SyntaxToken token)
{
var node = token.Parent;
var argument = node as BaseArgumentListSyntax;
if (argument != null)
{
return GetIndentationFromCommaSeparatedList(argument.Arguments, token);
}
var parameter = node as BaseParameterListSyntax;
if (parameter != null)
{
return GetIndentationFromCommaSeparatedList(parameter.Parameters, token);
}
var typeArgument = node as TypeArgumentListSyntax;
if (typeArgument != null)
{
return GetIndentationFromCommaSeparatedList(typeArgument.Arguments, token);
}
var typeParameter = node as TypeParameterListSyntax;
if (typeParameter != null)
{
return GetIndentationFromCommaSeparatedList(typeParameter.Parameters, token);
}
var enumDeclaration = node as EnumDeclarationSyntax;
if (enumDeclaration != null)
{
return GetIndentationFromCommaSeparatedList(enumDeclaration.Members, token);
}
var initializerSyntax = node as InitializerExpressionSyntax;
if (initializerSyntax != null)
{
return GetIndentationFromCommaSeparatedList(initializerSyntax.Expressions, token);
}
return GetDefaultIndentationFromToken(token);
}
private IndentationResult? GetIndentationFromCommaSeparatedList<T>(SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode
{
var index = list.GetWithSeparators().IndexOf(token);
if (index < 0)
{
return GetDefaultIndentationFromToken(token);
}
// find node that starts at the beginning of a line
var snapshot = LineToBeIndented.Snapshot;
for (int i = (index - 1) / 2; i >= 0; i--)
{
var node = list[i];
var firstToken = node.GetFirstToken(includeZeroWidth: true);
if (firstToken.IsFirstTokenOnLine(snapshot))
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(firstToken.SpanStart));
}
}
// smart indenter has a special indent block rule for comma separated list, so don't
// need to add default additional space for multiline expressions
return GetDefaultIndentationFromTokenLine(token, additionalSpace: 0);
}
private IndentationResult? GetDefaultIndentationFromToken(SyntaxToken token)
{
if (IsPartOfQueryExpression(token))
{
return GetIndentationForQueryExpression(token);
}
return GetDefaultIndentationFromTokenLine(token);
}
private IndentationResult? GetIndentationForQueryExpression(SyntaxToken token)
{
// find containing non terminal node
var queryExpressionClause = GetQueryExpressionClause(token);
Contract.ThrowIfNull(queryExpressionClause);
// find line where first token of the node is
var snapshot = LineToBeIndented.Snapshot;
var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true);
var firstTokenLine = snapshot.GetLineFromPosition(firstToken.SpanStart);
// find line where given token is
var givenTokenLine = snapshot.GetLineFromPosition(token.SpanStart);
if (firstTokenLine.LineNumber != givenTokenLine.LineNumber)
{
// do default behavior
return GetDefaultIndentationFromTokenLine(token);
}
// okay, we are right under the query expression.
// align caret to query expression
if (firstToken.IsFirstTokenOnLine(snapshot))
{
return GetIndentationOfToken(firstToken);
}
// find query body that has a token that is a first token on the line
var queryBody = queryExpressionClause.Parent as QueryBodySyntax;
if (queryBody == null)
{
return GetIndentationOfToken(firstToken);
}
// find preceding clause that starts on its own.
var clauses = queryBody.Clauses;
for (int i = clauses.Count - 1; i >= 0; i--)
{
var clause = clauses[i];
if (firstToken.SpanStart <= clause.SpanStart)
{
continue;
}
var clauseToken = clause.GetFirstToken(includeZeroWidth: true);
if (clauseToken.IsFirstTokenOnLine(snapshot))
{
var tokenSpan = clauseToken.Span.ToSnapshotSpan(snapshot);
return GetIndentationOfToken(clauseToken);
}
}
// no query clause start a line. use the first token of the query expression
return GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true));
}
private SyntaxNode GetQueryExpressionClause(SyntaxToken token)
{
var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax || n is SelectOrGroupClauseSyntax);
if (clause != null)
{
return clause;
}
// If this is a query continuation, use the last clause of its parenting query.
var body = token.GetAncestor<QueryBodySyntax>();
if (body != null)
{
if (body.SelectOrGroup.IsMissing)
{
return body.Clauses.LastOrDefault();
}
else
{
return body.SelectOrGroup;
}
}
return null;
}
private bool IsPartOfQueryExpression(SyntaxToken token)
{
var queryExpression = token.GetAncestor<QueryExpressionSyntax>();
return queryExpression != null;
}
private IndentationResult? GetDefaultIndentationFromTokenLine(SyntaxToken token, int? additionalSpace = null)
{
var spaceToAdd = additionalSpace ?? this.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language);
var snapshot = LineToBeIndented.Snapshot;
// find line where given token is
var givenTokenLine = snapshot.GetLineFromPosition(token.SpanStart);
// find right position
var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start);
// find containing non expression node
var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax);
if (nonExpressionNode == null)
{
// well, I can't find any non expression node. use default behavior
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken));
}
// find line where first token of the node is
var firstTokenLine = snapshot.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart);
// single line expression
if (firstTokenLine.LineNumber == givenTokenLine.LineNumber)
{
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken));
}
// okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token
return GetIndentationOfLine(givenTokenLine);
}
protected override bool HasPreprocessorCharacter(ITextSnapshotLine currentLine)
{
if (currentLine == null)
{
throw new ArgumentNullException(nameof(currentLine));
}
var text = currentLine.GetText();
Contract.Requires(!string.IsNullOrWhiteSpace(text));
var trimmedText = text.Trim();
Contract.Assert(SyntaxFacts.GetText(SyntaxKind.HashToken).Length == 1);
return trimmedText[0] == SyntaxFacts.GetText(SyntaxKind.HashToken)[0];
}
private int GetCurrentPositionNotBelongToEndOfFileToken(int position)
{
var compilationUnit = Tree.GetRoot(CancellationToken) as CompilationUnitSyntax;
if (compilationUnit == null)
{
return position;
}
return Math.Min(compilationUnit.EndOfFileToken.FullSpan.Start, position);
}
}
}
}
| |
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using UnityEngine;
using Object = UnityEngine.Object;
using VertexLayout = TiltBrush.GeometryPool.VertexLayout;
using TexcoordInfo = TiltBrush.GeometryPool.TexcoordInfo;
using TexcoordData = TiltBrush.GeometryPool.TexcoordData;
using Semantic = TiltBrush.GeometryPool.Semantic;
namespace TiltBrush {
internal class TestGeometryPool {
// Individual tests can write/read files in this directory
private static string TemporaryData {
get {
var dir = string.Format("{0}/../Temp/TestGeometryPool", UnityEngine.Application.dataPath);
Directory.CreateDirectory(dir);
return dir;
}
}
private static GeometryPool RandomGeometryPool() {
int vertexCount = 20;
int indexCount = 60;
var pool = new GeometryPool();
pool.Layout = new VertexLayout {
texcoord0 = new TexcoordInfo { size = 2, semantic = Semantic.XyIsUv },
bUseNormals = true,
bUseColors = true,
bUseTangents = true
};
pool.m_Vertices = MathTestUtils.RandomVector3List(vertexCount);
pool.m_Tris = MathTestUtils.RandomIntList(indexCount, 0, vertexCount);
pool.m_Normals = MathTestUtils.RandomVector3List(vertexCount);
pool.m_Colors = MathTestUtils.RandomColor32List(vertexCount);
pool.m_Tangents = MathTestUtils.RandomVector4List(vertexCount);
pool.m_Texcoord0.v2 = MathTestUtils.RandomVector2List(vertexCount);
return pool;
}
public static bool AreEqual(GeometryPool lhs, GeometryPool rhs, ref string outWhy) {
string why = "";
if (! (lhs.Layout == rhs.Layout)) {
why += "Layout,";
}
if (! (ElementEqual(lhs.m_Vertices, rhs.m_Vertices, ref why))) {
why += "verts,";
}
if (! (ElementEqual(lhs.m_Tris, rhs.m_Tris, ref why))) {
why += "tris,";
}
if (! (ElementEqual(lhs.m_Normals, rhs.m_Normals, ref why))) {
why += "normals,";
}
if (! (ElementEqual(lhs.m_Colors, rhs.m_Colors, ref why))) {
why += "colors,";
}
if (! (ElementEqual(lhs.m_Tangents, rhs.m_Tangents, ref why))) {
why += "tangents,";
}
if (! (AreEqual(lhs.m_Texcoord0, rhs.m_Texcoord0, rhs.Layout.texcoord0.size, ref why))) {
why += "texcoord0,";
}
if (! (AreEqual(lhs.m_Texcoord1, rhs.m_Texcoord1, rhs.Layout.texcoord1.size, ref why))) {
why += "texcoord1,";
}
if (! (AreEqual(lhs.m_Texcoord2, rhs.m_Texcoord2, rhs.Layout.texcoord2.size, ref why))) {
why += "texcoord2,";
}
outWhy += why;
return (why == "");
}
static bool AreEqual(TexcoordData lhs, TexcoordData rhs, int size, ref string why) {
switch (size) {
case 0: return true;
case 2: return ElementEqual(lhs.v2, rhs.v2, ref why);
case 3: return ElementEqual(lhs.v3, rhs.v3, ref why);
case 4: return ElementEqual(lhs.v4, rhs.v4, ref why);
default: return false;
}
}
static bool ElementEqual<T>(List<T> lhs, List<T> rhs, ref string why) where T: struct {
if (lhs == null && rhs == null) return true;
if (lhs == null || rhs == null) return false;
if (lhs.Count != rhs.Count) return false;
int c = lhs.Count;
for (int i = 0; i < c; ++i) {
if (! EqualityComparer<T>.Default.Equals(lhs[i], rhs[i])) {
why += string.Format("{1} != {2} at [{0}] of ", i, lhs[i], rhs[i]);
return false;
}
}
return true;
}
private static void AssertAreEqual(GeometryPool expected, GeometryPool actual) {
string why = "";
bool equal = AreEqual(expected, actual, ref why);
Assert.AreEqual("", why);
Assert.IsTrue(equal);
}
[Test]
public void TestGetSizeAndSemantic() {
var layout = new VertexLayout {
texcoord0 = new TexcoordInfo { size = 2, semantic = Semantic.XyIsUv },
texcoord1 = new TexcoordInfo { size = 3, semantic = Semantic.Position },
texcoord2 = new TexcoordInfo { size = 4, semantic = Semantic.Vector }
};
Assert.AreEqual(layout.texcoord0, layout.GetTexcoordInfo(0));
Assert.AreEqual(layout.texcoord1, layout.GetTexcoordInfo(1));
Assert.AreEqual(layout.texcoord2, layout.GetTexcoordInfo(2));
}
[Test]
public void TestTexcoordInfoEquality() {
var ti = new TexcoordInfo { size = 3, semantic = Semantic.Position };
TexcoordInfo ti2;
ti2 = ti;
Assert.AreEqual(ti, ti2);
ti2 = ti;
ti2.size += 1;
Assert.AreNotEqual(ti, ti2);
ti2 = ti;
ti2.semantic = Semantic.XyIsUvZIsDistance;
Assert.AreNotEqual(ti, ti2);
}
[Test]
public void TestLayoutAssignmentAndReset() {
var pool = new GeometryPool {
Layout = new VertexLayout {
texcoord0 = new TexcoordInfo { size = 2 },
texcoord1 = new TexcoordInfo { size = 3 },
texcoord2 = new TexcoordInfo { size = 4 },
}
};
Assert.IsNotNull(pool.m_Texcoord0.v2);
Assert.IsNotNull(pool.m_Texcoord1.v3);
Assert.IsNotNull(pool.m_Texcoord2.v4);
int N = 30;
pool.m_Texcoord0.v2.AddRange(MathTestUtils.RandomVector2List(N));
pool.m_Texcoord1.v3.AddRange(MathTestUtils.RandomVector3List(N));
pool.m_Texcoord2.v4.AddRange(MathTestUtils.RandomVector4List(N));
pool.Reset();
Assert.AreEqual(0, pool.m_Texcoord0.v2.Count);
Assert.AreEqual(0, pool.m_Texcoord1.v3.Count);
Assert.AreEqual(0, pool.m_Texcoord2.v4.Count);
}
[Test]
public void TestLayoutEquality() {
var vl = new VertexLayout {
texcoord0 = new TexcoordInfo { size = 2, semantic = Semantic.Position },
texcoord1 = new TexcoordInfo { size = 3, semantic = Semantic.Position },
texcoord2 = new TexcoordInfo { size = 4, semantic = Semantic.Position }
};
VertexLayout vl2;
vl2 = vl; Assert.AreEqual(vl, vl2);
vl2 = vl; vl2.texcoord0.size += 1; Assert.AreNotEqual(vl, vl2);
vl2 = vl; vl2.texcoord1.size += 1; Assert.AreNotEqual(vl, vl2);
vl2 = vl; vl2.texcoord2.size += 1; Assert.AreNotEqual(vl, vl2);
vl2 = vl; vl2.texcoord0.semantic = Semantic.Unspecified; Assert.AreNotEqual(vl, vl2);
vl2 = vl; vl2.texcoord1.semantic = Semantic.Unspecified; Assert.AreNotEqual(vl, vl2);
vl2 = vl; vl2.texcoord2.semantic = Semantic.Unspecified; Assert.AreNotEqual(vl, vl2);
}
[Test]
public void TestGeometryPool_Clone() {
var pool = RandomGeometryPool();
var pool2 = pool.Clone();
AssertAreEqual(pool, pool2);
}
[Test]
public void TestGeometryPool_RoundTripToStream() {
var pool = RandomGeometryPool();
var stream = new MemoryStream();
pool.SerializeToStream(stream);
// Deserialize to already-created pool; empty-pool case is handled by the next test.
var expected = pool.Clone();
stream.Position = 0;
Assert.IsTrue(pool.DeserializeFromStream(stream));
AssertAreEqual(expected, pool);
}
[Test]
public void TestGeometryPool_RoundTripToBackingFile() {
var pool = RandomGeometryPool();
var expected = pool.Clone();
var filename = Path.Combine(TemporaryData, "roundtriptobackingfile.bin");
pool.MakeGeometryNotResident(filename);
pool.EnsureGeometryResident();
AssertAreEqual(expected, pool);
}
[Test]
public void TestStructByReference() {
var pool = new GeometryPool();
pool.Layout = new VertexLayout {
texcoord0 = new TexcoordInfo { size = 2, semantic = GeometryPool.Semantic.XyIsUv }
};
Assert.IsNotNull(pool.m_Texcoord0.v2 != null);
// One or the other of m_UvSetN, m_TexcoordN is a property.
// Normally, properties can only return structs by value.
// Check that these properties are references.
pool.m_Texcoord1.v2 = pool.m_Texcoord0.v2;
Assert.IsNotNull(pool.m_Texcoord1.v2);
pool.m_Texcoord0.v2 = null;
Assert.IsNull(pool.m_Texcoord0.v2);
}
[Test]
public void TestAppendMeshFailure() {
var mesh = new Mesh();
mesh.vertices = new[] {Vector3.one};
{
var pool = new GeometryPool {Layout = new VertexLayout {bUseNormals = true}};
Assert.Throws<InvalidOperationException>(() => pool.Append(mesh));
}
{
var pool = new GeometryPool {Layout = new VertexLayout {bUseColors = true}};
Assert.Throws<InvalidOperationException>(() => pool.Append(mesh));
}
{
var pool = new GeometryPool {Layout = new VertexLayout {bUseTangents = true}};
Assert.Throws<InvalidOperationException>(() => pool.Append(mesh));
}
{
var pool = new GeometryPool {
Layout = new VertexLayout { texcoord0 = new TexcoordInfo {size = 2} } };
Assert.Throws<InvalidOperationException>(() => pool.Append(mesh));
}
Object.DestroyImmediate(mesh);
}
[Test]
public void TestAppendMeshFallback() {
var mesh = new Mesh();
mesh.vertices = new[] {Vector3.one};
var pool = new GeometryPool {Layout = new VertexLayout {bUseColors = true}};
Color32 white = Color.white;
pool.Append(mesh, fallbackColor: white);
Assert.AreEqual(white, pool.m_Colors[0]);
Object.DestroyImmediate(mesh);
}
[Test]
public void TestAppendMeshExtraData() {
// Mesh has all the data but pool doesn't want any of it
var mesh = new Mesh();
mesh.vertices = new[] {Vector3.one};
mesh.normals = new[] {Vector3.up};
mesh.SetUVs(0, new List<Vector2> { Vector2.zero });
mesh.colors = new[] {Color.white};
mesh.tangents = new[] {Vector4.one};
var pool = new GeometryPool {Layout = new VertexLayout()};
// This should not throw
pool.Append(mesh);
Object.DestroyImmediate(mesh);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.CodeAnalysis.Editor.Extensibility.Composition;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Moq;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo
{
public class InteractiveNavigateToTests : AbstractNavigateToTests
{
protected override string Language => "csharp";
protected override Task<TestWorkspace> CreateWorkspace(string content, ExportProvider exportProvider)
=> TestWorkspace.CreateCSharpAsync(content, parseOptions: Options.Script);
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task NoItemsForEmptyFile()
{
await TestAsync("", async w =>
{
Assert.Empty(await _aggregator.GetItemsAsync("Hello"));
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClass()
{
await TestAsync(
@"class Foo
{
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindNestedClass()
{
await TestAsync(
@"class Foo
{
class Bar
{
internal class DogBed
{
}
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "DogBed", MatchKind.Exact, NavigateToItemKind.Class);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMemberInANestedClass()
{
await TestAsync(
@"class Foo
{
class Bar
{
class DogBed
{
public void Method()
{
}
}
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("Method")).Single();
VerifyNavigateToResultItem(item, "Method", MatchKind.Exact, NavigateToItemKind.Method, "Method()", $"{FeaturesResources.type_space}Foo.Bar.DogBed");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindGenericClassWithConstraints()
{
await TestAsync(
@"using System.Collections;
class Foo<T> where T : IEnumerable
{
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class, displayName: "Foo<T>");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindGenericMethodWithConstraints()
{
await TestAsync(
@"using System;
class Foo<U>
{
public void Bar<T>(T item) where T : IComparable<T>
{
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("Bar")).Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar<T>(T)", $"{FeaturesResources.type_space}Foo<U>");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialClass()
{
await TestAsync(
@"public partial class Foo
{
int a;
}
partial class Foo
{
int b;
}", async w =>
{
var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = await _aggregator.GetItemsAsync("Foo");
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindTypesInMetadata()
{
await TestAsync(
@"using System;
Class Program { FileStyleUriParser f; }", async w =>
{
var items = await _aggregator.GetItemsAsync("FileStyleUriParser");
Assert.Equal(items.Count(), 0);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClassInNamespace()
{
await TestAsync(
@"namespace Bar
{
class Foo
{
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindStruct()
{
await TestAsync(
@"struct Bar
{
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Structure);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEnum()
{
await TestAsync(
@"enum Colors
{
Red,
Green,
Blue
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Colors", MatchKind.Exact, NavigateToItemKind.Enum);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEnumMember()
{
await TestAsync(
@"enum Colors
{
Red,
Green,
Blue
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("R")).Single();
VerifyNavigateToResultItem(item, "Red", MatchKind.Prefix, NavigateToItemKind.EnumItem);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindConstField()
{
await TestAsync(
@"class Foo
{
const int bar = 7;
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("ba")).Single();
VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Constant);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindVerbatimIdentifier()
{
await TestAsync(
@"class Foo
{
string @string;
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("string")).Single();
VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindIndexer()
{
var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }";
await TestAsync(program, async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("this")).Single();
VerifyNavigateToResultItem(item, "this[]", MatchKind.Exact, NavigateToItemKind.Property, displayName: "this[int]", additionalInfo: $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEvent()
{
var program = "class Foo { public event EventHandler ChangedEventHandler; }";
await TestAsync(program, async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("CEH")).Single();
VerifyNavigateToResultItem(item, "ChangedEventHandler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindAutoProperty()
{
await TestAsync(
@"class Foo
{
int Bar { get; set; }
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("B")).Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMethod()
{
await TestAsync(
@"class Foo
{
void DoSomething();
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("DS")).Single();
VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething()", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindParameterizedMethod()
{
await TestAsync(
@"class Foo
{
void DoSomething(int a, string b)
{
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("DS")).Single();
VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething(int, string)", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindConstructor()
{
await TestAsync(
@"class Foo
{
public Foo()
{
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method);
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo()", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindParameterizedConstructor()
{
await TestAsync(
@"class Foo
{
public Foo(int i)
{
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method);
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo(int)", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindStaticConstructor()
{
await TestAsync(
@"class Foo
{
static Foo()
{
}
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "static Foo()", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethods()
{
await TestAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }", async w =>
{
var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = await _aggregator.GetItemsAsync("Bar");
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethodDefinitionOnly()
{
await TestAsync(
@"partial class Foo
{
partial void Bar();
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("Bar")).Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindOverriddenMembers()
{
var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }";
await TestAsync(program, async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = await _aggregator.GetItemsAsync("Name");
VerifyNavigateToResultItems(expecteditems, items);
var item = items.ElementAt(0);
var itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
var unused = itemDisplay.Glyph;
Assert.Equal("Name", itemDisplay.Name);
Assert.Equal($"{FeaturesResources.type_space}DogBed", itemDisplay.AdditionalInformation);
_glyphServiceMock.Verify();
item = items.ElementAt(1);
itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
unused = itemDisplay.Glyph;
Assert.Equal("Name", itemDisplay.Name);
Assert.Equal($"{FeaturesResources.type_space}Foo", itemDisplay.AdditionalInformation);
_glyphServiceMock.Verify();
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindInterface()
{
await TestAsync(
@"public interface IFoo
{
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic);
var item = (await _aggregator.GetItemsAsync("IF")).Single();
VerifyNavigateToResultItem(item, "IFoo", MatchKind.Prefix, NavigateToItemKind.Interface, displayName: "IFoo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindDelegateInNamespace()
{
await TestAsync(
@"namespace Foo
{
delegate void DoStuff();
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend);
var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "DoStuff", MatchKind.Exact, NavigateToItemKind.Delegate, displayName: "DoStuff");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindLambdaExpression()
{
await TestAsync(
@"using System;
class Foo
{
Func<int, int> sqr = x => x * x;
}", async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("sqr")).Single();
VerifyNavigateToResultItem(item, "sqr", MatchKind.Exact, NavigateToItemKind.Field, "sqr", $"{FeaturesResources.type_space}Foo");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task OrderingOfConstructorsAndTypes()
{
await TestAsync(
@"class C1
{
C1(int i)
{
}
}
class C2
{
C2(float f)
{
}
static C2()
{
}
}", async w =>
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null),
new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null),
new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null),
new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor
new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null),
};
var items = (await _aggregator.GetItemsAsync("C")).ToList();
items.Sort(CompareNavigateToItems);
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task StartStopSanity()
{
// Verify that multiple calls to start/stop and dispose don't blow up
await TestAsync(
@"public class Foo
{
}", async w =>
{
// Do one set of queries
Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method"));
_provider.StopSearch();
// Do the same query again, make sure nothing was left over
Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method"));
_provider.StopSearch();
// Dispose the provider
_provider.Dispose();
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DescriptionItems()
{
var code = "public\r\nclass\r\nFoo\r\n{ }";
await TestAsync(code, async w =>
{
var item = (await _aggregator.GetItemsAsync("F")).Single(x => x.Kind != "Method");
var itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
var descriptionItems = itemDisplay.DescriptionItems;
Action<string, string> assertDescription = (label, value) =>
{
var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label);
Assert.Equal(value, descriptionItem.Details.Single().Text);
};
assertDescription("File:", w.Documents.Single().Name);
assertDescription("Line:", "3"); // one based line number
assertDescription("Project:", "Test");
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest1()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 };
var items = await _aggregator.GetItemsAsync("GK");
Assert.Equal(expecteditems.Count(), items.Count());
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest2()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = await _aggregator.GetItemsAsync("GKW");
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest3()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = await _aggregator.GetItemsAsync("K W");
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest4()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
var items = await _aggregator.GetItemsAsync("WKG");
Assert.Empty(items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest5()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = (await _aggregator.GetItemsAsync("G_K_W")).Single();
VerifyNavigateToResultItem(item, "get_key_word", MatchKind.Regular, NavigateToItemKind.Field);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest7()
{
////Diff from dev10
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = await _aggregator.GetItemsAsync("K*W");
VerifyNavigateToResultItems(expecteditems, items);
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest8()
{
////Diff from dev10
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
await TestAsync(source, async w =>
{
var items = await _aggregator.GetItemsAsync("GTW");
Assert.Empty(items);
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Test
{
public class UnionTests
{
private const int DuplicateFactor = 8;
public static IEnumerable<object[]> UnionUnorderedData(object[] leftCounts, object[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => l, rightCounts.Cast<int>()))
{
yield return parms.Take(4).ToArray();
}
}
// Union returns only the ordered portion ordered. See Issue #1331
public static IEnumerable<object[]> UnionData(object[] leftCounts, object[] rightCounts)
{
foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
public static IEnumerable<object[]> UnionFirstOrderedData(object[] leftCounts, object[] rightCounts)
{
foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
}
}
public static IEnumerable<object[]> UnionSecondOrderedData(object[] leftCounts, object[] rightCounts)
{
foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts))
{
yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
public static IEnumerable<object[]> UnionSourceMultipleData(object[] counts)
{
foreach (int leftCount in counts.Cast<int>())
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel();
foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) })
{
int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2;
ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel();
yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 };
}
}
}
//
// Union
//
[Theory]
[MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
foreach (int i in leftQuery.Union(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Unordered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(leftCount + rightCount, seen);
}
[Theory]
[OuterLoop]
[MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount);
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery))
{
if (i < leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
foreach (int i in leftQuery.Union(rightQuery))
{
if (i >= leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount + rightCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Unordered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(leftCount + rightCount, seen);
}
[Theory]
[OuterLoop]
[MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount);
int seen = 0;
Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
{
if (x < leftCount) Assert.Equal(seen++, x);
else seenUnordered.Add(x);
});
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
{
if (x >= leftCount) Assert.Equal(seen++, x);
else seenUnordered.Add(x);
});
Assert.Equal(leftCount + rightCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int offset = leftCount;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount);
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - offset) % DuplicateFactor + leftCount - Math.Min(leftCount, rightCount) / 2)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Unordered_Distinct(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int offset = leftCount;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
int seen = 0;
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - offset) % DuplicateFactor + leftCount - Math.Min(leftCount, rightCount) / 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(expectedCount, seen);
}
[Theory]
[OuterLoop]
[MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Distinct(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_FirstOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int offset = leftCount;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, expectedCount - leftCount);
int seen = 0;
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - offset) % DuplicateFactor + leftCount - Math.Min(leftCount, rightCount) / 2)))
{
if (i < leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_FirstOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered_Distinct(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_SecondOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int offset = leftCount;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - offset) % DuplicateFactor + leftCount - Math.Min(leftCount, rightCount) / 2)))
{
if (i >= leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(expectedCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_SecondOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered_Distinct(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int offset = leftCount;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount);
Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - offset) % DuplicateFactor + leftCount - Math.Min(leftCount, rightCount) / 2)).ToList(),
x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int offset = leftCount;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
int seen = 0;
Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - offset) % DuplicateFactor + leftCount - Math.Min(leftCount, rightCount) / 2)).ToList(),
x => Assert.Equal(seen++, x));
Assert.Equal(expectedCount, seen);
}
[Theory]
[OuterLoop]
[MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Distinct_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))]
public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
int seen = 0;
Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))]
public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Union_FirstOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, count - leftCount);
int seen = 0;
foreach (int i in leftQuery.AsOrdered().Union(rightQuery))
{
if (i < leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))]
public static void Union_FirstOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_FirstOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Union_SecondOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
foreach (int i in leftQuery.Union(rightQuery.AsOrdered()))
{
if (i >= leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(count, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))]
public static void Union_SecondOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_SecondOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_Unordered_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(DuplicateFactor, leftCount + rightCount));
foreach (int i in leftQuery.Union(rightQuery, new ModularCongruenceComparer(DuplicateFactor)))
{
Assert.InRange(i, 0, leftCount + rightCount - 1);
seen.Add(i % DuplicateFactor);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Unordered_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Union_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery, new ModularCongruenceComparer(DuplicateFactor)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(DuplicateFactor, leftCount + rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })]
public static void Union_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_CustomComparator(left, leftCount, right, rightCount);
}
[Fact]
public static void Union_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
public static void Union_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1)));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default));
}
}
}
| |
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 MIMDashboard.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;
}
}
}
| |
/*
* 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.Reflection;
using System.Threading;
namespace Apache.Geode.DUnitFramework
{
/// <summary>
/// Delegate to be invoked on the client side. This one is for
/// a parameterless function that doesn't return any value.
/// </summary>
public delegate void UnitFnMethod();
public delegate void UnitFnMethod<T1>(T1 param1);
public delegate void UnitFnMethod<T1, T2>(T1 param1,
T2 param2);
public delegate void UnitFnMethod<T1, T2, T3>(T1 param1,
T2 param2, T3 param3);
public delegate void UnitFnMethod<T1, T2, T3, T4>(T1 param1,
T2 param2, T3 param3, T4 param4);
public delegate void UnitFnMethod<T1, T2, T3, T4, T5>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5);
public delegate void UnitFnMethod<T1, T2, T3, T4, T5, T6>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6);
public delegate void UnitFnMethod<T1, T2, T3, T4, T5, T6, T7>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7);
/*
public delegate void UnitFnMethodGeneric<TKey, TVal, T1, T2, T3, T4, T5, T6, T7>(T1<TKey, TVal> param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7);
* */
public delegate void UnitFnMethod<T1, T2, T3, T4, T5, T6, T7, T8>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8);
public delegate void UnitFnMethod<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9);
/// <summary>
/// Delegate to be invoked on the client side. This one is for a function
/// with arbitrary number of parameters that returns an object.
/// </summary>
/// <param name="data">Any data that needs to be passed to the function.</param>
/// <returns>The result of the function as an 'object'.</returns>
public delegate T0 UnitFnMethodR<T0>();
public delegate T0 UnitFnMethodR<T0, T1>(T1 param1);
public delegate T0 UnitFnMethodR<T0, T1, T2>(T1 param1,
T2 param2);
public delegate T0 UnitFnMethodR<T0, T1, T2, T3>(T1 param1,
T2 param2, T3 param3);
public delegate T0 UnitFnMethodR<T0, T1, T2, T3, T4>(T1 param1,
T2 param2, T3 param3, T4 param4);
public delegate T0 UnitFnMethodR<T0, T1, T2, T3, T4, T5>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5);
public delegate T0 UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6);
public delegate T0 UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6, T7>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7);
/*
public delegate T0 UnitFnMethodRUnitFnMethodGeneric<TKey, TVal, T0, T1, T2, T3, T4, T5, T6, T7>(T1<TKey, TVal> param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7);
* */
public delegate T0 UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6, T7, T8>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8);
public delegate T0 UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 param1,
T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9);
/// <summary>
/// An abstract class to encapsulate calling a function on a client
/// thread/process/... Example implementations would be a 'Thread'
/// or a process on a remote host.
///
/// Implementations are expected to catch the NUnit.Framework.AssertionException
/// exception thrown by the client thread/process/... and throw them in the
/// calling thread (i.e. in the function calls).
/// </summary>
public abstract class ClientBase : IDisposable
{
#region Private members
private string m_id;
private int m_numTasksRunning;
#endregion
#region Public accessors
public virtual string ID
{
get
{
return m_id;
}
set
{
m_id = value;
}
}
public bool TaskRunning
{
get
{
return (m_numTasksRunning > 0);
}
}
public virtual string StartDir
{
get
{
return null;
}
}
#endregion
#region Call functions with no result
/// <summary>
/// Call a 'UnitFunction' on this thread/process/... blocking till
/// the function completes.
/// </summary>
/// <param name="deleg">The function to run on this thread/process/...</param>
/// <exception cref="ClientExitedException">
/// If the client has exited due to some exception or if the object has been destroyed.
/// </exception>
public void Call(UnitFnMethod deleg)
{
CallFn(deleg, null);
}
public void Call<T1>(UnitFnMethod<T1> deleg, T1 param1)
{
CallFn(deleg, new object[] { param1 });
}
public void Call<T1, T2>(UnitFnMethod<T1, T2> deleg,
T1 param1, T2 param2)
{
CallFn(deleg, new object[] { param1, param2 });
}
public void Call<T1, T2, T3>(UnitFnMethod<T1, T2, T3> deleg,
T1 param1, T2 param2, T3 param3)
{
CallFn(deleg, new object[] { param1, param2, param3 });
}
public void Call<T1, T2, T3, T4>(UnitFnMethod<T1, T2, T3, T4> deleg,
T1 param1, T2 param2, T3 param3, T4 param4)
{
CallFn(deleg, new object[] { param1, param2, param3, param4 });
}
public void Call<T1, T2, T3, T4, T5>(UnitFnMethod<T1, T2, T3, T4, T5> deleg,
T1 param1, T2 param2, T3 param3, T4 param4, T5 param5)
{
CallFn(deleg, new object[] { param1, param2, param3, param4, param5 });
}
public void Call<T1, T2, T3, T4, T5, T6>(UnitFnMethod<T1, T2, T3, T4, T5, T6> deleg,
T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6)
{
CallFn(deleg, new object[] { param1, param2, param3, param4, param5, param6 });
}
public void Call<T1, T2, T3, T4, T5, T6, T7>(UnitFnMethod<T1, T2, T3, T4, T5, T6, T7> deleg,
T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7)
{
CallFn(deleg, new object[] { param1, param2, param3, param4, param5, param6, param7 });
}
public void Call<T1, T2, T3, T4, T5, T6, T7, T8>(UnitFnMethod<T1, T2, T3, T4, T5, T6, T7, T8> deleg,
T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8)
{
CallFn(deleg, new object[] { param1, param2, param3, param4, param5, param6, param7, param8 });
}
public void Call<T1, T2, T3, T4, T5, T6, T7, T8, T9>(UnitFnMethod<T1, T2, T3, T4, T5, T6, T7, T8, T9> deleg,
T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9)
{
CallFn(deleg, new object[] { param1, param2, param3, param4, param5, param6, param7, param8, param9 });
}
#endregion
#region Call functions that return a result
public void Call<T0>(UnitFnMethodR<T0> deleg,
out T0 outparam)
{
outparam = (T0)CallFnR(deleg, null);
}
public void Call<T0, T1>(UnitFnMethodR<T0, T1> deleg,
out T0 outparam, T1 param1)
{
outparam = (T0)CallFnR(deleg, new object[] { param1 });
}
public void Call<T0, T1, T2>(UnitFnMethodR<T0, T1, T2> deleg,
out T0 outparam, T1 param1, T2 param2)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2 });
}
public void Call<T0, T1, T2, T3>(UnitFnMethodR<T0, T1, T2, T3> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3 });
}
public void Call<T0, T1, T2, T3, T4>(UnitFnMethodR<T0, T1, T2, T3, T4> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3, T4 param4)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3, param4 });
}
public void Call<T0, T1, T2, T3, T4, T5>(UnitFnMethodR<T0, T1, T2, T3, T4, T5> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3, param4, param5 });
}
public void Call<T0, T1, T2, T3, T4, T5, T6>(UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3, param4, param5, param6 });
}
public void Call<T0, T1, T2, T3, T4, T5, T6, T7>(UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6, T7> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3, param4, param5, param6, param7 });
}
public void Call<T0, T1, T2, T3, T4, T5, T6, T7, T8>(UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6, T7, T8> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3, param4, param5, param6, param7, param8 });
}
public void Call<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(UnitFnMethodR<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> deleg,
out T0 outparam, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9)
{
outparam = (T0)CallFnR(deleg, new object[] { param1, param2, param3, param4, param5, param6, param7, param8, param9 });
}
#endregion
public void RemoveObject(object obj)
{
if (obj != null)
{
RemoveObjectID(obj.GetHashCode());
}
}
public void RemoveType(Type tp)
{
if (tp != null)
{
RemoveObjectID(tp.GetHashCode());
}
}
public virtual void IncrementTasksRunning()
{
Interlocked.Increment(ref m_numTasksRunning);
}
public virtual void DecrementTasksRunning()
{
Interlocked.Decrement(ref m_numTasksRunning);
}
public static void GetDelegateInfo(Delegate deleg, out string assemblyName,
out string typeName, out string methodName, out int objectId)
{
MethodInfo mInfo = deleg.Method;
object target = deleg.Target;
Type delegType;
if (target != null)
{
// Do not use ReflectedType, otherwise it returns base class type
// for a derived class object when the derived class does not
// override the method.
delegType = target.GetType();
objectId = target.GetHashCode();
}
else
{
// This case would be for static methods.
delegType = mInfo.ReflectedType;
objectId = delegType.GetHashCode();
}
assemblyName = delegType.Assembly.FullName;
typeName = delegType.FullName;
methodName = mInfo.Name;
}
public abstract void RemoveObjectID(int objectID);
public abstract void CallFn(Delegate deleg, object[] paramList);
public abstract object CallFnR(Delegate deleg, object[] paramList);
public abstract string HostName
{
get;
}
/// <summary>
/// Set the path of the log file.
/// </summary>
/// <param name="logPath">The path of the log file.</param>
public abstract void SetLogFile(string logPath);
/// <summary>
/// Set logging level for the client.
/// </summary>
/// <param name="logLevel">The logging level to set.</param>
public abstract void SetLogLevel(Util.LogLevel logLevel);
/// <summary>
/// Dump the stack trace of the client in the file set using the
/// <see cref="SetLogFile"/> functions (or to console if not set).
/// </summary>
public abstract void DumpStackTrace();
/// <summary>
/// Kill the client after waiting for it to exit cleanly for the given
/// milliseconds. This function should also dispose the object so that
/// no other functions can be invoked on it.
/// </summary>
/// <param name="waitMillis">
/// The number of milliseconds to wait before forcibly killing the client.
/// A value of less than or equal to 0 means immediately killing.
/// </param>
public abstract void ForceKill(int waitMillis);
/// <summary>
/// Create a new client from the current instance.
/// </summary>
/// <param name="clientId">The ID of the new client.</param>
/// <returns>An instance of a new client.</returns>
public abstract ClientBase CreateNew(string clientId);
/// <summary>
/// Any actions required to be done to cleanup at the end of each test.
/// </summary>
public abstract void TestCleanup();
/// <summary>
/// Exit the client cleanly. This should normally wait for the current
/// call to complete, perform any additional cleanup tasks registered and
/// then close the client. To immediately kill the client use <see cref="ForceKill"/>.
/// </summary>
public abstract void Exit();
~ClientBase()
{
Exit();
}
#region IDisposable Members
public void Dispose()
{
Exit();
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Ecosim;
using Ecosim.SceneData;
using Ecosim.GameCtrl.GameButtons;
using System;
using System.IO;
using Ecosim.SceneEditor;
public class ReportWindow : ReportBaseWindow
{
private Scene scene;
private Report report;
private Progression.ReportState state;
private List<Progression.ReportState.ParagraphState> paragraphStates;
private List<Progression.QuestionnaireState.QuestionState> copyToReportQuestions;
private Vector2 scrollPos;
public ReportWindow (Report report, System.Action onFinished, Texture2D icon) : base (onFinished, icon)
{
this.scene = EditorCtrl.self.scene;
this.report = report;
this.state = scene.progression.GetReportState (this.report.id);
this.state.name = scene.playerInfo.firstName + " " + scene.playerInfo.familyName;
// Paragraph states
this.paragraphStates = new List<Progression.ReportState.ParagraphState>();
for (int i = 0; i < this.report.paragraphs.Count; i++) {
Progression.ReportState.ParagraphState ps = new Progression.ReportState.ParagraphState ();
this.state.paragraphStates.Add (ps);
this.paragraphStates.Add (ps);
}
// Find all "copy to reports"
this.copyToReportQuestions = new List<Progression.QuestionnaireState.QuestionState>();
foreach (Questionnaire qn in ReportsMgr.self.questionnaires)
{
if (!qn.enabled) continue;
for (int n = 0; n < qn.questions.Count; n++)
{
Question q = qn.questions [n];
if (!(q is OpenQuestion)) continue;
OpenQuestion oq = (OpenQuestion)q;
for (int i = 0; i < oq.answers.Count; i++)
{
if (oq.answers [i] is OpenQuestion.OpenAnswer)
{
OpenQuestion.OpenAnswer oa = (OpenQuestion.OpenAnswer)oq.answers [i];
if (oa.copyToReport && oa.reportIndices.Contains (this.report.id))
{
// Find the question state(s)
Progression.QuestionnaireState[] qStates = EditorCtrl.self.scene.progression.GetQuestionnaireStates (qn.id);
if (qStates.Length > 0) {
foreach (Progression.QuestionnaireState qs in qStates) {
this.copyToReportQuestions.Add (qs.GetQuestionState (n));
}
}
}
}
}
}
}
this.height = Screen.height * 0.85f;
this.yOffset = (int)((Screen.height - height) * 0.5f);
}
protected override void UpdateWidthAndHeight ()
{
base.UpdateWidthAndHeight ();
height = Screen.height * 0.85f;
}
public override void Render ()
{
base.Render ();
Rect areaRect = new Rect (left + 32, top, width - 32, height);
GUILayout.BeginArea (areaRect);
//{
CameraControl.MouseOverGUI |= areaRect.Contains (Input.mousePosition);
// Header
GUILayout.Label ("Report: " + this.report.name, headerDark, GUILayout.Width (width), defaultOption);
GUILayout.Space (5);
scrollPos = GUILayout.BeginScrollView (scrollPos);
// Name/number
if (this.report.useName)
{
//GUILayout.BeginHorizontal ();
//{
GUILayout.Label ("Name:", headerDark, GUILayout.Width (width), defaultOption);
this.state.name = GUILayout.TextField (this.state.name, textArea, GUILayout.Width (width), defaultOption);
//}
//GUILayout.EndHorizontal ();
}
if (this.report.useNumber)
{
//GUILayout.BeginHorizontal ();
//{
GUILayout.Label ("Number:", headerDark, GUILayout.Width (width), defaultOption);
this.state.number = GUILayout.TextField (this.state.number, textArea, GUILayout.Width (width), defaultOption);
//}
//GUILayout.EndHorizontal ();
}
if (this.report.useName || this.report.useNumber) {
GUILayout.Space (5);
}
// Introduction
if (this.report.useIntroduction)
{
GUILayout.Label ("Introduction:", headerDark, GUILayout.Width (width), defaultOption);
GUILayout.Label (this.report.introduction, headerLight, GUILayout.Width (width), defaultOption);
GUILayout.Space (5);
}
// Copy to reports
foreach (Progression.QuestionnaireState.QuestionState qs in this.copyToReportQuestions)
{
// Name
GUILayout.Label ("\"" + qs.questionName + "\"", headerDark, GUILayout.Width (width), defaultOption);
GUILayout.Label ("\"" + qs.questionAnswer + "\"", textArea, GUILayout.Width (width), defaultOption);
GUILayout.Space (5);
}
// Paragraphs
Progression.ReportState.ParagraphState ps;
ReportParagraph rp;
for (int i = 0; i < this.report.paragraphs.Count; i++)
{
ps = this.paragraphStates [i];
rp = this.report.paragraphs [i];
// Header
//GUILayout.BeginHorizontal ();
//{
//GUILayout.Label ((i+1).ToString(), headerDark, GUILayout.Width (30), defaultOption);
if (rp.useTitle) GUILayout.Label ((i+1).ToString() + " " + rp.title, headerDark, GUILayout.Width (width), defaultOption);
//}
//GUILayout.EndHorizontal ();
// Description
if (rp.useDescription) {
GUILayout.Label (rp.description, headerDark, GUILayout.Width (width), defaultOption);
}
// Body
if (rp.useMaxChars)
{
ps.body = GUILayout.TextArea (ps.body, rp.maxChars, textArea, GUILayout.Width (width), defaultOption);
GUILayout.Label (string.Format("<size=10>Characters {0}/{1}</size>", ps.body.Length, rp.maxChars), headerLight , GUILayout.Width (width), GUILayout.Height (30), defaultOption);
} else
{
ps.body = GUILayout.TextArea (ps.body, textArea, GUILayout.Width (width), defaultOption);
}
GUILayout.Space (5);
}
// Conclusion
if (this.report.useConclusion)
{
GUILayout.Label ("Final Remark:", headerDark, GUILayout.Width (width), defaultOption);
GUILayout.Label (this.report.conclusion, headerLight, GUILayout.Width (width), defaultOption);
GUILayout.Space (5);
}
GUILayout.BeginHorizontal ();
{
int saveWidth = (SaveFileDialog.SystemDialogAvailable ()) ? 80 : 135;
GUILayout.Label ("", headerLight, GUILayout.Width (width - 2 - (saveWidth + 80)), defaultOption);
// Save
GUILayout.Space (1);
string saveName = (SaveFileDialog.SystemDialogAvailable ()) ? "Save" : "Save to Desktop";
if (GUILayout.Button (saveName, button, GUILayout.Width (saveWidth), defaultOption))
{
DoSave ();
}
// Continue
GUILayout.Space (1);
if (GUILayout.Button ("Continue", button, GUILayout.Width (80), defaultOption))
{
if (onFinished != null)
onFinished ();
}
}
GUILayout.EndHorizontal ();
//}
GUILayout.EndScrollView ();
GUILayout.EndArea ();
}
private void DoSave ()
{
MonoBehaviour mb = instance;
if (mb == null) mb = GameControl.self;
mb.StartCoroutine (SaveFileDialog.Show (string.Format ("report_{0}", this.report.id), "txt files (*.txt)|*.txt", delegate(bool ok, string url)
{
if (!ok) return;
// Create new file
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding ();
FileStream fs = File.Create (url);
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
if (this.report.useName) sb.AppendFormat ("Name: {0}\n", this.state.name);
if (this.report.useNumber) sb.AppendFormat ("Number: {0}\n", this.state.number);
sb.AppendFormat ("Date: {0}\n", System.DateTime.Today.ToString ("dd\\/MM\\/yyyy"));
sb.AppendLine ();
sb.AppendFormat ("Report {0}:\n", this.report.id);
sb.AppendFormat ("{0}\n", this.report.name);
sb.AppendLine ();
if (this.report.useIntroduction)
{
sb.AppendFormat ("Introduction:\n");
sb.AppendFormat ("{0}\n", this.report.introduction);
sb.AppendLine ();
}
foreach (Progression.QuestionnaireState.QuestionState qs in this.copyToReportQuestions)
{
sb.AppendFormat ("\"{0}\"\n", qs.questionName);
sb.AppendFormat ("\"{0}\"\n", qs.questionAnswer);
sb.AppendLine ();
}
Progression.ReportState.ParagraphState ps;
ReportParagraph rp;
for (int i = 0; i < this.report.paragraphs.Count; i++)
{
ps = this.paragraphStates [i];
rp = this.report.paragraphs [i];
if (rp.useTitle) {
sb.AppendFormat ("{0}\n", rp.title);
}
if (rp.useDescription) {
sb.AppendFormat ("{0}\n", rp.description);
sb.AppendLine ();
}
sb.AppendFormat ("{0}\n", ps.body);
sb.AppendLine ();
}
if (this.report.useConclusion)
{
sb.AppendFormat ("Final Remark:\n");
sb.AppendFormat ("{0}\n", this.report.conclusion);
sb.AppendLine ();
}
// Stringify and save
string txt = sb.ToString ();
fs.Write (enc.GetBytes (txt), 0, enc.GetByteCount (txt));
// Close and dispose the stream
fs.Close ();
fs.Dispose ();
fs = null;
}));
}
public override void Dispose ()
{
base.Dispose ();
this.report = null;
}
}
| |
using Lucene.Net.Codecs.Lucene41;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Codecs.Asserting
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Just like <see cref="Lucene41PostingsFormat"/> but with additional asserts.
/// </summary>
[PostingsFormatName("Asserting")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name
public sealed class AssertingPostingsFormat : PostingsFormat
{
private readonly PostingsFormat @in = new Lucene41PostingsFormat();
public AssertingPostingsFormat()
: base()
{
}
public override FieldsConsumer FieldsConsumer(SegmentWriteState state)
{
return new AssertingFieldsConsumer(@in.FieldsConsumer(state));
}
public override FieldsProducer FieldsProducer(SegmentReadState state)
{
return new AssertingFieldsProducer(@in.FieldsProducer(state));
}
internal class AssertingFieldsProducer : FieldsProducer
{
private readonly FieldsProducer @in;
internal AssertingFieldsProducer(FieldsProducer @in)
{
this.@in = @in;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
@in.Dispose();
}
}
public override IEnumerator<string> GetEnumerator()
{
IEnumerator<string> iterator = @in.GetEnumerator();
if (Debugging.AssertsEnabled) Debugging.Assert(iterator != null);
return iterator;
}
public override Terms GetTerms(string field)
{
Terms terms = @in.GetTerms(field);
return terms == null ? null : new AssertingTerms(terms);
}
public override int Count => @in.Count;
[Obsolete("iterate fields and add their Count instead.")]
public override long UniqueTermCount => @in.UniqueTermCount;
public override long RamBytesUsed()
{
return @in.RamBytesUsed();
}
public override void CheckIntegrity()
{
@in.CheckIntegrity();
}
}
internal class AssertingFieldsConsumer : FieldsConsumer
{
private readonly FieldsConsumer @in;
internal AssertingFieldsConsumer(FieldsConsumer @in)
{
this.@in = @in;
}
public override TermsConsumer AddField(FieldInfo field)
{
TermsConsumer consumer = @in.AddField(field);
if (Debugging.AssertsEnabled) Debugging.Assert(consumer != null);
return new AssertingTermsConsumer(consumer, field);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
@in.Dispose();
}
}
}
internal enum TermsConsumerState
{
INITIAL,
START,
FINISHED
}
internal class AssertingTermsConsumer : TermsConsumer
{
private readonly TermsConsumer @in;
private readonly FieldInfo fieldInfo;
private BytesRef lastTerm = null;
private TermsConsumerState state = TermsConsumerState.INITIAL;
private AssertingPostingsConsumer lastPostingsConsumer = null;
private long sumTotalTermFreq = 0;
private long sumDocFreq = 0;
private OpenBitSet visitedDocs = new OpenBitSet();
internal AssertingTermsConsumer(TermsConsumer @in, FieldInfo fieldInfo)
{
this.@in = @in;
this.fieldInfo = fieldInfo;
}
public override PostingsConsumer StartTerm(BytesRef text)
{
if (Debugging.AssertsEnabled) Debugging.Assert(state == TermsConsumerState.INITIAL || state == TermsConsumerState.START && lastPostingsConsumer.docFreq == 0);
state = TermsConsumerState.START;
if (Debugging.AssertsEnabled) Debugging.Assert(lastTerm == null || @in.Comparer.Compare(text, lastTerm) > 0);
lastTerm = BytesRef.DeepCopyOf(text);
return lastPostingsConsumer = new AssertingPostingsConsumer(@in.StartTerm(text), fieldInfo, visitedDocs);
}
public override void FinishTerm(BytesRef text, TermStats stats)
{
if (Debugging.AssertsEnabled) Debugging.Assert(state == TermsConsumerState.START);
state = TermsConsumerState.INITIAL;
if (Debugging.AssertsEnabled) Debugging.Assert(text.Equals(lastTerm));
if (Debugging.AssertsEnabled) Debugging.Assert(stats.DocFreq > 0); // otherwise, this method should not be called.
if (Debugging.AssertsEnabled) Debugging.Assert(stats.DocFreq == lastPostingsConsumer.docFreq);
sumDocFreq += stats.DocFreq;
if (fieldInfo.IndexOptions == IndexOptions.DOCS_ONLY)
{
if (Debugging.AssertsEnabled) Debugging.Assert(stats.TotalTermFreq == -1);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(stats.TotalTermFreq == lastPostingsConsumer.totalTermFreq);
sumTotalTermFreq += stats.TotalTermFreq;
}
@in.FinishTerm(text, stats);
}
public override void Finish(long sumTotalTermFreq, long sumDocFreq, int docCount)
{
if (Debugging.AssertsEnabled) Debugging.Assert(state == TermsConsumerState.INITIAL || state == TermsConsumerState.START && lastPostingsConsumer.docFreq == 0);
state = TermsConsumerState.FINISHED;
if (Debugging.AssertsEnabled) Debugging.Assert(docCount >= 0);
if (Debugging.AssertsEnabled) Debugging.Assert(docCount == visitedDocs.Cardinality());
if (Debugging.AssertsEnabled) Debugging.Assert(sumDocFreq >= docCount);
if (Debugging.AssertsEnabled) Debugging.Assert(sumDocFreq == this.sumDocFreq);
if (fieldInfo.IndexOptions == IndexOptions.DOCS_ONLY)
{
if (Debugging.AssertsEnabled) Debugging.Assert(sumTotalTermFreq == -1);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(sumTotalTermFreq >= sumDocFreq);
if (Debugging.AssertsEnabled) Debugging.Assert(sumTotalTermFreq == this.sumTotalTermFreq);
}
@in.Finish(sumTotalTermFreq, sumDocFreq, docCount);
}
public override IComparer<BytesRef> Comparer => @in.Comparer;
}
internal enum PostingsConsumerState
{
INITIAL,
START
}
internal class AssertingPostingsConsumer : PostingsConsumer
{
private readonly PostingsConsumer @in;
private readonly FieldInfo fieldInfo;
private readonly OpenBitSet visitedDocs;
private PostingsConsumerState state = PostingsConsumerState.INITIAL;
private int freq;
private int positionCount;
private int lastPosition = 0;
private int lastStartOffset = 0;
internal int docFreq = 0;
internal long totalTermFreq = 0;
internal AssertingPostingsConsumer(PostingsConsumer @in, FieldInfo fieldInfo, OpenBitSet visitedDocs)
{
this.@in = @in;
this.fieldInfo = fieldInfo;
this.visitedDocs = visitedDocs;
}
public override void StartDoc(int docID, int freq)
{
if (Debugging.AssertsEnabled) Debugging.Assert(state == PostingsConsumerState.INITIAL);
state = PostingsConsumerState.START;
if (Debugging.AssertsEnabled) Debugging.Assert(docID >= 0);
if (fieldInfo.IndexOptions == IndexOptions.DOCS_ONLY)
{
if (Debugging.AssertsEnabled) Debugging.Assert(freq == -1);
this.freq = 0; // we don't expect any positions here
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(freq > 0);
this.freq = freq;
totalTermFreq += freq;
}
this.positionCount = 0;
this.lastPosition = 0;
this.lastStartOffset = 0;
docFreq++;
visitedDocs.Set(docID);
@in.StartDoc(docID, freq);
}
public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset)
{
if (Debugging.AssertsEnabled) Debugging.Assert(state == PostingsConsumerState.START);
if (Debugging.AssertsEnabled) Debugging.Assert(positionCount < freq);
positionCount++;
if (Debugging.AssertsEnabled) Debugging.Assert(position >= lastPosition || position == -1); // we still allow -1 from old 3.x indexes
lastPosition = position;
if (fieldInfo.IndexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS)
{
if (Debugging.AssertsEnabled) Debugging.Assert(startOffset >= 0);
if (Debugging.AssertsEnabled) Debugging.Assert(startOffset >= lastStartOffset);
lastStartOffset = startOffset;
if (Debugging.AssertsEnabled) Debugging.Assert(endOffset >= startOffset);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(startOffset == -1);
if (Debugging.AssertsEnabled) Debugging.Assert(endOffset == -1);
}
if (payload != null)
{
if (Debugging.AssertsEnabled) Debugging.Assert(fieldInfo.HasPayloads);
}
@in.AddPosition(position, payload, startOffset, endOffset);
}
public override void FinishDoc()
{
if (Debugging.AssertsEnabled) Debugging.Assert(state == PostingsConsumerState.START);
state = PostingsConsumerState.INITIAL;
if (fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0)
{
if (Debugging.AssertsEnabled) Debugging.Assert(positionCount == 0); // we should not have fed any positions!
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(positionCount == freq);
}
@in.FinishDoc();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
using Zencoder.Converters;
using Zencoder.Notification;
using Zencoder.ThirdPartyStorages.S3;
namespace Zencoder.IO.Outputs
{
/// <summary>
/// Represents job output settings.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Output
{
[JsonProperty("headers", NullValueHandling = NullValueHandling.Ignore)]
private IDictionary<string, string> headers;
/// <summary>
/// Gets or sets the collection of custom S3 access grants to apply to the output
/// if its destination is S3.
/// </summary>
[JsonProperty("access_control", NullValueHandling = NullValueHandling.Ignore)]
public S3Access[] AccessControl { get; set; }
/// <summary>
/// Gets or sets the aspect mode to use if the input aspect ratio does not
/// match the input aspect ratio.
/// </summary>
[JsonProperty("aspect_mode", NullValueHandling = NullValueHandling.Ignore)]
public AspectMode? AspectMode { get; set; }
/// <summary>
/// Gets or sets the audio bitrate to use in Kbps. Should be a multiple of 16,
/// and lower than 160Kbps per channel (i.e., 320Kbps stereo).
/// Identifies that total bitrate, not per channel.
/// </summary>
[JsonProperty("audio_bitrate", NullValueHandling = NullValueHandling.Ignore)]
public int? AudioBitrate { get; set; }
/// <summary>
/// Gets or sets the number of audio channels to use (1 or 2). Defaults to keep the number of
/// input channels, or reduce to 2.
/// </summary>
[JsonProperty("audio_channels", NullValueHandling = NullValueHandling.Ignore)]
public int? AudioChannels { get; set; }
/// <summary>
/// Gets or sets the audio codec to use. If encoding video and not set,
/// the output video codec will determine this value automatically unless specifically set.
/// </summary>
[JsonProperty("audio_codec", NullValueHandling = NullValueHandling.Ignore)]
public AudioCodec? AudioCodec { get; set; }
/// <summary>
/// Normalize the audio before applying expansion or compression effects.
/// </summary>
[JsonProperty("audio_pre_normalize", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? AudioPreNormalize { get; set; }
/// <summary>
/// Normalize the audio after applying expansion or compression effects.
/// </summary>
[JsonProperty("audio_post_normalize", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? AudioPostNormalize { get; set; }
/// <summary>
/// Gets or sets a target audio quality, from 1 to 5. 5 is the best
/// quality, but results in the largest files.
/// </summary>
[JsonProperty("audio_quality", NullValueHandling = NullValueHandling.Ignore)]
public int? AudioQuality { get; set; }
/// <summary>
/// Gets or sets the audio sample rate in Hz. Not recommended.
/// By default, the input sample rate will be used. Rates higher than 48,000 Hz
/// will be resampled to 48KHz.
/// </summary>
[JsonProperty("audio_sample_rate", NullValueHandling = NullValueHandling.Ignore)]
public int? AudioSampleRate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to apply an auto-level filter to the output video.
/// </summary>
[JsonProperty("auto_level", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? AutoLevel { get; set; }
/// <summary>
/// Gets or sets a directory to place the output file in, but not the file name.
/// If no <see cref="FileName" /> is specified, a random one will be generated with the appropriate extension.
/// </summary>
[JsonProperty("base_url", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
public string BaseUrl { get; set; }
/// <summary>
/// Gets or sets the desired peak bitrate for the output video, without
/// forcing lower bitrates to be raised.
/// </summary>
[JsonProperty("bitrate_cap", NullValueHandling = NullValueHandling.Ignore)]
public int? BitrateCap { get; set; }
/// <summary>
/// Gets or sets the buffer size. Used in conjuction with <see cref="BitrateCap" />, this should be determined by
/// your streaming server settings. For example, use 10,000 for iPhone.
/// </summary>
[JsonProperty("buffer_size", NullValueHandling = NullValueHandling.Ignore)]
public int? BufferSize { get; set; }
/// <summary>
/// Gets or sets the duration of the movie subclip to create.
/// </summary>
[JsonProperty("clip_length", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
public string ClipLength { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use constant bitrate (CBR) encoding.
/// Requires setting <see cref="VideoBitrate" />. Cannot be used in conjuction with <see cref="Quality" />.
/// </summary>
[JsonProperty("constant_bitrate", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? ConstantBitrate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to apply a deblocking filter to the output video.
/// </summary>
[JsonProperty("deblock", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Deblock { get; set; }
/// <summary>
/// Gets or sets a value that acts as a divisor for the input frame rate.
/// Given an input frame rate of 20 and a decimate value of 2, the output frame rate will be 10.
/// </summary>
[JsonProperty("decimate", NullValueHandling = NullValueHandling.Ignore)]
public int? Decimate { get; set; }
/// <summary>
/// Gets or sets the deinterlace mode to use.
/// </summary>
[JsonProperty("deinterlace", NullValueHandling = NullValueHandling.Ignore)]
public Deinterlace? Deinterlace { get; set; }
/// <summary>
/// Gets or sets the denoise filter to apply to the output video, if applicable.
/// </summary>
[JsonProperty("denoise", NullValueHandling = NullValueHandling.Ignore)]
public DenoiseFilter? Denoise { get; set; }
/// <summary>
/// Gets or sets a shortcut device profile to use for the output.
/// See https://app.zencoder.com/docs/api/encoding/general-output-settings/device-profile
/// for more details on device profiles.
/// </summary>
[JsonProperty("device_profile", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(EnumDescriptionConverter))]
public DeviceProfile? DeviceProfile { get; set; }
/// <summary>
/// Gets or sets the file name of the finished file. If supplied and <see cref="BaseUrl" />
/// is empty, Zencoder will store a file with this name in an S3 bucket for download.
/// </summary>
[JsonProperty("filename", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
public string FileName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enable or disable variability in keyframe
/// generation when using <see cref="KeyframeInterval" />. When not set, defaults to false,
/// allowing variability.
/// </summary>
[JsonProperty("fixed_keyframe_interval", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? FixedKeyframeInterval { get; set; }
/// <summary>
/// Gets or sets the format of the output container to use. Only set this value if not inferring
/// the format from the output file name.
/// </summary>
[JsonProperty("format", NullValueHandling = NullValueHandling.Ignore)]
public MediaFileFormat? Format { get; set; }
/// <summary>
/// Gets or sets the output frame rate to use. Not recommended.
/// </summary>
[JsonProperty("frame_rate", NullValueHandling = NullValueHandling.Ignore)]
public float? FrameRate { get; set; }
/// <summary>
/// Gets or sets the level to use when performing H264 encoding.
/// </summary>
[JsonProperty("h264_level", NullValueHandling = NullValueHandling.Ignore)]
public H264Level? H264Level { get; set; }
/// <summary>
/// Gets or sets the profile to use when performing H264 encoding.
/// </summary>
[JsonProperty("h264_profile", NullValueHandling = NullValueHandling.Ignore)]
public H264Profile? H264Profile { get; set; }
/// <summary>
/// Gets or sets the number of reference frames to use when performing H264 encoding.
/// </summary>
[JsonProperty("h264_reference_frames", NullValueHandling = NullValueHandling.Ignore)]
public int? H264ReferenceFrames { get; set; }
/// <summary>
/// Gets the custom header dictionary to send to Amazon S3, if applicable. Zencoder supports
/// the following subset of headers: Cache-Control, Content-Disposition, Content-Encoding,
/// Content-Type, Expires, x-amz-acl, x-amz-storage-class and x-amz-meta-*.
/// </summary>
public IDictionary<string, string> Headers => headers ?? (headers = new Dictionary<string, string>());
/// <summary>
/// Gets or sets the height of the output video, if applicable.
/// </summary>
[JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)]
public int? Height { get; set; }
/// <summary>
/// Gets or sets the maximum number of frames between each keyframe.
/// Defaults to 250.
/// </summary>
[JsonProperty("keyframe_interval", NullValueHandling = NullValueHandling.Ignore)]
public int? KeyframeInterval { get; set; }
/// <summary>
/// Gets or sets the number of keyframes per second. A value of 0.5 would result
/// in one keyframe every two seconds, a value of 3 would result in three keyframes
/// per second. Use this instead of <see cref="KeyframeInterval" /> if desired, althouth
/// <see cref="KeyframeInterval" /> takes precedence if both are set.
/// </summary>
[JsonProperty("keyframe_rate", NullValueHandling = NullValueHandling.Ignore)]
public float? KeyframeRate { get; set; }
/// <summary>
/// Gets or sets a nickname to use for the output, if applicable.
/// </summary>
[JsonProperty("label", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
public string Label { get; set; }
/// <summary>
/// Gets or sets a value indicating the maximum audio sample rate to use, rather than
/// forcing a specific sample rate. Value should be in Hz (e.g., 44100 for CD quality).
/// </summary>
[JsonProperty("max_audio_sample_rate", NullValueHandling = NullValueHandling.Ignore)]
public int? MaxAudioSampleRate { get; set; }
/// <summary>
/// Gets or sets the maximum frame rate (and therefore bitrate) to use,
/// rather than forcing a specific frame rate.
/// </summary>
[JsonProperty("max_frame_rate", NullValueHandling = NullValueHandling.Ignore)]
public float? MaxFrameRate { get; set; }
/// <summary>
/// Gets or sets the maximum average bitrate to use. Overiddes both <see cref="Quality" />
/// and <see cref="VideoBitrate" />.
/// </summary>
[JsonProperty("max_video_bitrate", NullValueHandling = NullValueHandling.Ignore)]
public int? MaxVideoBitrate { get; set; }
/// <summary>
/// Gets or sets the collection of notifications to define for the output.
/// </summary>
[JsonProperty("notifications", NullValueHandling = NullValueHandling.Ignore)]
public Notification.Notification[] Notifications { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to force onepass encoding when
/// <see cref="VideoBitrate" /> is set.
/// </summary>
[JsonProperty("onepass", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Onepass { get; set; }
/// <summary>
/// Gets or sets the output type to use.
/// </summary>
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public OutputType? OutputType { get; set; }
/// <summary>
/// Gets or sets a value indicating a shortcut S3 ACL granding READ permission to the AllUsers group,
/// if the output is being placed in S3.
/// </summary>
[JsonProperty("public", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Public { get; set; }
/// <summary>
/// Gets or sets the desired video output quality, from 1 to 5.
/// 5 is almost lossless, but results in the largest files.
/// Defaults to 3.
/// </summary>
[JsonProperty("quality", NullValueHandling = NullValueHandling.Ignore)]
public int? Quality { get; set; }
/// <summary>
/// Gets or sets the degrees by which to explicitly rotate the video.
/// Setting to non-null will prevent auto rotation.
/// </summary>
[JsonProperty("rotate", NullValueHandling = NullValueHandling.Ignore)]
public Rotate? Rotate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to pass the necessary headers to S3
/// if the destination S3 bucket is using Reduced Redundancy Storage. Only
/// application when storing outputs on S3.
/// </summary>
[JsonProperty("rrs", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Rrs { get; set; }
/// <summary>
/// Gets or sets the maximum duration to use for each segment in segmented outputs.
/// </summary>
[JsonProperty("segment_seconds", NullValueHandling = NullValueHandling.Ignore)]
public int? SegmentSeconds { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to apply a sharpen filter to the output video.
/// </summary>
[JsonProperty("sharpet", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Sharpen { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to skip the input audio track, if one is present.
/// </summary>
[JsonProperty("skip_audio", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? SkipAudio { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to skip the input video track, if one is present.
/// </summary>
[JsonProperty("skip_video", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? SkipVideo { get; set; }
/// <summary>
/// Gets or sets the target transcoding speed, from 1 to 5.
/// 1 is the slowest, resulting in the smallest file.
/// </summary>
[JsonProperty("speed", NullValueHandling = NullValueHandling.Ignore)]
public int? Speed { get; set; }
/// <summary>
/// Gets or sets the time to start creating a subclip of the movie at.
/// </summary>
[JsonProperty("start_clip", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
public string StartClip { get; set; }
/// <summary>
/// Gets or sets a collection of streams to be re-formatted as a playlist.
/// </summary>
[JsonProperty("streams", NullValueHandling = NullValueHandling.Ignore)]
public PlaylistStream[] Streams { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enable "strict" mode. Will cause jobs to fail with invalid encoding
/// settings,
/// rather than having the service move bad parameters into valid ranges.
/// </summary>
[JsonProperty("strict", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Strict { get; set; }
/// <summary>
/// Gets or sets a collection of thumbnails settings to use for the output.
/// </summary>
[JsonProperty("thumbnails", NullValueHandling = NullValueHandling.Ignore)]
public Thumbnails[] Thumbnails { get; set; }
/// <summary>
/// Gets or sets the tuning value to use when performing H264 encoding.
/// </summary>
[JsonProperty("tuning", NullValueHandling = NullValueHandling.Ignore)]
public Tuning? Tuning { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to scale the input
/// up to the output resolution if necessary.
/// </summary>
[JsonProperty("upscale", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BooleanConverter))]
public bool? Upscale { get; set; }
/// <summary>
/// Gets or sets the destination for the output file. If an S3 bucket,
/// the bucket must have write permission enabled for aws@zencoder.com.
/// Can also be an FTP/SFTP server.
/// </summary>
[JsonProperty("url", DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore)]
public string Url { get; set; }
/// <summary>
/// Gets or sets the desired output bitrate for the video, in Kbps, if applicable.
/// </summary>
[JsonProperty("video_bitrate", NullValueHandling = NullValueHandling.Ignore)]
public int? VideoBitrate { get; set; }
/// <summary>
/// Gets or sets the video codec to use for the output, if applicable.
/// </summary>
[JsonProperty("video_codec", NullValueHandling = NullValueHandling.Ignore)]
public VideoCodec? VideoCodec { get; set; }
/// <summary>
/// Gets or sets the collection of watermarks to apply to the output video, if applicable.
/// </summary>
[JsonProperty("watermarks", NullValueHandling = NullValueHandling.Ignore)]
public Watermark[] Watermarks { get; set; }
/// <summary>
/// Gets or sets the width of the output video, if applicable.
/// </summary>
[JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)]
public int? Width { get; set; }
/// <summary>
/// Appends the given S3 access control to this instance's <see cref="AccessControl" /> collection.
/// </summary>
/// <param name="accessControl">The access controls to append.</param>
/// <returns>The instance.</returns>
public Output WithAccessControl(S3Access accessControl)
{
return WithAccessControls(new[] {accessControl});
}
/// <summary>
/// Appends the given collection S3 access controls to this instance's <see cref="AccessControl" /> collection.
/// </summary>
/// <param name="accessControls">The access controls to append.</param>
/// <returns>The instance.</returns>
public Output WithAccessControls(IEnumerable<S3Access> accessControls)
{
if (accessControls != null)
AccessControl = (AccessControl ?? new S3Access[0]).Concat(accessControls).ToArray();
return this;
}
/// <summary>
/// Sets this instance's clipping (<see cref="StartClip" /> and <see cref="ClipLength" />) properties.
/// </summary>
/// <param name="startClip">The start clip to set.</param>
/// <param name="clipLength">The clip length to set.</param>
/// <returns>This instance.</returns>
public Output WithClip(TimeSpan? startClip, TimeSpan? clipLength)
{
StartClip = null;
ClipLength = null;
if (startClip != null)
StartClip = startClip.Value.TotalSeconds.ToString("N1", CultureInfo.InvariantCulture);
if (clipLength != null)
ClipLength = clipLength.Value.TotalSeconds.ToString("N1", CultureInfo.InvariantCulture);
return this;
}
/// <summary>
/// Sets this instance's <see cref="Thumbnails" /> property.
/// </summary>
/// <param name="thumbnails">The thumbnails to set.</param>
/// <returns>This instance.</returns>
public Output WithThumbnails(Thumbnails thumbnails)
{
return WithThumbnails(thumbnails != null ? new Thumbnails[1] {thumbnails} : null);
}
/// <summary>
/// Sets this instance's <see cref="Thumbnails" /> property.
/// </summary>
/// <param name="thumbnails">The thumbnails collection to set.</param>
/// <returns>This instance.</returns>
public Output WithThumbnails(IEnumerable<Thumbnails> thumbnails)
{
var t = thumbnails != null ? thumbnails.ToArray() : new Thumbnails[0];
Thumbnails = t.Length > 0 ? t : null;
return this;
}
/// <summary>
/// Sets the instance's <see cref="Url" /> property.
/// </summary>
/// <param name="url">The URL to set.</param>
/// <returns>This instance.</returns>
public Output WithUrl(Uri url)
{
Url = url.ToString();
return this;
}
/// <summary>
/// Appends a <see cref="Notification" /> to this instance's <see cref="Notification" /> collection.
/// </summary>
/// <param name="notification">The notification to append.</param>
/// <returns>This instance.</returns>
public Output WithNotification(Notification.Notification notification)
{
if (notification != null)
return WithNotifications(new[] {notification});
return this;
}
/// <summary>
/// Appends a collection of <see cref="Notification" />s to this instance's <see cref="Notification" /> collection.
/// </summary>
/// <param name="notifications">The notifications to append.</param>
/// <returns>This instance.</returns>
public Output WithNotifications(IEnumerable<Notification.Notification> notifications)
{
if (notifications != null)
Notifications = (Notifications ?? new Notification.Notification[0]).Concat(notifications).ToArray();
return this;
}
/// <summary>
/// Appends a <see cref="Watermark" /> to this instance's <see cref="Watermark" /> collection.
/// </summary>
/// <param name="watermark">The watermark to append.</param>
/// <returns>This instance.</returns>
public Output WithWatermark(Watermark watermark)
{
if (watermark != null)
return WithWatermarks(new[] {watermark});
return this;
}
/// <summary>
/// Appends a collection of <see cref="Watermark" />s to this instance's <see cref="Watermark" /> collection.
/// </summary>
/// <param name="watermarks">The watermarks to append.</param>
/// <returns>This instance.</returns>
public Output WithWatermarks(IEnumerable<Watermark> watermarks)
{
if (watermarks != null)
Watermarks = (Watermarks ?? new Watermark[0]).Concat(watermarks).ToArray();
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using fNbt;
using fNbt.Serialization;
using TrueCraft.API.World;
using TrueCraft.API;
using TrueCraft.Core.Logic.Blocks;
namespace TrueCraft.Core.World
{
public class Chunk : INbtSerializable, IChunk
{
public const int Width = 16, Height = 128, Depth = 16;
public event EventHandler Disposed;
public void Dispose()
{
if (Disposed != null)
Disposed(this, null);
}
[NbtIgnore]
public DateTime LastAccessed { get; set; }
[NbtIgnore]
public bool IsModified { get; set; }
[NbtIgnore]
public byte[] Data { get; set; }
[NbtIgnore]
public NibbleSlice Metadata { get; set; }
[NbtIgnore]
public NibbleSlice BlockLight { get; set; }
[NbtIgnore]
public NibbleSlice SkyLight { get; set; }
public byte[] Biomes { get; set; }
public int[] HeightMap { get; set; }
public int MaxHeight { get; private set; }
[TagName("xPos")]
public int X { get; set; }
[TagName("zPos")]
public int Z { get; set; }
[NbtIgnore]
private bool _LightPopulated;
public bool LightPopulated
{
get
{
return _LightPopulated;
}
set
{
_LightPopulated = value;
IsModified = true;
}
}
public Dictionary<Coordinates3D, NbtCompound> TileEntities { get; set; }
public Coordinates2D Coordinates
{
get
{
return new Coordinates2D(X, Z);
}
set
{
X = value.X;
Z = value.Z;
}
}
public long LastUpdate { get; set; }
public bool TerrainPopulated { get; set; }
[NbtIgnore]
public IRegion ParentRegion { get; set; }
public Chunk()
{
Biomes = new byte[Width * Depth];
HeightMap = new int[Width * Depth];
TileEntities = new Dictionary<Coordinates3D, NbtCompound>();
TerrainPopulated = false;
LightPopulated = false;
MaxHeight = 0;
const int size = Width * Height * Depth;
const int halfSize = size / 2;
Data = new byte[size + halfSize * 3];
Metadata = new NibbleSlice(Data, size, halfSize);
BlockLight = new NibbleSlice(Data, size + halfSize, halfSize);
SkyLight = new NibbleSlice(Data, size + halfSize * 2, halfSize);
}
public Chunk(Coordinates2D coordinates) : this()
{
X = coordinates.X;
Z = coordinates.Z;
}
public byte GetBlockID(Coordinates3D coordinates)
{
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
return Data[index];
}
public byte GetMetadata(Coordinates3D coordinates)
{
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
return Metadata[index];
}
public byte GetSkyLight(Coordinates3D coordinates)
{
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
return SkyLight[index];
}
public byte GetBlockLight(Coordinates3D coordinates)
{
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
return BlockLight[index];
}
/// <summary>
/// Sets the block ID at specific coordinates relative to this chunk.
/// Warning: The parent world's BlockChanged event handler does not get called.
/// </summary>
public void SetBlockID(Coordinates3D coordinates, byte value)
{
IsModified = true;
if (ParentRegion != null)
ParentRegion.DamageChunk(Coordinates);
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
Data[index] = value;
if (value == AirBlock.BlockID)
Metadata[index] = 0x0;
var oldHeight = GetHeight((byte)coordinates.X, (byte)coordinates.Z);
if (value == AirBlock.BlockID)
{
if (oldHeight <= coordinates.Y)
{
// Shift height downwards
while (coordinates.Y > 0)
{
coordinates.Y--;
if (GetBlockID(coordinates) != 0)
{
SetHeight((byte)coordinates.X, (byte)coordinates.Z, coordinates.Y);
if (coordinates.Y > MaxHeight)
MaxHeight = coordinates.Y;
break;
}
}
}
}
else
{
if (oldHeight < coordinates.Y)
SetHeight((byte)coordinates.X, (byte)coordinates.Z, coordinates.Y);
}
}
/// <summary>
/// Sets the metadata at specific coordinates relative to this chunk.
/// Warning: The parent world's BlockChanged event handler does not get called.
/// </summary>
public void SetMetadata(Coordinates3D coordinates, byte value)
{
IsModified = true;
if (ParentRegion != null)
ParentRegion.DamageChunk(Coordinates);
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
Metadata[index] = value;
}
/// <summary>
/// Sets the sky light at specific coordinates relative to this chunk.
/// Warning: The parent world's BlockChanged event handler does not get called.
/// </summary>
public void SetSkyLight(Coordinates3D coordinates, byte value)
{
IsModified = true;
if (ParentRegion != null)
ParentRegion.DamageChunk(Coordinates);
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
SkyLight[index] = value;
}
/// <summary>
/// Sets the block light at specific coordinates relative to this chunk.
/// Warning: The parent world's BlockChanged event handler does not get called.
/// </summary>
public void SetBlockLight(Coordinates3D coordinates, byte value)
{
IsModified = true;
if (ParentRegion != null)
ParentRegion.DamageChunk(Coordinates);
int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width);
BlockLight[index] = value;
}
/// <summary>
/// Gets the tile entity for the given coordinates. May return null.
/// </summary>
public NbtCompound GetTileEntity(Coordinates3D coordinates)
{
if (TileEntities.ContainsKey(coordinates))
return TileEntities[coordinates];
return null;
}
/// <summary>
/// Sets the tile entity at the given coordinates to the given value.
/// </summary>
public void SetTileEntity(Coordinates3D coordinates, NbtCompound value)
{
if (value == null && TileEntities.ContainsKey(coordinates))
TileEntities.Remove(coordinates);
else
TileEntities[coordinates] = value;
IsModified = true;
if (ParentRegion != null)
ParentRegion.DamageChunk(Coordinates);
}
/// <summary>
/// Gets the height of the specified column.
/// </summary>
public int GetHeight(byte x, byte z)
{
return HeightMap[(x * Width) + z];
}
private void SetHeight(byte x, byte z, int value)
{
IsModified = true;
HeightMap[(x * Width) + z] = value;
}
public void UpdateHeightMap()
{
for (byte x = 0; x < Chunk.Width; x++)
{
for (byte z = 0; z < Chunk.Depth; z++)
{
int y;
for (y = Chunk.Height - 1; y >= 0; y--)
{
int index = y + (z * Height) + (x * Height * Width);
if (Data[index] != 0)
{
SetHeight(x, z, y);
if (y > MaxHeight)
MaxHeight = y;
break;
}
}
if (y == 0)
SetHeight(x, z, 0);
}
}
}
public NbtFile ToNbt()
{
var serializer = new NbtSerializer(typeof(Chunk));
var compound = serializer.Serialize(this, "Level") as NbtCompound;
var file = new NbtFile();
file.RootTag.Add(compound);
return file;
}
public static Chunk FromNbt(NbtFile nbt)
{
var serializer = new NbtSerializer(typeof(Chunk));
var chunk = (Chunk)serializer.Deserialize(nbt.RootTag["Level"]);
return chunk;
}
public NbtTag Serialize(string tagName)
{
var chunk = new NbtCompound(tagName);
var entities = new NbtList("Entities", NbtTagType.Compound);
chunk.Add(entities);
chunk.Add(new NbtInt("X", X));
chunk.Add(new NbtInt("Z", Z));
chunk.Add(new NbtByte("LightPopulated", (byte)(LightPopulated ? 1 : 0)));
chunk.Add(new NbtByte("TerrainPopulated", (byte)(TerrainPopulated ? 1 : 0)));
chunk.Add(new NbtByteArray("Blocks", Data));
chunk.Add(new NbtByteArray("Data", Metadata.ToArray()));
chunk.Add(new NbtByteArray("SkyLight", SkyLight.ToArray()));
chunk.Add(new NbtByteArray("BlockLight", BlockLight.ToArray()));
var tiles = new NbtList("TileEntities", NbtTagType.Compound);
foreach (var kvp in TileEntities)
{
var c = new NbtCompound();
c.Add(new NbtList("coordinates", new[] {
new NbtInt(kvp.Key.X),
new NbtInt(kvp.Key.Y),
new NbtInt(kvp.Key.Z)
}));
c.Add(new NbtList("value", new[] { kvp.Value }));
tiles.Add(c);
}
chunk.Add(tiles);
// TODO: Entities
return chunk;
}
public void Deserialize(NbtTag value)
{
var tag = (NbtCompound)value;
X = tag["X"].IntValue;
Z = tag["Z"].IntValue;
if (tag.Contains("TerrainPopulated"))
TerrainPopulated = tag["TerrainPopulated"].ByteValue > 0;
if (tag.Contains("LightPopulated"))
LightPopulated = tag["LightPopulated"].ByteValue > 0;
const int size = Width * Height * Depth;
const int halfSize = size / 2;
Data = new byte[(int)(size * 2.5)];
Buffer.BlockCopy(tag["Blocks"].ByteArrayValue, 0, Data, 0, size);
Metadata = new NibbleSlice(Data, size, halfSize);
BlockLight = new NibbleSlice(Data, size + halfSize, halfSize);
SkyLight = new NibbleSlice(Data, size + halfSize * 2, halfSize);
Metadata.Deserialize(tag["Data"]);
BlockLight.Deserialize(tag["BlockLight"]);
SkyLight.Deserialize(tag["SkyLight"]);
if (tag.Contains("TileEntities"))
{
foreach (var entity in tag["TileEntities"] as NbtList)
{
TileEntities[new Coordinates3D(entity["coordinates"][0].IntValue,
entity["coordinates"][1].IntValue,
entity["coordinates"][2].IntValue)] = entity["value"][0] as NbtCompound;
}
}
UpdateHeightMap();
// TODO: Entities
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type long with 2 components, used for implementing swizzling for lvec2.
/// </summary>
[Serializable]
[DataContract(Namespace = "swizzle")]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_lvec2
{
#region Fields
/// <summary>
/// x-component
/// </summary>
[DataMember]
internal readonly long x;
/// <summary>
/// y-component
/// </summary>
[DataMember]
internal readonly long y;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_lvec2.
/// </summary>
internal swizzle_lvec2(long x, long y)
{
this.x = x;
this.y = y;
}
#endregion
#region Properties
/// <summary>
/// Returns lvec2.xx swizzling.
/// </summary>
public lvec2 xx => new lvec2(x, x);
/// <summary>
/// Returns lvec2.rr swizzling (equivalent to lvec2.xx).
/// </summary>
public lvec2 rr => new lvec2(x, x);
/// <summary>
/// Returns lvec2.xxx swizzling.
/// </summary>
public lvec3 xxx => new lvec3(x, x, x);
/// <summary>
/// Returns lvec2.rrr swizzling (equivalent to lvec2.xxx).
/// </summary>
public lvec3 rrr => new lvec3(x, x, x);
/// <summary>
/// Returns lvec2.xxxx swizzling.
/// </summary>
public lvec4 xxxx => new lvec4(x, x, x, x);
/// <summary>
/// Returns lvec2.rrrr swizzling (equivalent to lvec2.xxxx).
/// </summary>
public lvec4 rrrr => new lvec4(x, x, x, x);
/// <summary>
/// Returns lvec2.xxxy swizzling.
/// </summary>
public lvec4 xxxy => new lvec4(x, x, x, y);
/// <summary>
/// Returns lvec2.rrrg swizzling (equivalent to lvec2.xxxy).
/// </summary>
public lvec4 rrrg => new lvec4(x, x, x, y);
/// <summary>
/// Returns lvec2.xxy swizzling.
/// </summary>
public lvec3 xxy => new lvec3(x, x, y);
/// <summary>
/// Returns lvec2.rrg swizzling (equivalent to lvec2.xxy).
/// </summary>
public lvec3 rrg => new lvec3(x, x, y);
/// <summary>
/// Returns lvec2.xxyx swizzling.
/// </summary>
public lvec4 xxyx => new lvec4(x, x, y, x);
/// <summary>
/// Returns lvec2.rrgr swizzling (equivalent to lvec2.xxyx).
/// </summary>
public lvec4 rrgr => new lvec4(x, x, y, x);
/// <summary>
/// Returns lvec2.xxyy swizzling.
/// </summary>
public lvec4 xxyy => new lvec4(x, x, y, y);
/// <summary>
/// Returns lvec2.rrgg swizzling (equivalent to lvec2.xxyy).
/// </summary>
public lvec4 rrgg => new lvec4(x, x, y, y);
/// <summary>
/// Returns lvec2.xy swizzling.
/// </summary>
public lvec2 xy => new lvec2(x, y);
/// <summary>
/// Returns lvec2.rg swizzling (equivalent to lvec2.xy).
/// </summary>
public lvec2 rg => new lvec2(x, y);
/// <summary>
/// Returns lvec2.xyx swizzling.
/// </summary>
public lvec3 xyx => new lvec3(x, y, x);
/// <summary>
/// Returns lvec2.rgr swizzling (equivalent to lvec2.xyx).
/// </summary>
public lvec3 rgr => new lvec3(x, y, x);
/// <summary>
/// Returns lvec2.xyxx swizzling.
/// </summary>
public lvec4 xyxx => new lvec4(x, y, x, x);
/// <summary>
/// Returns lvec2.rgrr swizzling (equivalent to lvec2.xyxx).
/// </summary>
public lvec4 rgrr => new lvec4(x, y, x, x);
/// <summary>
/// Returns lvec2.xyxy swizzling.
/// </summary>
public lvec4 xyxy => new lvec4(x, y, x, y);
/// <summary>
/// Returns lvec2.rgrg swizzling (equivalent to lvec2.xyxy).
/// </summary>
public lvec4 rgrg => new lvec4(x, y, x, y);
/// <summary>
/// Returns lvec2.xyy swizzling.
/// </summary>
public lvec3 xyy => new lvec3(x, y, y);
/// <summary>
/// Returns lvec2.rgg swizzling (equivalent to lvec2.xyy).
/// </summary>
public lvec3 rgg => new lvec3(x, y, y);
/// <summary>
/// Returns lvec2.xyyx swizzling.
/// </summary>
public lvec4 xyyx => new lvec4(x, y, y, x);
/// <summary>
/// Returns lvec2.rggr swizzling (equivalent to lvec2.xyyx).
/// </summary>
public lvec4 rggr => new lvec4(x, y, y, x);
/// <summary>
/// Returns lvec2.xyyy swizzling.
/// </summary>
public lvec4 xyyy => new lvec4(x, y, y, y);
/// <summary>
/// Returns lvec2.rggg swizzling (equivalent to lvec2.xyyy).
/// </summary>
public lvec4 rggg => new lvec4(x, y, y, y);
/// <summary>
/// Returns lvec2.yx swizzling.
/// </summary>
public lvec2 yx => new lvec2(y, x);
/// <summary>
/// Returns lvec2.gr swizzling (equivalent to lvec2.yx).
/// </summary>
public lvec2 gr => new lvec2(y, x);
/// <summary>
/// Returns lvec2.yxx swizzling.
/// </summary>
public lvec3 yxx => new lvec3(y, x, x);
/// <summary>
/// Returns lvec2.grr swizzling (equivalent to lvec2.yxx).
/// </summary>
public lvec3 grr => new lvec3(y, x, x);
/// <summary>
/// Returns lvec2.yxxx swizzling.
/// </summary>
public lvec4 yxxx => new lvec4(y, x, x, x);
/// <summary>
/// Returns lvec2.grrr swizzling (equivalent to lvec2.yxxx).
/// </summary>
public lvec4 grrr => new lvec4(y, x, x, x);
/// <summary>
/// Returns lvec2.yxxy swizzling.
/// </summary>
public lvec4 yxxy => new lvec4(y, x, x, y);
/// <summary>
/// Returns lvec2.grrg swizzling (equivalent to lvec2.yxxy).
/// </summary>
public lvec4 grrg => new lvec4(y, x, x, y);
/// <summary>
/// Returns lvec2.yxy swizzling.
/// </summary>
public lvec3 yxy => new lvec3(y, x, y);
/// <summary>
/// Returns lvec2.grg swizzling (equivalent to lvec2.yxy).
/// </summary>
public lvec3 grg => new lvec3(y, x, y);
/// <summary>
/// Returns lvec2.yxyx swizzling.
/// </summary>
public lvec4 yxyx => new lvec4(y, x, y, x);
/// <summary>
/// Returns lvec2.grgr swizzling (equivalent to lvec2.yxyx).
/// </summary>
public lvec4 grgr => new lvec4(y, x, y, x);
/// <summary>
/// Returns lvec2.yxyy swizzling.
/// </summary>
public lvec4 yxyy => new lvec4(y, x, y, y);
/// <summary>
/// Returns lvec2.grgg swizzling (equivalent to lvec2.yxyy).
/// </summary>
public lvec4 grgg => new lvec4(y, x, y, y);
/// <summary>
/// Returns lvec2.yy swizzling.
/// </summary>
public lvec2 yy => new lvec2(y, y);
/// <summary>
/// Returns lvec2.gg swizzling (equivalent to lvec2.yy).
/// </summary>
public lvec2 gg => new lvec2(y, y);
/// <summary>
/// Returns lvec2.yyx swizzling.
/// </summary>
public lvec3 yyx => new lvec3(y, y, x);
/// <summary>
/// Returns lvec2.ggr swizzling (equivalent to lvec2.yyx).
/// </summary>
public lvec3 ggr => new lvec3(y, y, x);
/// <summary>
/// Returns lvec2.yyxx swizzling.
/// </summary>
public lvec4 yyxx => new lvec4(y, y, x, x);
/// <summary>
/// Returns lvec2.ggrr swizzling (equivalent to lvec2.yyxx).
/// </summary>
public lvec4 ggrr => new lvec4(y, y, x, x);
/// <summary>
/// Returns lvec2.yyxy swizzling.
/// </summary>
public lvec4 yyxy => new lvec4(y, y, x, y);
/// <summary>
/// Returns lvec2.ggrg swizzling (equivalent to lvec2.yyxy).
/// </summary>
public lvec4 ggrg => new lvec4(y, y, x, y);
/// <summary>
/// Returns lvec2.yyy swizzling.
/// </summary>
public lvec3 yyy => new lvec3(y, y, y);
/// <summary>
/// Returns lvec2.ggg swizzling (equivalent to lvec2.yyy).
/// </summary>
public lvec3 ggg => new lvec3(y, y, y);
/// <summary>
/// Returns lvec2.yyyx swizzling.
/// </summary>
public lvec4 yyyx => new lvec4(y, y, y, x);
/// <summary>
/// Returns lvec2.gggr swizzling (equivalent to lvec2.yyyx).
/// </summary>
public lvec4 gggr => new lvec4(y, y, y, x);
/// <summary>
/// Returns lvec2.yyyy swizzling.
/// </summary>
public lvec4 yyyy => new lvec4(y, y, y, y);
/// <summary>
/// Returns lvec2.gggg swizzling (equivalent to lvec2.yyyy).
/// </summary>
public lvec4 gggg => new lvec4(y, y, y, y);
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Globalization;
using Windows.Media.SpeechRecognition;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SpeechAndTTS
{
public sealed partial class ListConstraintScenario : Page
{
/// <summary>
/// This HResult represents the scenario where a user is prompted to allow in-app speech, but
/// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
/// not per-app.
/// </summary>
private static uint HResultPrivacyStatementDeclined = 0x80045509;
/// <summary>
/// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot
/// be found. This may occur if the language is installed, but the speech pack for that language is not.
/// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options.
/// </summary>
private static uint HResultRecognizerNotFound = 0x8004503a;
private SpeechRecognizer speechRecognizer;
private CoreDispatcher dispatcher;
private ResourceContext speechContext;
private ResourceMap speechResourceMap;
private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
public ListConstraintScenario()
{
InitializeComponent();
}
/// <summary>
/// When activating the scenario, ensure we have permission from the user to access their microphone, and
/// provide an appropriate path for the user to enable access to the microphone if they haven't
/// given explicit permission for it.
/// </summary>
/// <param name="e">The navigation event details</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
// Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
if (permissionGained)
{
// Enable the recognition buttons.
btnRecognizeWithUI.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
string langTag = speechLanguage.LanguageTag;
speechContext = ResourceContext.GetForCurrentView();
speechContext.Languages = new string[] { langTag };
speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
PopulateLanguageDropdown();
await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
cbLanguageSelection.IsEnabled = false;
}
}
/// <summary>
/// Look up the supported languages for this speech recognition scenario,
/// that are installed on this machine, and populate a dropdown with a list.
/// </summary>
private void PopulateLanguageDropdown()
{
// disable the callback so we don't accidentally trigger initialization of the recognizer
// while initialization is already in progress.
cbLanguageSelection.SelectionChanged -= cbLanguageSelection_SelectionChanged;
Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages;
foreach(Language lang in supportedLanguages)
{
ComboBoxItem item = new ComboBoxItem();
item.Tag = lang;
item.Content = lang.DisplayName;
cbLanguageSelection.Items.Add(item);
if(lang.LanguageTag == defaultLanguage.LanguageTag)
{
item.IsSelected = true;
cbLanguageSelection.SelectedItem = item;
}
}
cbLanguageSelection.SelectionChanged += cbLanguageSelection_SelectionChanged;
}
/// <summary>
/// When a user changes the speech recognition language, trigger re-initialization of the
/// speech engine with that language, and change any speech-specific UI assets.
/// </summary>
/// <param name="sender">Ignored</param>
/// <param name="e">Ignored</param>
private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
Language newLanguage = (Language)item.Tag;
if (speechRecognizer != null)
{
if (speechRecognizer.CurrentLanguage == newLanguage)
{
return;
}
}
// trigger cleanup and re-initialization of speech.
try
{
// update the context for resource lookup
speechContext.Languages = new string[] { newLanguage.LanguageTag };
await InitializeRecognizer(newLanguage);
}
catch (Exception exception)
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
/// <summary>
/// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks,
/// dipose the speech recognizer, and clean up to ensure the scenario is not still attempting to recognize
/// speech while not in view.
/// </summary>
/// <param name="e">Details about the navigation event</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (speechRecognizer != null)
{
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
if (recognitionOperation != null)
{
recognitionOperation.Cancel();
recognitionOperation = null;
}
}
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
}
/// <summary>
/// Initialize Speech Recognizer and compile constraints.
/// </summary>
/// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
/// <returns>Awaitable task.</returns>
private async Task InitializeRecognizer(Language recognizerLanguage)
{
if(speechRecognizer != null)
{
// cleanup prior to re-initializing this scenario.
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
try
{
// Create an instance of SpeechRecognizer.
speechRecognizer = new SpeechRecognizer(recognizerLanguage);
// Provide feedback to the user about the state of the recognizer.
speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
// Add a list constraint to the recognizer.
speechRecognizer.Constraints.Add(
new SpeechRecognitionListConstraint(
new List<string>()
{
speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString
}, "Home"));
speechRecognizer.Constraints.Add(
new SpeechRecognitionListConstraint(
new List<string>()
{
speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString
}, "GoToContosoStudio"));
speechRecognizer.Constraints.Add(
new SpeechRecognitionListConstraint(
new List<string>()
{
speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString,
speechResourceMap.GetValue("ListGrammarOpenMessage", speechContext).ValueAsString
}, "Message"));
speechRecognizer.Constraints.Add(
new SpeechRecognitionListConstraint(
new List<string>()
{
speechResourceMap.GetValue("ListGrammarSendEmail", speechContext).ValueAsString,
speechResourceMap.GetValue("ListGrammarCreateEmail", speechContext).ValueAsString
}, "Email"));
speechRecognizer.Constraints.Add(
new SpeechRecognitionListConstraint(
new List<string>()
{
speechResourceMap.GetValue("ListGrammarCallNitaFarley", speechContext).ValueAsString,
speechResourceMap.GetValue("ListGrammarCallNita", speechContext).ValueAsString
}, "CallNita"));
speechRecognizer.Constraints.Add(
new SpeechRecognitionListConstraint(
new List<string>()
{
speechResourceMap.GetValue("ListGrammarCallWayneSigmon", speechContext).ValueAsString,
speechResourceMap.GetValue("ListGrammarCallWayne", speechContext).ValueAsString
}, "CallWayne"));
// RecognizeWithUIAsync allows developers to customize the prompts.
string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'",
speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString,
speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString,
speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString);
speechRecognizer.UIOptions.ExampleText = uiOptionsText;
helpTextBlock.Text = string.Format("{0}\n{1}",
speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString,
uiOptionsText);
// Compile the constraint.
SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
// Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
{
// Disable the recognition buttons.
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
// Let the user know that the grammar didn't compile properly.
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Unable to compile grammar.";
}
else
{
btnRecognizeWithUI.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
resultTextBlock.Visibility = Visibility.Collapsed;
}
}
catch(Exception ex)
{
if((uint)ex.HResult == HResultRecognizerNotFound)
{
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Speech Language pack for selected language not installed.";
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
await messageDialog.ShowAsync();
}
}
}
/// <summary>
/// Handle SpeechRecognizer state changed events by updating a UI component.
/// </summary>
/// <param name="sender">Speech recognizer that generated this status event</param>
/// <param name="args">The recognizer's status</param>
private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
});
}
/// <summary>
/// Uses the recognizer constructed earlier to listen for speech from the user before displaying
/// it back on the screen. Uses the built-in speech recognition UI.
/// </summary>
/// <param name="sender">Button that triggered this event</param>
/// <param name="e">State information about the routed event</param>
private async void RecognizeWithUIListConstraint_Click(object sender, RoutedEventArgs e)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
// Start recognition.
try
{
recognitionOperation = speechRecognizer.RecognizeWithUIAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
string tag = "unknown";
if(speechRecognitionResult.Constraint != null)
{
// Only attempt to retreive the tag if we didn't hit the garbage rule.
tag = speechRecognitionResult.Constraint.Tag;
}
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString());
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString() );
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
// Handle the speech privacy policy error.
if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "The privacy statement was declined.";
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
}
/// <summary>
/// Uses the recognizer constructed earlier to listen for speech from the user before displaying
/// it back on the screen. Uses developer-provided UI for user feedback.
/// </summary>
/// <param name="sender">Button that triggered this event</param>
/// <param name="e">State information about the routed event</param>
private async void RecognizeWithoutUIListConstraint_Click(object sender, RoutedEventArgs e)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
// Disable the UI while recognition is occurring, and provide feedback to the user about current state.
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
cbLanguageSelection.IsEnabled = false;
listenWithoutUIButtonText.Text = " listening for speech...";
// Start recognition.
try
{
// Save the recognition operation so we can cancel it (as it does not provide a blocking
// UI, unlike RecognizeWithAsync()
recognitionOperation = speechRecognizer.RecognizeAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result. A cancelled task should do nothing.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
string tag = "unknown";
if (speechRecognitionResult.Constraint != null)
{
// Only attempt to retreive the tag if we didn't hit the garbage rule.
tag = speechRecognitionResult.Constraint.Tag;
}
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString());
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
// Handle the speech privacy policy error.
if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "The privacy statement was declined.";
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
// Reset UI state.
listenWithoutUIButtonText.Text = " without UI";
cbLanguageSelection.IsEnabled = true;
btnRecognizeWithUI.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui
{
public class MouseLocker : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject
{
public MouseLocker(global::haxe.lang.EmptyObject empty) : base()
{
unchecked
{
}
#line default
}
public MouseLocker() : base()
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.prevState = false;
#line 42 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.panel = false;
}
#line default
}
public static object __hx_createEmpty()
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return new global::pony.unity3d.ui.MouseLocker(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static object __hx_create(global::Array arr)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return new global::pony.unity3d.ui.MouseLocker();
}
#line default
}
public bool panel;
public bool prevState;
public virtual void Update()
{
unchecked
{
#line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
bool h = default(bool);
#line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (this.panel)
{
h = ( this.guiTexture as global::UnityEngine.GUIElement ).HitTest(((global::UnityEngine.Vector3) (new global::UnityEngine.Vector3(((float) (( global::UnityEngine.Input.mousePosition.x - global::pony.unity3d.Fixed2dCamera.begin )) ), ((float) (global::UnityEngine.Input.mousePosition.y) ))) ));
}
else
{
h = ( this.guiTexture as global::UnityEngine.GUIElement ).HitTest(((global::UnityEngine.Vector3) (new global::UnityEngine.Vector3(((float) (( global::UnityEngine.Input.mousePosition.x + ( ((double) ((( global::UnityEngine.Screen.width - global::pony.unity3d.Fixed2dCamera.begin ))) ) / 2 ) )) ), ((float) (global::UnityEngine.Input.mousePosition.y) ))) ));
}
if (( this.prevState != h ))
{
if (h)
{
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
global::pony.events.LV<int> _g = global::pony.unity3d.scene.MouseHelper.@lock;
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int _g1 = _g.@value;
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
{
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int v = ( _g1 + 1 );
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (( v != _g.@value ))
{
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
_g.@value = v;
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
{
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
_g.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{v})) ), ((object) (_g.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
global::pony.events.LV<int> __temp_expr752 = _g;
}
}
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int __temp_expr753 = v;
}
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int __temp_expr754 = _g1;
}
else
{
global::pony.events.LV<int> _g2 = global::pony.unity3d.scene.MouseHelper.@lock;
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int _g11 = _g2.@value;
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
{
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int v1 = ( _g11 - 1 );
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (( v1 != _g2.@value ))
{
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
_g2.@value = v1;
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
{
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
_g2.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{v1})) ), ((object) (_g2.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
global::pony.events.LV<int> __temp_expr749 = _g2;
}
}
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int __temp_expr750 = v1;
}
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int __temp_expr751 = _g11;
}
this.prevState = h;
}
}
#line default
}
public virtual void OnDisable()
{
unchecked
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (this.prevState)
{
this.prevState = false;
{
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
global::pony.events.LV<int> _g = global::pony.unity3d.scene.MouseHelper.@lock;
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int _g1 = _g.@value;
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
{
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int v = ( _g1 - 1 );
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (( v != _g.@value ))
{
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
_g.@value = v;
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
{
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
_g.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{v})) ), ((object) (_g.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
global::pony.events.LV<int> __temp_expr755 = _g;
}
}
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int __temp_expr756 = v;
}
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
int __temp_expr757 = _g1;
}
}
}
#line default
}
public virtual bool __hx_deleteField(string field, int hash)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return false;
}
#line default
}
public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (isCheck)
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return global::haxe.lang.Runtime.undefined;
}
else
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (throwErrors)
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found.");
}
else
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return default(object);
}
}
}
#line default
}
public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
if (throwErrors)
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type.");
}
else
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return default(double);
}
}
#line default
}
public virtual object __hx_lookupSetField(string field, int hash, object @value)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing.");
}
#line default
}
public virtual double __hx_lookupSetField_f(string field, int hash, double @value)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type.");
}
#line default
}
public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
switch (hash)
{
default:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.__hx_lookupSetField_f(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
switch (hash)
{
case 1575675685:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.hideFlags = ((global::UnityEngine.HideFlags) (@value) );
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 1224700491:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.name = global::haxe.lang.Runtime.toString(@value);
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 5790298:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.tag = global::haxe.lang.Runtime.toString(@value);
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 373703110:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.active = ((bool) (@value) );
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 2117141633:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.enabled = ((bool) (@value) );
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 896046654:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.useGUILayout = ((bool) (@value) );
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 1868699166:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.prevState = ((bool) (@value) );
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
case 1028815620:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.panel = ((bool) (@value) );
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return @value;
}
default:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.__hx_lookupSetField(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
switch (hash)
{
case 1826409040:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) );
}
case 304123084:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) );
}
case 276486854:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) );
}
case 295397041:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) );
}
case 1955029599:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) );
}
case 1575675685:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.hideFlags;
}
case 1224700491:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.name;
}
case 294420221:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) );
}
case 139469119:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) );
}
case 967979664:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) );
}
case 2122408236:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) );
}
case 1328964235:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) );
}
case 1723652455:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) );
}
case 89600725:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) );
}
case 2134927590:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) );
}
case 5790298:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.tag;
}
case 373703110:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.active;
}
case 1471506513:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.gameObject;
}
case 1751728597:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.particleSystem;
}
case 524620744:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.particleEmitter;
}
case 964013983:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.hingeJoint;
}
case 1238753076:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.collider;
}
case 674101152:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.guiTexture;
}
case 262266241:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.guiElement;
}
case 1515196979:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.networkView;
}
case 801759432:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.guiText;
}
case 662730966:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.audio;
}
case 853263683:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.renderer;
}
case 1431885287:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.constantForce;
}
case 1261760260:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.animation;
}
case 1962709206:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.light;
}
case 931940005:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.camera;
}
case 1895479501:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.rigidbody;
}
case 1167273324:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.transform;
}
case 2117141633:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.enabled;
}
case 2084823382:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) );
}
case 1856815770:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) );
}
case 832859768:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) );
}
case 987108662:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) );
}
case 602588383:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) );
}
case 1641152943:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) );
}
case 1416948632:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) );
}
case 757431474:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) );
}
case 896046654:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.useGUILayout;
}
case 718668393:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("OnDisable"), ((int) (718668393) ))) );
}
case 999946793:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Update"), ((int) (999946793) ))) );
}
case 1868699166:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.prevState;
}
case 1028815620:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.panel;
}
default:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.__hx_lookupField(field, hash, throwErrors, isCheck);
}
}
}
#line default
}
public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
switch (hash)
{
default:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return this.__hx_lookupField_f(field, hash, throwErrors);
}
}
}
#line default
}
public virtual object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
switch (hash)
{
case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return global::haxe.lang.Runtime.slowCallField(this, field, dynargs);
}
case 718668393:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.OnDisable();
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
break;
}
case 999946793:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
this.Update();
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
break;
}
default:
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs);
}
}
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
return default(object);
}
#line default
}
public virtual void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("hideFlags");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("name");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("tag");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("active");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("gameObject");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("particleSystem");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("particleEmitter");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("hingeJoint");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("collider");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("guiTexture");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("guiElement");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("networkView");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("guiText");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("audio");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("renderer");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("constantForce");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("animation");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("light");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("camera");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("rigidbody");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("transform");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("enabled");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("useGUILayout");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("prevState");
#line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/MouseLocker.hx"
baseArr.push("panel");
}
#line default
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ReadOnlyBindingListBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>This is the base class from which readonly collections</summary>
//-----------------------------------------------------------------------
#if NETFX_CORE
using System;
namespace Csla
{
/// <summary>
/// This is the base class from which readonly collections
/// of readonly objects should be derived.
/// </summary>
/// <typeparam name="T">Type of the list class.</typeparam>
/// <typeparam name="C">Type of child objects contained in the list.</typeparam>
[Serializable]
public abstract class ReadOnlyBindingListBase<T, C> : ReadOnlyListBase<T, C>
where T : ReadOnlyBindingListBase<T, C>
{ }
}
#else
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using Csla.Properties;
namespace Csla
{
/// <summary>
/// This is the base class from which readonly collections
/// of readonly objects should be derived.
/// </summary>
/// <typeparam name="T">Type of the list class.</typeparam>
/// <typeparam name="C">Type of child objects contained in the list.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable()]
public abstract class ReadOnlyBindingListBase<T, C> :
Core.ReadOnlyBindingList<C>, Csla.Core.IReadOnlyCollection,
ICloneable, Server.IDataPortalTarget
where T : ReadOnlyBindingListBase<T, C>
{
/// <summary>
/// Creates an instance of the object.
/// </summary>
protected ReadOnlyBindingListBase()
{
Initialize();
}
#region Initialize
/// <summary>
/// Override this method to set up event handlers so user
/// code in a partial class can respond to events raised by
/// generated code.
/// </summary>
protected virtual void Initialize()
{ /* allows subclass to initialize events before any other activity occurs */ }
#endregion
#region ICloneable
object ICloneable.Clone()
{
return GetClone();
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual object GetClone()
{
return Core.ObjectCloner.Clone(this);
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>
/// A new object containing the exact data of the original object.
/// </returns>
public T Clone()
{
return (T)GetClone();
}
#endregion
#region Data Access
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")]
private void DataPortal_Create(object criteria)
{
throw new NotSupportedException(Resources.CreateNotSupportedException);
}
/// <summary>
/// Override this method to allow retrieval of an existing business
/// object based on data in the database.
/// </summary>
/// <param name="criteria">An object containing criteria values to identify the object.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
protected virtual void DataPortal_Fetch(object criteria)
{
throw new NotSupportedException(Resources.FetchNotSupportedException);
}
private void DataPortal_Update()
{
throw new NotSupportedException(Resources.UpdateNotSupportedException);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")]
private void DataPortal_Delete(object criteria)
{
throw new NotSupportedException(Resources.DeleteNotSupportedException);
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
#endregion
#region ToArray
/// <summary>
/// Get an array containing all items in the list.
/// </summary>
public C[] ToArray()
{
List<C> result = new List<C>();
foreach (C item in this)
result.Add(item);
return result.ToArray();
}
#endregion
#region IDataPortalTarget Members
void Csla.Server.IDataPortalTarget.CheckRules()
{ }
void Csla.Server.IDataPortalTarget.MarkAsChild()
{ }
void Csla.Server.IDataPortalTarget.MarkNew()
{ }
void Csla.Server.IDataPortalTarget.MarkOld()
{ }
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.DataPortal_OnDataPortalException(e, ex);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.Child_OnDataPortalException(e, ex);
}
#endregion
}
}
#endif
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.IO;
#if !READ_ONLY
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageWriter : BinaryStreamWriter {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
readonly TextMap text_map;
ImageDebugDirectory debug_directory;
byte [] debug_data;
ByteBuffer win32_resources;
const uint pe_header_size = 0x98u;
const uint section_header_size = 0x28u;
const uint file_alignment = 0x200;
const uint section_alignment = 0x2000;
const ulong image_base = 0x00400000;
internal const RVA text_rva = 0x2000;
readonly bool pe64;
readonly bool has_reloc;
readonly uint time_stamp;
internal Section text;
internal Section rsrc;
internal Section reloc;
ushort sections;
ImageWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
: base (stream)
{
this.module = module;
this.metadata = metadata;
this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64;
this.has_reloc = module.Architecture == TargetArchitecture.I386;
this.GetDebugHeader ();
this.GetWin32Resources ();
this.text_map = BuildTextMap ();
this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc?
this.time_stamp = (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds;
}
void GetDebugHeader ()
{
var symbol_writer = metadata.symbol_writer;
if (symbol_writer == null)
return;
if (!symbol_writer.GetDebugHeader (out debug_directory, out debug_data))
debug_data = Empty<byte>.Array;
}
void GetWin32Resources ()
{
var rsrc = GetImageResourceSection ();
if (rsrc == null)
return;
var raw_resources = new byte [rsrc.Data.Length];
Buffer.BlockCopy (rsrc.Data, 0, raw_resources, 0, rsrc.Data.Length);
win32_resources = new ByteBuffer (raw_resources);
}
Section GetImageResourceSection ()
{
if (!module.HasImage)
return null;
const string rsrc_section = ".rsrc";
return module.Image.GetSection (rsrc_section);
}
public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
{
var writer = new ImageWriter (module, metadata, stream);
writer.BuildSections ();
return writer;
}
void BuildSections ()
{
var has_win32_resources = win32_resources != null;
if (has_win32_resources)
sections++;
text = CreateSection (".text", text_map.GetLength (), null);
var previous = text;
if (has_win32_resources) {
rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous);
PatchWin32Resources (win32_resources);
previous = rsrc;
}
if (has_reloc)
reloc = CreateSection (".reloc", 12u, previous);
}
Section CreateSection (string name, uint size, Section previous)
{
return new Section {
Name = name,
VirtualAddress = previous != null
? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment)
: text_rva,
VirtualSize = size,
PointerToRawData = previous != null
? previous.PointerToRawData + previous.SizeOfRawData
: Align (GetHeaderSize (), file_alignment),
SizeOfRawData = Align (size, file_alignment)
};
}
static uint Align (uint value, uint align)
{
align--;
return (value + align) & ~align;
}
void WriteDOSHeader ()
{
Write (new byte [] {
// dos header start
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00,
0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff,
0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// lfanew
0x80, 0x00, 0x00, 0x00,
// dos header end
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09,
0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21,
0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72,
0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63,
0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62,
0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d,
0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
});
}
ushort SizeOfOptionalHeader ()
{
return (ushort) (!pe64 ? 0xe0 : 0xf0);
}
void WritePEFileHeader ()
{
WriteUInt32 (0x00004550); // Magic
WriteUInt16 (GetMachine ()); // Machine
WriteUInt16 (sections); // NumberOfSections
WriteUInt32 (time_stamp);
WriteUInt32 (0); // PointerToSymbolTable
WriteUInt32 (0); // NumberOfSymbols
WriteUInt16 (SizeOfOptionalHeader ()); // SizeOfOptionalHeader
// ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware)
var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020));
if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule)
characteristics |= 0x2000;
WriteUInt16 (characteristics); // Characteristics
}
ushort GetMachine ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 0x014c;
case TargetArchitecture.AMD64:
return 0x8664;
case TargetArchitecture.IA64:
return 0x0200;
case TargetArchitecture.ARMv7:
return 0x01c4;
}
throw new NotSupportedException ();
}
Section LastSection ()
{
if (reloc != null)
return reloc;
if (rsrc != null)
return rsrc;
return text;
}
void WriteOptionalHeaders ()
{
WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic
WriteByte (8); // LMajor
WriteByte (0); // LMinor
WriteUInt32 (text.SizeOfRawData); // CodeSize
WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0)
+ (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize
WriteUInt32 (0); // UninitializedDataSize
var startub_stub = text_map.GetRange (TextSegment.StartupStub);
WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // EntryPointRVA
WriteUInt32 (text_rva); // BaseOfCode
if (!pe64) {
WriteUInt32 (0); // BaseOfData
WriteUInt32 ((uint) image_base); // ImageBase
} else {
WriteUInt64 (image_base); // ImageBase
}
WriteUInt32 (section_alignment); // SectionAlignment
WriteUInt32 (file_alignment); // FileAlignment
WriteUInt16 (4); // OSMajor
WriteUInt16 (0); // OSMinor
WriteUInt16 (0); // UserMajor
WriteUInt16 (0); // UserMinor
WriteUInt16 (4); // SubSysMajor
WriteUInt16 (0); // SubSysMinor
WriteUInt32 (0); // Reserved
var last_section = LastSection();
WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize
WriteUInt32 (text.PointerToRawData); // HeaderSize
WriteUInt32 (0); // Checksum
WriteUInt16 (GetSubSystem ()); // SubSystem
WriteUInt16 ((ushort) module.Characteristics); // DLLFlags
const ulong stack_reserve = 0x100000;
const ulong stack_commit = 0x1000;
const ulong heap_reserve = 0x100000;
const ulong heap_commit = 0x1000;
if (!pe64) {
WriteUInt32 ((uint) stack_reserve);
WriteUInt32 ((uint) stack_commit);
WriteUInt32 ((uint) heap_reserve);
WriteUInt32 ((uint) heap_commit);
} else {
WriteUInt64 (stack_reserve);
WriteUInt64 (stack_commit);
WriteUInt64 (heap_reserve);
WriteUInt64 (heap_commit);
}
WriteUInt32 (0); // LoaderFlags
WriteUInt32 (16); // NumberOfDataDir
WriteZeroDataDirectory (); // ExportTable
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable
if (rsrc != null) { // ResourceTable
WriteUInt32 (rsrc.VirtualAddress);
WriteUInt32 (rsrc.VirtualSize);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // ExceptionTable
WriteZeroDataDirectory (); // CertificateTable
WriteUInt32 (reloc != null ? reloc.VirtualAddress : 0); // BaseRelocationTable
WriteUInt32 (reloc != null ? reloc.VirtualSize : 0);
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory));
WriteUInt32 (28u);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // Copyright
WriteZeroDataDirectory (); // GlobalPtr
WriteZeroDataDirectory (); // TLSTable
WriteZeroDataDirectory (); // LoadConfigTable
WriteZeroDataDirectory (); // BoundImport
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT
WriteZeroDataDirectory (); // DelayImportDesc
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader
WriteZeroDataDirectory (); // Reserved
}
void WriteZeroDataDirectory ()
{
WriteUInt32 (0);
WriteUInt32 (0);
}
ushort GetSubSystem ()
{
switch (module.Kind) {
case ModuleKind.Console:
case ModuleKind.Dll:
case ModuleKind.NetModule:
return 0x3;
case ModuleKind.Windows:
return 0x2;
default:
throw new ArgumentOutOfRangeException ();
}
}
void WriteSectionHeaders ()
{
WriteSection (text, 0x60000020);
if (rsrc != null)
WriteSection (rsrc, 0x40000040);
if (reloc != null)
WriteSection (reloc, 0x42000040);
}
void WriteSection (Section section, uint characteristics)
{
var name = new byte [8];
var sect_name = section.Name;
for (int i = 0; i < sect_name.Length; i++)
name [i] = (byte) sect_name [i];
WriteBytes (name);
WriteUInt32 (section.VirtualSize);
WriteUInt32 (section.VirtualAddress);
WriteUInt32 (section.SizeOfRawData);
WriteUInt32 (section.PointerToRawData);
WriteUInt32 (0); // PointerToRelocations
WriteUInt32 (0); // PointerToLineNumbers
WriteUInt16 (0); // NumberOfRelocations
WriteUInt16 (0); // NumberOfLineNumbers
WriteUInt32 (characteristics);
}
void MoveTo (uint pointer)
{
BaseStream.Seek (pointer, SeekOrigin.Begin);
}
void MoveToRVA (Section section, RVA rva)
{
BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin);
}
void MoveToRVA (TextSegment segment)
{
MoveToRVA (text, text_map.GetRVA (segment));
}
void WriteRVA (RVA rva)
{
if (!pe64)
WriteUInt32 (rva);
else
WriteUInt64 (rva);
}
void PrepareSection (Section section)
{
MoveTo (section.PointerToRawData);
const int buffer_size = 4096;
if (section.SizeOfRawData <= buffer_size) {
Write (new byte [section.SizeOfRawData]);
MoveTo (section.PointerToRawData);
return;
}
var written = 0;
var buffer = new byte [buffer_size];
while (written != section.SizeOfRawData) {
var write_size = System.Math.Min((int) section.SizeOfRawData - written, buffer_size);
Write (buffer, 0, write_size);
written += write_size;
}
MoveTo (section.PointerToRawData);
}
void WriteText ()
{
PrepareSection (text);
// ImportAddressTable
if (has_reloc) {
WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable));
WriteRVA (0);
}
// CLIHeader
WriteUInt32 (0x48);
WriteUInt16 (2);
WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5));
WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader));
WriteUInt32 (GetMetadataLength ());
WriteUInt32 ((uint) module.Attributes);
WriteUInt32 (metadata.entry_point.ToUInt32 ());
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources));
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature));
WriteZeroDataDirectory (); // CodeManagerTable
WriteZeroDataDirectory (); // VTableFixups
WriteZeroDataDirectory (); // ExportAddressTableJumps
WriteZeroDataDirectory (); // ManagedNativeHeader
// Code
MoveToRVA (TextSegment.Code);
WriteBuffer (metadata.code);
// Resources
MoveToRVA (TextSegment.Resources);
WriteBuffer (metadata.resources);
// Data
if (metadata.data.length > 0) {
MoveToRVA (TextSegment.Data);
WriteBuffer (metadata.data);
}
// StrongNameSignature
// stays blank
// MetadataHeader
MoveToRVA (TextSegment.MetadataHeader);
WriteMetadataHeader ();
WriteMetadata ();
// DebugDirectory
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
MoveToRVA (TextSegment.DebugDirectory);
WriteDebugDirectory ();
}
if (!has_reloc)
return;
// ImportDirectory
MoveToRVA (TextSegment.ImportDirectory);
WriteImportDirectory ();
// StartupStub
MoveToRVA (TextSegment.StartupStub);
WriteStartupStub ();
}
uint GetMetadataLength ()
{
return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader);
}
void WriteMetadataHeader ()
{
WriteUInt32 (0x424a5342); // Signature
WriteUInt16 (1); // MajorVersion
WriteUInt16 (1); // MinorVersion
WriteUInt32 (0); // Reserved
var version = GetZeroTerminatedString (module.runtime_version);
WriteUInt32 ((uint) version.Length);
WriteBytes (version);
WriteUInt16 (0); // Flags
WriteUInt16 (GetStreamCount ());
uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader);
WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~");
WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings");
WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US");
WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID");
WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob");
}
ushort GetStreamCount ()
{
return (ushort) (
1 // #~
+ 1 // #Strings
+ (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US
+ 1 // GUID
+ (metadata.blob_heap.IsEmpty ? 0 : 1)); // #Blob
}
void WriteStreamHeader (ref uint offset, TextSegment heap, string name)
{
var length = (uint) text_map.GetLength (heap);
if (length == 0)
return;
WriteUInt32 (offset);
WriteUInt32 (length);
WriteBytes (GetZeroTerminatedString (name));
offset += length;
}
static int GetZeroTerminatedStringLength (string @string)
{
return (@string.Length + 1 + 3) & ~3;
}
static byte [] GetZeroTerminatedString (string @string)
{
return GetString (@string, GetZeroTerminatedStringLength (@string));
}
static byte [] GetSimpleString (string @string)
{
return GetString (@string, @string.Length);
}
static byte [] GetString (string @string, int length)
{
var bytes = new byte [length];
for (int i = 0; i < @string.Length; i++)
bytes [i] = (byte) @string [i];
return bytes;
}
void WriteMetadata ()
{
WriteHeap (TextSegment.TableHeap, metadata.table_heap);
WriteHeap (TextSegment.StringHeap, metadata.string_heap);
WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap);
WriteGuidHeap ();
WriteHeap (TextSegment.BlobHeap, metadata.blob_heap);
}
void WriteHeap (TextSegment heap, HeapBuffer buffer)
{
if (buffer.IsEmpty)
return;
MoveToRVA (heap);
WriteBuffer (buffer);
}
void WriteGuidHeap ()
{
MoveToRVA (TextSegment.GuidHeap);
WriteBytes (module.Mvid.ToByteArray ());
}
void WriteDebugDirectory ()
{
WriteInt32 (debug_directory.Characteristics);
WriteUInt32 (time_stamp);
WriteInt16 (debug_directory.MajorVersion);
WriteInt16 (debug_directory.MinorVersion);
WriteInt32 (debug_directory.Type);
WriteInt32 (debug_directory.SizeOfData);
WriteInt32 (debug_directory.AddressOfRawData);
WriteInt32 ((int) BaseStream.Position + 4);
WriteBytes (debug_data);
}
void WriteImportDirectory ()
{
WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable
WriteUInt32 (0); // DateTimeStamp
WriteUInt32 (0); // ForwarderChain
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14);
WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable));
Advance (20);
// ImportLookupTable
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable));
// ImportHintNameTable
MoveToRVA (TextSegment.ImportHintNameTable);
WriteUInt16 (0); // Hint
WriteBytes (GetRuntimeMain ());
WriteByte (0);
WriteBytes (GetSimpleString ("mscoree.dll"));
WriteUInt16 (0);
}
byte [] GetRuntimeMain ()
{
return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule
? GetSimpleString ("_CorDllMain")
: GetSimpleString ("_CorExeMain");
}
void WriteStartupStub ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt16 (0x25ff);
WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
return;
default:
throw new NotSupportedException ();
}
}
void WriteRsrc ()
{
PrepareSection (rsrc);
WriteBuffer (win32_resources);
}
void WriteReloc ()
{
PrepareSection (reloc);
var reloc_rva = text_map.GetRVA (TextSegment.StartupStub);
reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2;
var page_rva = reloc_rva & ~0xfffu;
WriteUInt32 (page_rva); // PageRVA
WriteUInt32 (0x000c); // Block Size
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt32 (0x3000 + reloc_rva - page_rva);
break;
default:
throw new NotSupportedException();
}
}
public void WriteImage ()
{
WriteDOSHeader ();
WritePEFileHeader ();
WriteOptionalHeaders ();
WriteSectionHeaders ();
WriteText ();
if (rsrc != null)
WriteRsrc ();
if (reloc != null)
WriteReloc ();
}
TextMap BuildTextMap ()
{
var map = metadata.text_map;
map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16);
map.AddMap (TextSegment.Resources, metadata.resources.length, 8);
map.AddMap (TextSegment.Data, metadata.data.length, 4);
if (metadata.data.length > 0)
metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data));
map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4);
map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength (module.RuntimeVersion));
map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4);
map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4);
map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4);
map.AddMap (TextSegment.GuidHeap, 16);
map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4);
int debug_dir_len = 0;
if (!debug_data.IsNullOrEmpty ()) {
const int debug_dir_header_len = 28;
debug_directory.AddressOfRawData = (int) map.GetNextRVA (TextSegment.BlobHeap) + debug_dir_header_len;
debug_dir_len = debug_data.Length + debug_dir_header_len;
}
map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4);
if (!has_reloc) {
var start = map.GetNextRVA (TextSegment.DebugDirectory);
map.AddMap (TextSegment.ImportDirectory, new Range (start, 0));
map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0));
map.AddMap (TextSegment.StartupStub, new Range (start, 0));
return map;
}
RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory);
RVA import_hnt_rva = import_dir_rva + 48u;
import_hnt_rva = (import_hnt_rva + 15u) & ~15u;
uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u;
RVA startup_stub_rva = import_dir_rva + import_dir_len;
startup_stub_rva = module.Architecture == TargetArchitecture.IA64
? (startup_stub_rva + 15u) & ~15u
: 2 + ((startup_stub_rva + 3u) & ~3u);
map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len));
map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0));
map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ()));
return map;
}
uint GetStartupStubLength ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 6;
default:
throw new NotSupportedException ();
}
}
int GetMetadataHeaderLength (string runtimeVersion)
{
return
// MetadataHeader
20 + GetZeroTerminatedStringLength (runtimeVersion)
// #~ header
+ 12
// #Strings header
+ 20
// #US header
+ (metadata.user_string_heap.IsEmpty ? 0 : 12)
// #GUID header
+ 16
// #Blob header
+ (metadata.blob_heap.IsEmpty ? 0 : 16);
}
int GetStrongNameLength ()
{
if (module.Assembly == null)
return 0;
var public_key = module.Assembly.Name.PublicKey;
if (public_key.IsNullOrEmpty ())
return 0;
// in fx 2.0 the key may be from 384 to 16384 bits
// so we must calculate the signature size based on
// the size of the public key (minus the 32 byte header)
int size = public_key.Length;
if (size > 32)
return size - 32;
// note: size == 16 for the ECMA "key" which is replaced
// by the runtime with a 1024 bits key (128 bytes)
return 128; // default strongname signature size
}
public DataDirectory GetStrongNameSignatureDirectory ()
{
return text_map.GetDataDirectory (TextSegment.StrongNameSignature);
}
public uint GetHeaderSize ()
{
return pe_header_size + SizeOfOptionalHeader () + (sections * section_header_size);
}
void PatchWin32Resources (ByteBuffer resources)
{
PatchResourceDirectoryTable (resources);
}
void PatchResourceDirectoryTable (ByteBuffer resources)
{
resources.Advance (12);
var entries = resources.ReadUInt16 () + resources.ReadUInt16 ();
for (int i = 0; i < entries; i++)
PatchResourceDirectoryEntry (resources);
}
void PatchResourceDirectoryEntry (ByteBuffer resources)
{
resources.Advance (4);
var child = resources.ReadUInt32 ();
var position = resources.position;
resources.position = (int) child & 0x7fffffff;
if ((child & 0x80000000) != 0)
PatchResourceDirectoryTable (resources);
else
PatchResourceDataEntry (resources);
resources.position = position;
}
void PatchResourceDataEntry (ByteBuffer resources)
{
var old_rsrc = GetImageResourceSection ();
var rva = resources.ReadUInt32 ();
resources.position -= 4;
resources.WriteUInt32 (rva - old_rsrc.VirtualAddress + rsrc.VirtualAddress);
}
}
}
#endif
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C03_SubContinentColl (editable child list).<br/>
/// This is a generated base class of <see cref="C03_SubContinentColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="C02_Continent"/> editable root object.<br/>
/// The items of the collection are <see cref="C04_SubContinent"/> objects.
/// </remarks>
[Serializable]
public partial class C03_SubContinentColl : BusinessListBase<C03_SubContinentColl, C04_SubContinent>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="C04_SubContinent"/> item from the collection.
/// </summary>
/// <param name="subContinent_ID">The SubContinent_ID of the item to be removed.</param>
public void Remove(int subContinent_ID)
{
foreach (var c04_SubContinent in this)
{
if (c04_SubContinent.SubContinent_ID == subContinent_ID)
{
Remove(c04_SubContinent);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="C04_SubContinent"/> item is in the collection.
/// </summary>
/// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param>
/// <returns><c>true</c> if the C04_SubContinent is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int subContinent_ID)
{
foreach (var c04_SubContinent in this)
{
if (c04_SubContinent.SubContinent_ID == subContinent_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="C04_SubContinent"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param>
/// <returns><c>true</c> if the C04_SubContinent is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int subContinent_ID)
{
foreach (var c04_SubContinent in DeletedList)
{
if (c04_SubContinent.SubContinent_ID == subContinent_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="C04_SubContinent"/> item of the <see cref="C03_SubContinentColl"/> collection, based on a given SubContinent_ID.
/// </summary>
/// <param name="subContinent_ID">The SubContinent_ID.</param>
/// <returns>A <see cref="C04_SubContinent"/> object.</returns>
public C04_SubContinent FindC04_SubContinentBySubContinent_ID(int subContinent_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].SubContinent_ID.Equals(subContinent_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C03_SubContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="C03_SubContinentColl"/> collection.</returns>
internal static C03_SubContinentColl NewC03_SubContinentColl()
{
return DataPortal.CreateChild<C03_SubContinentColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="C03_SubContinentColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_Continent_ID">The Parent_Continent_ID parameter of the C03_SubContinentColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="C03_SubContinentColl"/> collection.</returns>
internal static C03_SubContinentColl GetC03_SubContinentColl(int parent_Continent_ID)
{
return DataPortal.FetchChild<C03_SubContinentColl>(parent_Continent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C03_SubContinentColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C03_SubContinentColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="C03_SubContinentColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_Continent_ID">The Parent Continent ID.</param>
protected void Child_Fetch(int parent_Continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetC03_SubContinentColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Continent_ID", parent_Continent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_Continent_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="C03_SubContinentColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(C04_SubContinent.GetC04_SubContinent(dr));
}
RaiseListChangedEvents = rlce;
}
#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
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
using System.Composition;
using Microsoft.VisualStudio.Composition;
namespace Microsoft.CodeAnalysis.UnitTests.Workspaces
{
public partial class WorkspaceTests
{
[Shared]
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.Workspace)]
private class WorkspaceWaiter : AsynchronousOperationListener
{
internal WorkspaceWaiter()
{
}
}
private static Lazy<ExportProvider> s_exportProvider = new Lazy<ExportProvider>(CreateExportProvider);
private static ExportProvider CreateExportProvider()
{
var catalog = MinimalTestExportProvider.WithPart(
TestExportProvider.CreateAssemblyCatalogWithCSharpAndVisualBasic(),
typeof(WorkspaceWaiter));
return MinimalTestExportProvider.CreateExportProvider(catalog);
}
private TestWorkspace CreateWorkspace(bool disablePartialSolutions = true)
{
return new TestWorkspace(s_exportProvider.Value, disablePartialSolutions: disablePartialSolutions);
}
private static async Task WaitForWorkspaceOperationsToComplete(TestWorkspace workspace)
{
var workspaceWaiter = workspace.ExportProvider
.GetExports<IAsynchronousOperationListener, FeatureMetadata>()
.First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
await workspaceWaiter.CreateWaitTask();
}
[Fact]
public async Task TestEmptySolutionUpdateDoesNotFireEvents()
{
using (var workspace = CreateWorkspace())
{
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
// wait for all previous operations to complete
await WaitForWorkspaceOperationsToComplete(workspace);
var solution = workspace.CurrentSolution;
bool workspaceChanged = false;
workspace.WorkspaceChanged += (s, e) => workspaceChanged = true;
// make an 'empty' update by claiming something changed, but its the same as before
workspace.OnParseOptionsChanged(project.Id, project.ParseOptions);
// wait for any new outstanding operations to complete (there shouldn't be any)
await WaitForWorkspaceOperationsToComplete(workspace);
// same solution instance == nothing changed
Assert.Equal(solution, workspace.CurrentSolution);
// no event was fired because nothing was changed
Assert.False(workspaceChanged);
}
}
[Fact]
public void TestAddProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
solution = workspace.CurrentSolution;
Assert.Equal(1, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveExistingProject1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
workspace.OnProjectRemoved(project.Id);
solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveExistingProject2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
solution = workspace.CurrentSolution;
workspace.OnProjectRemoved(project.Id);
solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveNonAddedProject1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project.Id));
}
}
[Fact]
public void TestRemoveNonAddedProject2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project2.Id));
}
}
[Fact]
public async Task TestChangeOptions1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(
@"#if FOO
class C { }
#else
class D { }
#endif");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
await VerifyRootTypeNameAsync(workspace, "D");
workspace.OnParseOptionsChanged(document.Id.ProjectId,
new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" }));
await VerifyRootTypeNameAsync(workspace, "C");
}
}
[Fact]
public async Task TestChangeOptions2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(
@"#if FOO
class C { }
#else
class D { }
#endif");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
await VerifyRootTypeNameAsync(workspace, "D");
workspace.OnParseOptionsChanged(document.Id.ProjectId,
new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" }));
await VerifyRootTypeNameAsync(workspace, "C");
workspace.OnDocumentClosed(document.Id);
}
}
[Fact]
public async void TestAddedSubmissionParseTreeHasEmptyFilePath()
{
using (var workspace = CreateWorkspace())
{
var document1 = new TestHostDocument("var x = 1;", displayName: "Sub1", sourceCodeKind: SourceCodeKind.Script);
var project1 = new TestHostProject(workspace, document1, name: "Submission");
var document2 = new TestHostDocument("var x = 2;", displayName: "Sub2", sourceCodeKind: SourceCodeKind.Script, filePath: "a.csx");
var project2 = new TestHostProject(workspace, document2, name: "Script");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.TryApplyChanges(workspace.CurrentSolution);
// Check that a parse tree for a submission has an empty file path.
SyntaxTree tree1 = await workspace.CurrentSolution
.GetProjectState(project1.Id)
.GetDocumentState(document1.Id)
.GetSyntaxTreeAsync(CancellationToken.None);
Assert.Equal("", tree1.FilePath);
// Check that a parse tree for a script does not have an empty file path.
SyntaxTree tree2 = await workspace.CurrentSolution
.GetProjectState(project2.Id)
.GetDocumentState(document2.Id)
.GetSyntaxTreeAsync(CancellationToken.None);
Assert.Equal("a.csx", tree2.FilePath);
}
}
private static async Task VerifyRootTypeNameAsync(TestWorkspace workspaceSnapshotBuilder, string typeName)
{
var currentSnapshot = workspaceSnapshotBuilder.CurrentSolution;
var type = await GetRootTypeDeclarationAsync(currentSnapshot);
Assert.Equal(type.Identifier.ValueText, typeName);
}
private static async Task<TypeDeclarationSyntax> GetRootTypeDeclarationAsync(Solution currentSnapshot)
{
var tree = await currentSnapshot.Projects.First().Documents.First().GetSyntaxTreeAsync();
var root = (CompilationUnitSyntax)tree.GetRoot();
var type = (TypeDeclarationSyntax)root.Members[0];
return type;
}
[Fact]
public void TestAddP2PReferenceFails()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)));
}
}
[Fact]
public void TestAddP2PReference1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var reference = new ProjectReference(project2.Id);
workspace.OnProjectReferenceAdded(project1.Id, reference);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
Assert.True(snapshot.GetProject(id1).ProjectReferences.Contains(reference), "ProjectReferences did not contain project2");
}
}
[Fact]
public void TestAddP2PReferenceTwice()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)));
}
}
[Fact]
public void TestRemoveP2PReference1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
workspace.OnProjectReferenceRemoved(project1.Id, new ProjectReference(project2.Id));
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
Assert.Equal(0, snapshot.GetProject(id1).ProjectReferences.Count());
}
}
[Fact]
public void TestAddP2PReferenceCircularity()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project2.Id, new ProjectReference(project1.Id)));
}
}
[Fact]
public void TestRemoveProjectWithOpenedDocuments()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OnProjectRemoved(project1.Id);
Assert.False(workspace.IsDocumentOpen(document.Id));
Assert.Empty(workspace.CurrentSolution.Projects);
}
}
[Fact]
public void TestRemoveProjectWithClosedDocuments()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public void TestRemoveOpenedDocument()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
Assert.Throws<ArgumentException>(() => workspace.OnDocumentRemoved(document.Id));
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public async Task TestGetCompilation()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(@"class C { }");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
await VerifyRootTypeNameAsync(workspace, "C");
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var compilation = await snapshot.GetProject(id1).GetCompilationAsync();
var classC = compilation.SourceModule.GlobalNamespace.GetMembers("C").Single();
}
}
[Fact]
public async Task TestGetCompilationOnDependentProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument(@"class D : C { }");
var project2 = new TestHostProject(workspace, document2, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = await snapshot.GetProject(id2).GetCompilationAsync();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
}
}
[Fact]
public async Task TestGetCompilationOnCrossLanguageDependentProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = await snapshot.GetProject(id2).GetCompilationAsync();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
}
}
[Fact]
public async Task TestGetCompilationOnCrossLanguageDependentProjectChanged()
{
using (var workspace = CreateWorkspace())
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = await solutionY.GetProject(id2).GetCompilationAsync();
var errors = compilation2.GetDiagnostics();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
Assert.NotEqual(TypeKind.Error, classC.TypeKind);
// change the class name in document1
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
var buffer1 = document1.GetTextBuffer();
// change C to X
buffer1.Replace(new Span(13, 1), "X");
// this solution should have the change
var solutionZ = workspace.CurrentSolution;
var docZ = solutionZ.GetDocument(document1.Id);
var docZText = await docZ.GetTextAsync();
var compilation2Z = await solutionZ.GetProject(id2).GetCompilationAsync();
var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCz = classDz.BaseType;
Assert.Equal(TypeKind.Error, classCz.TypeKind);
}
}
[WpfFact]
public async Task TestDependentSemanticVersionChangesWhenNotOriginallyAccessed()
{
using (var workspace = CreateWorkspace(disablePartialSolutions: false))
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2y = await solutionY.GetProject(id2).GetCompilationAsync();
var errors = compilation2y.GetDiagnostics();
var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCy = classDy.BaseType;
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
// change C to X
var buffer1 = document1.GetTextBuffer();
buffer1.Replace(new Span(13, 1), "X");
for (int iter = 0; iter < 10; iter++)
{
WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle);
Thread.Sleep(1000);
// the current solution should eventually have the change
var cs = workspace.CurrentSolution;
var doc1Z = cs.GetDocument(document1.Id);
var hasX = (await doc1Z.GetTextAsync()).ToString().Contains("X");
if (hasX)
{
var newVersion = await cs.GetProject(project1.Id).GetDependentSemanticVersionAsync();
var newVersionX = await doc1Z.Project.GetDependentSemanticVersionAsync();
Assert.NotEqual(VersionStamp.Default, newVersion);
Assert.Equal(newVersion, newVersionX);
break;
}
}
}
}
[WpfFact]
public async Task TestGetCompilationOnCrossLanguageDependentProjectChangedInProgress()
{
using (var workspace = CreateWorkspace(disablePartialSolutions: false))
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2y = await solutionY.GetProject(id2).GetCompilationAsync();
var errors = compilation2y.GetDiagnostics();
var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCy = classDy.BaseType;
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
// change C to X
var buffer1 = document1.GetTextBuffer();
buffer1.Replace(new Span(13, 1), "X");
var foundTheError = false;
for (int iter = 0; iter < 10; iter++)
{
WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle);
Thread.Sleep(1000);
// the current solution should eventually have the change
var cs = workspace.CurrentSolution;
var doc1Z = cs.GetDocument(document1.Id);
var hasX = (await doc1Z.GetTextAsync()).ToString().Contains("X");
if (hasX)
{
var doc2Z = cs.GetDocument(document2.Id);
var partialDoc2Z = await doc2Z.WithFrozenPartialSemanticsAsync(CancellationToken.None);
var compilation2Z = await partialDoc2Z.Project.GetCompilationAsync();
var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCz = classDz.BaseType;
if (classCz.TypeKind == TypeKind.Error)
{
foundTheError = true;
break;
}
}
}
Assert.True(foundTheError, "Did not find error");
}
}
[Fact]
public async Task TestOpenAndChangeDocument()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
buffer.Insert(0, "class C {}");
solution = workspace.CurrentSolution;
var doc = solution.Projects.Single().Documents.First();
var syntaxTree = await doc.GetSyntaxTreeAsync(CancellationToken.None);
Assert.True(syntaxTree.GetRoot().Width() > 0, "syntaxTree.GetRoot().Width should be > 0");
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public async Task TestApplyChangesWithDocumentTextUpdated()
{
using (var workspace = CreateWorkspace())
{
var startText = "public class C { }";
var newText = "public class D { }";
var document = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
// prove the document has the correct text
Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString());
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.WithDocumentText(document.Id, SourceText.From(newText));
// prove that current document text is unchanged
Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString());
// prove buffer is unchanged too
Assert.Equal(startText, buffer.CurrentSnapshot.GetText());
workspace.TryApplyChanges(newSolution);
// new text should have been pushed into buffer
Assert.Equal(newText, buffer.CurrentSnapshot.GetText());
}
}
[Fact]
public void TestApplyChangesWithDocumentAdded()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var doc2Text = "public class D { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.AddDocument(DocumentId.CreateNewId(project1.Id), "Doc2", SourceText.From(doc2Text));
workspace.TryApplyChanges(newSolution);
// new document should have been added.
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
}
}
[Fact]
public void TestApplyChangesWithDocumentRemoved()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.RemoveDocument(document.Id);
workspace.TryApplyChanges(newSolution);
// document should have been removed
Assert.Equal(0, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
}
}
[Fact]
public async Task TestDocumentEvents()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
var longEventTimeout = TimeSpan.FromMinutes(5);
var shortEventTimeout = TimeSpan.FromSeconds(5);
workspace.AddTestProject(project1);
// Creating two waiters that will allow us to know for certain if the events have fired.
using (var closeWaiter = new EventWaiter())
using (var openWaiter = new EventWaiter())
{
// Wrapping event handlers so they can notify us on being called.
var documentOpenedEventHandler = openWaiter.Wrap<DocumentEventArgs>(
(sender, args) => Assert.True(args.Document.Id == document.Id,
"The document given to the 'DocumentOpened' event handler did not have the same id as the one created for the test."));
var documentClosedEventHandler = closeWaiter.Wrap<DocumentEventArgs>(
(sender, args) => Assert.True(args.Document.Id == document.Id,
"The document given to the 'DocumentClosed' event handler did not have the same id as the one created for the test."));
workspace.DocumentOpened += documentOpenedEventHandler;
workspace.DocumentClosed += documentClosedEventHandler;
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
// Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified.
await WaitForWorkspaceOperationsToComplete(workspace);
// Wait to receive signal that events have fired.
Assert.True(openWaiter.WaitForEventToFire(longEventTimeout),
string.Format("event 'DocumentOpened' was not fired within {0} minutes.",
longEventTimeout.Minutes));
Assert.True(closeWaiter.WaitForEventToFire(longEventTimeout),
string.Format("event 'DocumentClosed' was not fired within {0} minutes.",
longEventTimeout.Minutes));
workspace.DocumentOpened -= documentOpenedEventHandler;
workspace.DocumentClosed -= documentClosedEventHandler;
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
// Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified.
await WaitForWorkspaceOperationsToComplete(workspace);
// Verifying that an event has not been called is difficult to prove.
// All events should have already been called so we wait 5 seconds and then assume the event handler was removed correctly.
Assert.False(openWaiter.WaitForEventToFire(shortEventTimeout),
string.Format("event handler 'DocumentOpened' was called within {0} seconds though it was removed from the list.",
shortEventTimeout.Seconds));
Assert.False(closeWaiter.WaitForEventToFire(shortEventTimeout),
string.Format("event handler 'DocumentClosed' was called within {0} seconds though it was removed from the list.",
shortEventTimeout.Seconds));
}
}
}
[Fact]
public async Task TestAdditionalFile_Properties()
{
using (var workspace = CreateWorkspace())
{
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument("some text");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
Assert.Equal(1, project.Documents.Count());
Assert.Equal(1, project.AdditionalDocuments.Count());
Assert.Equal(1, project.AdditionalDocumentIds.Count);
var doc = project.GetDocument(additionalDoc.Id);
Assert.Null(doc);
var additionalDocument = project.GetAdditionalDocument(additionalDoc.Id);
Assert.Equal("some text", (await additionalDocument.GetTextAsync()).ToString());
}
}
[Fact]
public async Task TestAdditionalFile_DocumentChanged()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var newText = @"<setting value = ""foo1""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var buffer = additionalDoc.GetTextBuffer();
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
var project = workspace.CurrentSolution.Projects.Single();
var oldVersion = await project.GetSemanticVersionAsync();
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.WithAdditionalDocumentText(additionalDoc.Id, SourceText.From(newText));
workspace.TryApplyChanges(newSolution);
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
// new text should have been pushed into buffer
Assert.Equal(newText, buffer.CurrentSnapshot.GetText());
// Text changes are considered top level changes and they change the project's semantic version.
Assert.Equal(await doc.GetTextVersionAsync(), await doc.GetTopLevelChangeTextVersionAsync());
Assert.NotEqual(oldVersion, await doc.Project.GetSemanticVersionAsync());
}
}
[Fact]
public async Task TestAdditionalFile_OpenClose()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var buffer = additionalDoc.GetTextBuffer();
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
var text = await doc.GetTextAsync(CancellationToken.None);
var version = await doc.GetTextVersionAsync(CancellationToken.None);
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
// We don't have a GetOpenAdditionalDocumentIds since we don't need it. But make sure additional documents
// don't creep into OpenDocumentIds (Bug: 1087470)
Assert.Empty(workspace.GetOpenDocumentIds());
workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version)));
// Reopen and close to make sure we are not leaking anything.
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version)));
Assert.Empty(workspace.GetOpenDocumentIds());
}
}
[Fact]
public void TestAdditionalFile_AddRemove()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText, "original.config");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
// fork the solution to introduce a change.
var newDocId = DocumentId.CreateNewId(project.Id);
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.AddAdditionalDocument(newDocId, "app.config", "text");
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
workspace.TryApplyChanges(newSolution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
// Now remove the newly added document
oldSolution = workspace.CurrentSolution;
newSolution = oldSolution.RemoveAdditionalDocument(newDocId);
workspace.TryApplyChanges(newSolution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
[Fact]
public void TestAdditionalFile_AddRemove_FromProject()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText, "original.config");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
// fork the solution to introduce a change.
var doc = project.AddAdditionalDocument("app.config", "text");
workspace.TryApplyChanges(doc.Project.Solution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
// Now remove the newly added document
project = workspace.CurrentSolution.Projects.Single();
workspace.TryApplyChanges(project.RemoveAdditionalDocument(doc.Id).Solution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
}
}
| |
/*
* 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.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
{
/// <summary>
/// Manage asset transactions for a single agent.
/// </summary>
public class AgentAssetTransactions
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Fields
private bool m_dumpAssetsToFile;
public AssetTransactionModule Manager;
public UUID UserID;
public Dictionary<UUID, AssetXferUploader> XferUploaders = new Dictionary<UUID, AssetXferUploader>();
// Methods
public AgentAssetTransactions(UUID agentID, AssetTransactionModule manager, bool dumpAssetsToFile)
{
UserID = agentID;
Manager = manager;
m_dumpAssetsToFile = dumpAssetsToFile;
}
public AssetXferUploader RequestXferUploader(UUID transactionID)
{
if (!XferUploaders.ContainsKey(transactionID))
{
AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile);
lock (XferUploaders)
{
XferUploaders.Add(transactionID, uploader);
}
return uploader;
}
return null;
}
public void HandleXfer(ulong xferID, uint packetID, byte[] data)
{
lock (XferUploaders)
{
foreach (AssetXferUploader uploader in XferUploaders.Values)
{
if (uploader.XferID == xferID)
{
uploader.HandleXferPacket(xferID, packetID, data);
break;
}
}
}
}
public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
if (XferUploaders.ContainsKey(transactionID))
{
XferUploaders[transactionID].RequestCreateInventoryItem(remoteClient, transactionID, folderID,
callbackID, description, name, invType, type,
wearableType, nextOwnerMask);
}
}
/// <summary>
/// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed.
/// </summary>
/// <param name="transactionID"></param>
/// <returns>The asset if the upload has completed, null if it has not.</returns>
public AssetBase GetTransactionAsset(UUID transactionID)
{
if (XferUploaders.ContainsKey(transactionID))
{
AssetXferUploader uploader = XferUploaders[transactionID];
AssetBase asset = uploader.GetAssetData();
lock (XferUploaders)
{
XferUploaders.Remove(transactionID);
}
return asset;
}
return null;
}
//private void CreateItemFromUpload(AssetBase asset, IClientAPI ourClient, UUID inventoryFolderID, uint nextPerms, uint wearableType)
//{
// Manager.MyScene.CommsManager.AssetCache.AddAsset(asset);
// CachedUserInfo userInfo = Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails(
// ourClient.AgentId);
// if (userInfo != null)
// {
// InventoryItemBase item = new InventoryItemBase();
// item.Owner = ourClient.AgentId;
// item.Creator = ourClient.AgentId;
// item.ID = UUID.Random();
// item.AssetID = asset.FullID;
// item.Description = asset.Description;
// item.Name = asset.Name;
// item.AssetType = asset.Type;
// item.InvType = asset.Type;
// item.Folder = inventoryFolderID;
// item.BasePermissions = 0x7fffffff;
// item.CurrentPermissions = 0x7fffffff;
// item.EveryOnePermissions = 0;
// item.NextPermissions = nextPerms;
// item.Flags = wearableType;
// item.CreationDate = Util.UnixTimeSinceEpoch();
// userInfo.AddItem(item);
// ourClient.SendInventoryItemCreateUpdate(item);
// }
// else
// {
// m_log.ErrorFormat(
// "[ASSET TRANSACTIONS]: Could not find user {0} for inventory item creation",
// ourClient.AgentId);
// }
//}
public void RequestUpdateTaskInventoryItem(
IClientAPI remoteClient, SceneObjectPart part, UUID transactionID, TaskInventoryItem item)
{
if (XferUploaders.ContainsKey(transactionID))
{
AssetBase asset = XferUploaders[transactionID].GetAssetData();
if (asset != null)
{
m_log.DebugFormat(
"[ASSET TRANSACTIONS]: Updating task item {0} in {1} with asset in transaction {2}",
item.Name, part.Name, transactionID);
asset.Name = item.Name;
asset.Description = item.Description;
asset.Type = (sbyte)item.Type;
item.AssetID = asset.FullID;
Manager.MyScene.AssetService.Store(asset);
if (part.Inventory.UpdateInventoryItem(item))
part.GetProperties(remoteClient);
}
}
}
public void RequestUpdateInventoryItem(IClientAPI remoteClient, UUID transactionID,
InventoryItemBase item)
{
if (XferUploaders.ContainsKey(transactionID))
{
UUID assetID = UUID.Combine(transactionID, remoteClient.SecureSessionId);
AssetBase asset = Manager.MyScene.AssetService.Get(assetID.ToString());
if (asset == null)
{
asset = GetTransactionAsset(transactionID);
}
if (asset != null && asset.FullID == assetID)
{
// Assets never get updated, new ones get created
asset.FullID = UUID.Random();
asset.Name = item.Name;
asset.Description = item.Description;
asset.Type = (sbyte)item.AssetType;
item.AssetID = asset.FullID;
Manager.MyScene.AssetService.Store(asset);
}
IInventoryService invService = Manager.MyScene.InventoryService;
Manager.MyScene.EventManager.TriggerOnInventoryItemUpdated(item);
invService.UpdateItem(item);
}
}
}
}
| |
using System;
/// <summary>
/// Convert.ToDouble(String)
/// </summary>
public class ConvertToDouble13
{
public static int Main()
{
ConvertToDouble13 testObj = new ConvertToDouble13();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToDouble(String)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1();
retVal = NegTest2();
retVal = NegTest3();
retVal = NegTest4();
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string c_TEST_DESC = "PosTest1: Verfify value is a vaild string ... ";
string c_TEST_ID = "P001";
string actualValue = "62356.123";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (Double.Parse(actualValue) != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string c_TEST_DESC = "PosTest2: Verfify value is a null reference... ";
string c_TEST_ID = "P002";
String actualValue = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (0 != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is 0";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string c_TEST_DESC = "PosTest3: Verfify value is a string end with a radix point... ";
string c_TEST_ID = "P003";
String actualValue = "7923.";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
Double realValue = Double.Parse(actualValue);
if (realValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is"+ realValue;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string c_TEST_DESC = "PosTest4: Verfify value is a string started with a radix point... ";
string c_TEST_ID = "P003";
String actualValue= ".7923";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
Double realValue = Double.Parse(actualValue);
if (realValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + realValue;
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Value represents a number greater than Double.MaxValue ";
const string c_TEST_ID = "N001";
string actualValue = "2.7976931348623157E+308";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToDouble(actualValue);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "OverflowException is not thrown as expected.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: Value represents a number less than Double.MaxValue ";
const string c_TEST_ID = "N002";
string actualValue = "-1.7976931348623159E+308";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToDouble(actualValue);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "OverflowException is not thrown as expected.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: value is a string cantains invalid chars ";
const string c_TEST_ID = "N003";
string actualValue = "3222.79asd";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToDouble(actualValue);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "FormatException is not thrown as expected.");
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: value is a empty string ";
const string c_TEST_ID = "N004";
string actualValue = "";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToDouble(actualValue);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "FormatException is not thrown as expected.");
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// ReSharper disable RedundantArgumentDefaultValue
namespace Gu.State.Tests
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NUnit.Framework;
using static SynchronizeTypes;
public static partial class SynchronizeTests
{
public static class ObservableCollectionOfComplexTypes
{
[Test]
public static void CreateAndDisposeStructural()
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType>();
using (Synchronize.PropertyValues(source, target, ReferenceHandling.Structural))
{
var expected = new[] { new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
source[0].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
}
source.Add(new ComplexType("c", 3));
CollectionAssert.AreEqual(new[] { new ComplexType("a", 2), new ComplexType("b", 2), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(new[] { new ComplexType("a", 2), new ComplexType("b", 2) }, target, ComplexType.Comparer);
source[0].Value++;
CollectionAssert.AreEqual(new[] { new ComplexType("a", 3), new ComplexType("b", 2), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(new[] { new ComplexType("a", 2), new ComplexType("b", 2) }, target, ComplexType.Comparer);
source[1].Value++;
CollectionAssert.AreEqual(new[] { new ComplexType("a", 3), new ComplexType("b", 3), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(new[] { new ComplexType("a", 2), new ComplexType("b", 2) }, target, ComplexType.Comparer);
}
[Test]
public static void CreateAndDisposeStructural1()
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType>();
using (Synchronize.PropertyValues(source, target, ReferenceHandling.Structural))
{
var expected = new[] { new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
source[0].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
source.Add(source[0]);
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 2), new ComplexType("a", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
source[0].Value++;
expected = new[] { new ComplexType("a", 3), new ComplexType("b", 2), new ComplexType("a", 3) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
}
source.Add(new ComplexType("c", 3));
CollectionAssert.AreEqual(new[] { new ComplexType("a", 3), new ComplexType("b", 2), new ComplexType("a", 3), new ComplexType("c", 3) }, source, ComplexType.Comparer);
var expectedTargets = new[] { new ComplexType("a", 3), new ComplexType("b", 2), new ComplexType("a", 3) };
CollectionAssert.AreEqual(expectedTargets, target, ComplexType.Comparer);
source[0].Value++;
CollectionAssert.AreEqual(new[] { new ComplexType("a", 4), new ComplexType("b", 2), new ComplexType("a", 4), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expectedTargets, target, ComplexType.Comparer);
source[1].Value++;
CollectionAssert.AreEqual(new[] { new ComplexType("a", 4), new ComplexType("b", 3), new ComplexType("a", 4), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expectedTargets, target, ComplexType.Comparer);
source[2].Value++;
CollectionAssert.AreEqual(new[] { new ComplexType("a", 5), new ComplexType("b", 3), new ComplexType("a", 5), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expectedTargets, target, ComplexType.Comparer);
target[0].Value++;
target.Add(new ComplexType("c", 4));
expectedTargets = new[] { new ComplexType("a", 4), new ComplexType("b", 2), new ComplexType("a", 3), new ComplexType("c", 4) };
CollectionAssert.AreEqual(expectedTargets, target, ComplexType.Comparer);
}
[Test]
public static void CreateAndDisposeReference()
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType>();
using (Synchronize.PropertyValues(source, target, ReferenceHandling.References))
{
var expected = new[] { new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreSame(source[0], target[0]);
Assert.AreSame(source[1], target[1]);
source[0].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreSame(source[0], target[0]);
Assert.AreSame(source[1], target[1]);
}
source.Add(new ComplexType("c", 3));
CollectionAssert.AreEqual(new[] { new ComplexType("a", 2), new ComplexType("b", 2), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(new[] { new ComplexType("a", 2), new ComplexType("b", 2) }, target, ComplexType.Comparer);
source[0].Value++;
CollectionAssert.AreEqual(new[] { new ComplexType("a", 3), new ComplexType("b", 2), new ComplexType("c", 3) }, source, ComplexType.Comparer);
CollectionAssert.AreEqual(new[] { new ComplexType("a", 3), new ComplexType("b", 2) }, target, ComplexType.Comparer);
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void Add(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType>();
var target = new ObservableCollection<ComplexType>();
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.Add(new ComplexType("a", 1));
var expected = new[] { new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void AddThenUpdate1(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType>();
var target = new ObservableCollection<ComplexType>();
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.Add(new ComplexType("a", 1));
var expected = new[] { new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[0].Value++;
expected = new[] { new ComplexType("a", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void AddThenUpdate2(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.Add(new ComplexType("c", 3));
var expected = new[] { new ComplexType("a", 1), new ComplexType("b", 2), new ComplexType("c", 3) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[0].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 2), new ComplexType("c", 3) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[1].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 3), new ComplexType("c", 3) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[2].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("b", 3), new ComplexType("c", 4) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void Remove(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.RemoveAt(1);
var expected = new[] { new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source.RemoveAt(0);
CollectionAssert.IsEmpty(source);
CollectionAssert.IsEmpty(target);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void Insert(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.Insert(1, new ComplexType("c", 3));
var expected = new[] { new ComplexType("a", 1), new ComplexType("c", 3), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[0].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("c", 3), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[1].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("c", 4), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[2].Value++;
expected = new[] { new ComplexType("a", 2), new ComplexType("c", 4), new ComplexType("b", 3) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void Move(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.Move(1, 0);
var expected = new[] { new ComplexType("b", 2), new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source.Move(0, 1);
expected = new[] { new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void MoveThenUpdate(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2), new ComplexType("c", 3) };
var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2), new ComplexType("c", 3) };
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source.Move(2, 0);
var expected = new[] { new ComplexType("c", 3), new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[0].Value++;
expected = new[] { new ComplexType("c", 4), new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[1].Value++;
expected = new[] { new ComplexType("c", 4), new ComplexType("a", 2), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[2].Value++;
expected = new[] { new ComplexType("c", 4), new ComplexType("a", 2), new ComplexType("b", 3) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public static void Replace(ReferenceHandling referenceHandling)
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
using (Synchronize.PropertyValues(source, target, referenceHandling))
{
source[0] = new ComplexType("c", 3);
var expected = new[] { new ComplexType("c", 3), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
source[1] = new ComplexType("d", 4);
expected = new[] { new ComplexType("c", 3), new ComplexType("d", 4) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
}
}
[Test]
public static void Synchronizes()
{
var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
var target = new ObservableCollection<ComplexType>();
using (Synchronize.PropertyValues(source, target, ReferenceHandling.Structural))
{
var expected = new List<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) };
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
source.Add(new ComplexType("c", 3));
expected.Add(new ComplexType("c", 3));
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
Assert.AreNotSame(source[2], target[2]);
source[2].Name = "changed";
expected[2].Name = "changed";
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
Assert.AreNotSame(source[2], target[2]);
source.RemoveAt(1);
expected.RemoveAt(1);
CollectionAssert.AreEqual(expected, source, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target, ComplexType.Comparer);
Assert.AreNotSame(source[0], target[0]);
Assert.AreNotSame(source[1], target[1]);
source.Clear();
Assert.AreEqual(0, source.Count);
Assert.AreEqual(0, target.Count);
}
}
}
}
}
| |
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 WebApi.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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable queue.
/// </summary>
/// <typeparam name="T">The type of elements stored in the queue.</typeparam>
[DebuggerDisplay("IsEmpty = {IsEmpty}")]
[DebuggerTypeProxy(typeof(ImmutableQueueDebuggerProxy<>))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")]
public sealed class ImmutableQueue<T> : IImmutableQueue<T>
{
/// <summary>
/// The singleton empty queue.
/// </summary>
/// <remarks>
/// Additional instances representing the empty queue may exist on deserialized instances.
/// Actually since this queue is a struct, instances don't even apply and there are no singletons.
/// </remarks>
private static readonly ImmutableQueue<T> s_EmptyField = new ImmutableQueue<T>(ImmutableStack<T>.Empty, ImmutableStack<T>.Empty);
/// <summary>
/// The end of the queue that enqueued elements are pushed onto.
/// </summary>
private readonly ImmutableStack<T> _backwards;
/// <summary>
/// The end of the queue from which elements are dequeued.
/// </summary>
private readonly ImmutableStack<T> _forwards;
/// <summary>
/// Backing field for the <see cref="BackwardsReversed"/> property.
/// </summary>
private ImmutableStack<T> _backwardsReversed;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableQueue{T}"/> class.
/// </summary>
/// <param name="forward">The forward stack.</param>
/// <param name="backward">The backward stack.</param>
private ImmutableQueue(ImmutableStack<T> forward, ImmutableStack<T> backward)
{
Requires.NotNull(forward, "forward");
Requires.NotNull(backward, "backward");
_forwards = forward;
_backwards = backward;
_backwardsReversed = null;
}
/// <summary>
/// Gets the empty queue.
/// </summary>
public ImmutableQueue<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return Empty;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return _forwards.IsEmpty && _backwards.IsEmpty; }
}
/// <summary>
/// Gets the empty queue.
/// </summary>
public static ImmutableQueue<T> Empty
{
get
{
Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// <summary>
/// Gets an empty queue.
/// </summary>
IImmutableQueue<T> IImmutableQueue<T>.Clear()
{
Contract.Assume(s_EmptyField.IsEmpty);
return this.Clear();
}
/// <summary>
/// Gets the reversed <see cref="_backwards"/> stack.
/// </summary>
private ImmutableStack<T> BackwardsReversed
{
get
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
// Although this is a lazy-init pattern, no lock is required because
// this instance is immutable otherwise, and a double-assignment from multiple
// threads is harmless.
if (_backwardsReversed == null)
{
_backwardsReversed = _backwards.Reverse();
}
return _backwardsReversed;
}
}
/// <summary>
/// Gets the element at the front of the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _forwards.Peek();
}
/// <summary>
/// Adds an element to the back of the queue.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The new queue.
/// </returns>
[Pure]
public ImmutableQueue<T> Enqueue(T value)
{
Contract.Ensures(!Contract.Result<ImmutableQueue<T>>().IsEmpty);
if (this.IsEmpty)
{
return new ImmutableQueue<T>(ImmutableStack<T>.Empty.Push(value), ImmutableStack<T>.Empty);
}
else
{
return new ImmutableQueue<T>(_forwards, _backwards.Push(value));
}
}
/// <summary>
/// Adds an element to the back of the queue.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The new queue.
/// </returns>
[Pure]
IImmutableQueue<T> IImmutableQueue<T>.Enqueue(T value)
{
return this.Enqueue(value);
}
/// <summary>
/// Returns a queue that is missing the front element.
/// </summary>
/// <returns>A queue; never <c>null</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public ImmutableQueue<T> Dequeue()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
ImmutableStack<T> f = _forwards.Pop();
if (!f.IsEmpty)
{
return new ImmutableQueue<T>(f, _backwards);
}
else if (_backwards.IsEmpty)
{
return ImmutableQueue<T>.Empty;
}
else
{
return new ImmutableQueue<T>(this.BackwardsReversed, ImmutableStack<T>.Empty);
}
}
/// <summary>
/// Retrieves the item at the head of the queue, and returns a queue with the head element removed.
/// </summary>
/// <param name="value">Receives the value from the head of the queue.</param>
/// <returns>The new queue with the head element removed.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[Pure]
public ImmutableQueue<T> Dequeue(out T value)
{
value = this.Peek();
return this.Dequeue();
}
/// <summary>
/// Returns a queue that is missing the front element.
/// </summary>
/// <returns>A queue; never <c>null</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
IImmutableQueue<T> IImmutableQueue<T>.Dequeue()
{
return this.Dequeue();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="Enumerator"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// A memory allocation-free enumerator of <see cref="ImmutableQueue{T}"/>.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public struct Enumerator
{
/// <summary>
/// The original queue being enumerated.
/// </summary>
private readonly ImmutableQueue<T> _originalQueue;
/// <summary>
/// The remaining forwards stack of the queue being enumerated.
/// </summary>
private ImmutableStack<T> _remainingForwardsStack;
/// <summary>
/// The remaining backwards stack of the queue being enumerated.
/// Its order is reversed when the field is first initialized.
/// </summary>
private ImmutableStack<T> _remainingBackwardsStack;
/// <summary>
/// Initializes a new instance of the <see cref="Enumerator"/> struct.
/// </summary>
/// <param name="queue">The queue to enumerate.</param>
internal Enumerator(ImmutableQueue<T> queue)
{
_originalQueue = queue;
// The first call to MoveNext will initialize these.
_remainingForwardsStack = null;
_remainingBackwardsStack = null;
}
/// <summary>
/// The current element.
/// </summary>
public T Current
{
get
{
if (_remainingForwardsStack == null)
{
// The initial call to MoveNext has not yet been made.
throw new InvalidOperationException();
}
if (!_remainingForwardsStack.IsEmpty)
{
return _remainingForwardsStack.Peek();
}
else if (!_remainingBackwardsStack.IsEmpty)
{
return _remainingBackwardsStack.Peek();
}
else
{
// We've advanced beyond the end of the queue.
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Advances enumeration to the next element.
/// </summary>
/// <returns>A value indicating whether there is another element in the enumeration.</returns>
public bool MoveNext()
{
if (_remainingForwardsStack == null)
{
// This is the initial step.
// Empty queues have no forwards or backwards
_remainingForwardsStack = _originalQueue._forwards;
_remainingBackwardsStack = _originalQueue.BackwardsReversed;
}
else if (!_remainingForwardsStack.IsEmpty)
{
_remainingForwardsStack = _remainingForwardsStack.Pop();
}
else if (!_remainingBackwardsStack.IsEmpty)
{
_remainingBackwardsStack = _remainingBackwardsStack.Pop();
}
return !_remainingForwardsStack.IsEmpty || !_remainingBackwardsStack.IsEmpty;
}
}
/// <summary>
/// A memory allocation-free enumerator of <see cref="ImmutableQueue{T}"/>.
/// </summary>
private class EnumeratorObject : IEnumerator<T>
{
/// <summary>
/// The original queue being enumerated.
/// </summary>
private readonly ImmutableQueue<T> _originalQueue;
/// <summary>
/// The remaining forwards stack of the queue being enumerated.
/// </summary>
private ImmutableStack<T> _remainingForwardsStack;
/// <summary>
/// The remaining backwards stack of the queue being enumerated.
/// Its order is reversed when the field is first initialized.
/// </summary>
private ImmutableStack<T> _remainingBackwardsStack;
/// <summary>
/// A value indicating whether this enumerator has been disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="Enumerator"/> struct.
/// </summary>
/// <param name="queue">The queue to enumerate.</param>
internal EnumeratorObject(ImmutableQueue<T> queue)
{
_originalQueue = queue;
}
/// <summary>
/// The current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
if (_remainingForwardsStack == null)
{
// The initial call to MoveNext has not yet been made.
throw new InvalidOperationException();
}
if (!_remainingForwardsStack.IsEmpty)
{
return _remainingForwardsStack.Peek();
}
else if (!_remainingBackwardsStack.IsEmpty)
{
return _remainingBackwardsStack.Peek();
}
else
{
// We've advanced beyond the end of the queue.
throw new InvalidOperationException();
}
}
}
/// <summary>
/// The current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Advances enumeration to the next element.
/// </summary>
/// <returns>A value indicating whether there is another element in the enumeration.</returns>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (_remainingForwardsStack == null)
{
// This is the initial step.
// Empty queues have no forwards or backwards
_remainingForwardsStack = _originalQueue._forwards;
_remainingBackwardsStack = _originalQueue.BackwardsReversed;
}
else if (!_remainingForwardsStack.IsEmpty)
{
_remainingForwardsStack = _remainingForwardsStack.Pop();
}
else if (!_remainingBackwardsStack.IsEmpty)
{
_remainingBackwardsStack = _remainingBackwardsStack.Pop();
}
return !_remainingForwardsStack.IsEmpty || !_remainingBackwardsStack.IsEmpty;
}
/// <summary>
/// Restarts enumeration.
/// </summary>
public void Reset()
{
this.ThrowIfDisposed();
_remainingBackwardsStack = null;
_remainingForwardsStack = null;
}
/// <summary>
/// Disposes this instance.
/// </summary>
public void Dispose()
{
_disposed = true;
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this
/// enumerator has already been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
Requires.FailObjectDisposed(this);
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableQueueDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableQueue<T> _queue;
/// <summary>
/// The simple view of the collection.
/// </summary>
private T[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableQueueDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="queue">The collection to display in the debugger</param>
public ImmutableQueueDebuggerProxy(ImmutableQueue<T> queue)
{
_queue = queue;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Contents
{
get
{
if (_contents == null)
{
_contents = _queue.ToArray();
}
return _contents;
}
}
}
}
| |
//
// X509Certificates.cs: Handles X.509 certificates.
//
// Author:
// Sebastien Pouliot <sebastien@xamarin.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
// Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using SSCX = System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using Mono.Security.Cryptography;
namespace Mono.Security.X509 {
// References:
// a. Internet X.509 Public Key Infrastructure Certificate and CRL Profile
// http://www.ietf.org/rfc/rfc3280.txt
// b. ITU ASN.1 standards (free download)
// http://www.itu.int/ITU-T/studygroups/com17/languages/
#if INSIDE_CORLIB
internal class X509Certificate : ISerializable {
#else
public class X509Certificate : ISerializable {
#endif
private ASN1 decoder;
private byte[] m_encodedcert;
private DateTime m_from;
private DateTime m_until;
private ASN1 issuer;
private string m_issuername;
private string m_keyalgo;
private byte[] m_keyalgoparams;
private ASN1 subject;
private string m_subject;
private byte[] m_publickey;
private byte[] signature;
private string m_signaturealgo;
private byte[] m_signaturealgoparams;
private byte[] certhash;
private RSA _rsa;
private DSA _dsa;
// from http://msdn.microsoft.com/en-gb/library/ff635835.aspx
private const string OID_DSA = "1.2.840.10040.4.1";
private const string OID_RSA = "1.2.840.113549.1.1.1";
// from http://www.ietf.org/rfc/rfc2459.txt
//
//Certificate ::= SEQUENCE {
// tbsCertificate TBSCertificate,
// signatureAlgorithm AlgorithmIdentifier,
// signature BIT STRING }
//
//TBSCertificate ::= SEQUENCE {
// version [0] Version DEFAULT v1,
// serialNumber CertificateSerialNumber,
// signature AlgorithmIdentifier,
// issuer Name,
// validity Validity,
// subject Name,
// subjectPublicKeyInfo SubjectPublicKeyInfo,
// issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
// -- If present, version shall be v2 or v3
// subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
// -- If present, version shall be v2 or v3
// extensions [3] Extensions OPTIONAL
// -- If present, version shall be v3 -- }
private int version;
private byte[] serialnumber;
private byte[] issuerUniqueID;
private byte[] subjectUniqueID;
private X509ExtensionCollection extensions;
private static string encoding_error = ("Input data cannot be coded as a valid certificate.");
// that's were the real job is!
private void Parse (byte[] data)
{
try {
decoder = new ASN1 (data);
// Certificate
if (decoder.Tag != 0x30)
throw new CryptographicException (encoding_error);
// Certificate / TBSCertificate
if (decoder [0].Tag != 0x30)
throw new CryptographicException (encoding_error);
ASN1 tbsCertificate = decoder [0];
int tbs = 0;
// Certificate / TBSCertificate / Version
ASN1 v = decoder [0][tbs];
version = 1; // DEFAULT v1
if ((v.Tag == 0xA0) && (v.Count > 0)) {
// version (optional) is present only in v2+ certs
version += v [0].Value [0]; // zero based
tbs++;
}
// Certificate / TBSCertificate / CertificateSerialNumber
ASN1 sn = decoder [0][tbs++];
if (sn.Tag != 0x02)
throw new CryptographicException (encoding_error);
serialnumber = sn.Value;
Array.Reverse (serialnumber, 0, serialnumber.Length);
// Certificate / TBSCertificate / AlgorithmIdentifier
tbs++;
// ASN1 signatureAlgo = tbsCertificate.Element (tbs++, 0x30);
issuer = tbsCertificate.Element (tbs++, 0x30);
m_issuername = X501.ToString (issuer);
ASN1 validity = tbsCertificate.Element (tbs++, 0x30);
ASN1 notBefore = validity [0];
m_from = ASN1Convert.ToDateTime (notBefore);
ASN1 notAfter = validity [1];
m_until = ASN1Convert.ToDateTime (notAfter);
subject = tbsCertificate.Element (tbs++, 0x30);
m_subject = X501.ToString (subject);
ASN1 subjectPublicKeyInfo = tbsCertificate.Element (tbs++, 0x30);
ASN1 algorithm = subjectPublicKeyInfo.Element (0, 0x30);
ASN1 algo = algorithm.Element (0, 0x06);
m_keyalgo = ASN1Convert.ToOid (algo);
// parameters ANY DEFINED BY algorithm OPTIONAL
// so we dont ask for a specific (Element) type and return DER
ASN1 parameters = algorithm [1];
m_keyalgoparams = ((algorithm.Count > 1) ? parameters.GetBytes () : null);
ASN1 subjectPublicKey = subjectPublicKeyInfo.Element (1, 0x03);
// we must drop th first byte (which is the number of unused bits
// in the BITSTRING)
int n = subjectPublicKey.Length - 1;
m_publickey = new byte [n];
Buffer.BlockCopy (subjectPublicKey.Value, 1, m_publickey, 0, n);
// signature processing
byte[] bitstring = decoder [2].Value;
// first byte contains unused bits in first byte
signature = new byte [bitstring.Length - 1];
Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
algorithm = decoder [1];
algo = algorithm.Element (0, 0x06);
m_signaturealgo = ASN1Convert.ToOid (algo);
parameters = algorithm [1];
if (parameters != null)
m_signaturealgoparams = parameters.GetBytes ();
else
m_signaturealgoparams = null;
// Certificate / TBSCertificate / issuerUniqueID
ASN1 issuerUID = tbsCertificate.Element (tbs, 0x81);
if (issuerUID != null) {
tbs++;
issuerUniqueID = issuerUID.Value;
}
// Certificate / TBSCertificate / subjectUniqueID
ASN1 subjectUID = tbsCertificate.Element (tbs, 0x82);
if (subjectUID != null) {
tbs++;
subjectUniqueID = subjectUID.Value;
}
// Certificate / TBSCertificate / Extensions
ASN1 extns = tbsCertificate.Element (tbs, 0xA3);
if ((extns != null) && (extns.Count == 1))
extensions = new X509ExtensionCollection (extns [0]);
else
extensions = new X509ExtensionCollection (null);
// keep a copy of the original data
m_encodedcert = (byte[]) data.Clone ();
}
catch (Exception ex) {
throw new CryptographicException (encoding_error, ex);
}
}
// constructors
public X509Certificate (byte[] data)
{
if (data != null) {
// does it looks like PEM ?
if ((data.Length > 0) && (data [0] != 0x30)) {
try {
data = PEM ("CERTIFICATE", data);
}
catch (Exception ex) {
throw new CryptographicException (encoding_error, ex);
}
}
Parse (data);
}
}
private byte[] GetUnsignedBigInteger (byte[] integer)
{
if (integer [0] == 0x00) {
// this first byte is added so we're sure it's an unsigned integer
// however we can't feed it into RSAParameters or DSAParameters
int length = integer.Length - 1;
byte[] uinteger = new byte [length];
Buffer.BlockCopy (integer, 1, uinteger, 0, length);
return uinteger;
}
else
return integer;
}
// public methods
public DSA DSA {
get {
if (m_keyalgoparams == null)
throw new CryptographicException ("Missing key algorithm parameters.");
if (_dsa == null && m_keyalgo == OID_DSA) {
DSAParameters dsaParams = new DSAParameters ();
// for DSA m_publickey contains 1 ASN.1 integer - Y
ASN1 pubkey = new ASN1 (m_publickey);
if ((pubkey == null) || (pubkey.Tag != 0x02))
return null;
dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
ASN1 param = new ASN1 (m_keyalgoparams);
if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
return null;
if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
return null;
dsaParams.P = GetUnsignedBigInteger (param [0].Value);
dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
dsaParams.G = GetUnsignedBigInteger (param [2].Value);
// BUG: MS BCL 1.0 can't import a key which
// isn't the same size as the one present in
// the container.
_dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
_dsa.ImportParameters (dsaParams);
}
return _dsa;
}
set {
_dsa = value;
if (value != null)
_rsa = null;
}
}
public X509ExtensionCollection Extensions {
get { return extensions; }
}
public byte[] Hash {
get {
if (certhash == null) {
if ((decoder == null) || (decoder.Count < 1))
return null;
string algo = PKCS1.HashNameFromOid (m_signaturealgo, false);
if (algo == null)
return null;
byte[] toBeSigned = decoder [0].GetBytes ();
using (var hash = PKCS1.CreateFromName (algo))
certhash = hash.ComputeHash (toBeSigned, 0, toBeSigned.Length);
}
return (byte[]) certhash.Clone ();
}
}
public virtual string IssuerName {
get { return m_issuername; }
}
public virtual string KeyAlgorithm {
get { return m_keyalgo; }
}
public virtual byte[] KeyAlgorithmParameters {
get {
if (m_keyalgoparams == null)
return null;
return (byte[]) m_keyalgoparams.Clone ();
}
set { m_keyalgoparams = value; }
}
public virtual byte[] PublicKey {
get {
if (m_publickey == null)
return null;
return (byte[]) m_publickey.Clone ();
}
}
public virtual RSA RSA {
get {
if (_rsa == null && m_keyalgo == OID_RSA) {
RSAParameters rsaParams = new RSAParameters ();
// for RSA m_publickey contains 2 ASN.1 integers
// the modulus and the public exponent
ASN1 pubkey = new ASN1 (m_publickey);
ASN1 modulus = pubkey [0];
if ((modulus == null) || (modulus.Tag != 0x02))
return null;
ASN1 exponent = pubkey [1];
if (exponent.Tag != 0x02)
return null;
rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
rsaParams.Exponent = exponent.Value;
// BUG: MS BCL 1.0 can't import a key which
// isn't the same size as the one present in
// the container.
int keySize = (rsaParams.Modulus.Length << 3);
_rsa = (RSA) new RSACryptoServiceProvider (keySize);
_rsa.ImportParameters (rsaParams);
}
return _rsa;
}
set {
if (value != null)
_dsa = null;
_rsa = value;
}
}
public virtual byte[] RawData {
get {
if (m_encodedcert == null)
return null;
return (byte[]) m_encodedcert.Clone ();
}
}
public virtual byte[] SerialNumber {
get {
if (serialnumber == null)
return null;
return (byte[]) serialnumber.Clone ();
}
}
public virtual byte[] Signature {
get {
if (signature == null)
return null;
switch (m_signaturealgo) {
case "1.2.840.113549.1.1.2": // MD2 with RSA encryption
case "1.2.840.113549.1.1.3": // MD4 with RSA encryption
case "1.2.840.113549.1.1.4": // MD5 with RSA encryption
case "1.2.840.113549.1.1.5": // SHA-1 with RSA Encryption
case "1.3.14.3.2.29": // SHA1 with RSA signature
case "1.2.840.113549.1.1.11": // SHA-256 with RSA Encryption
case "1.2.840.113549.1.1.12": // SHA-384 with RSA Encryption
case "1.2.840.113549.1.1.13": // SHA-512 with RSA Encryption
case "1.3.36.3.3.1.2": // RIPEMD160 with RSA Encryption
return (byte[]) signature.Clone ();
case "1.2.840.10040.4.3": // SHA-1 with DSA
ASN1 sign = new ASN1 (signature);
if ((sign == null) || (sign.Count != 2))
return null;
byte[] part1 = sign [0].Value;
byte[] part2 = sign [1].Value;
byte[] sig = new byte [40];
// parts may be less than 20 bytes (i.e. first bytes were 0x00)
// parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
int s1 = System.Math.Max (0, part1.Length - 20);
int e1 = System.Math.Max (0, 20 - part1.Length);
Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
int s2 = System.Math.Max (0, part2.Length - 20);
int e2 = System.Math.Max (20, 40 - part2.Length);
Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
return sig;
default:
throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
}
}
}
public virtual string SignatureAlgorithm {
get { return m_signaturealgo; }
}
public virtual byte[] SignatureAlgorithmParameters {
get {
if (m_signaturealgoparams == null)
return m_signaturealgoparams;
return (byte[]) m_signaturealgoparams.Clone ();
}
}
public virtual string SubjectName {
get { return m_subject; }
}
public virtual DateTime ValidFrom {
get { return m_from; }
}
public virtual DateTime ValidUntil {
get { return m_until; }
}
public int Version {
get { return version; }
}
public bool IsCurrent {
get { return WasCurrent (DateTime.UtcNow); }
}
public bool WasCurrent (DateTime instant)
{
return ((instant > ValidFrom) && (instant <= ValidUntil));
}
// uncommon v2 "extension"
public byte[] IssuerUniqueIdentifier {
get {
if (issuerUniqueID == null)
return null;
return (byte[]) issuerUniqueID.Clone ();
}
}
// uncommon v2 "extension"
public byte[] SubjectUniqueIdentifier {
get {
if (subjectUniqueID == null)
return null;
return (byte[]) subjectUniqueID.Clone ();
}
}
internal bool VerifySignature (DSA dsa)
{
// signatureOID is check by both this.Hash and this.Signature
DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
// only SHA-1 is supported
v.SetHashAlgorithm ("SHA1");
return v.VerifySignature (this.Hash, this.Signature);
}
internal bool VerifySignature (RSA rsa)
{
// SHA1-1 with DSA
if (m_signaturealgo == "1.2.840.10040.4.3")
return false;
RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
v.SetHashAlgorithm (PKCS1.HashNameFromOid (m_signaturealgo));
return v.VerifySignature (this.Hash, this.Signature);
}
public bool VerifySignature (AsymmetricAlgorithm aa)
{
if (aa == null)
throw new ArgumentNullException ("aa");
if (aa is RSA)
return VerifySignature (aa as RSA);
else if (aa is DSA)
return VerifySignature (aa as DSA);
else
throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
}
public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature)
{
RSACryptoServiceProvider r = (RSACryptoServiceProvider) RSA;
return r.VerifyHash (hash, hashAlgorithm, signature);
}
public bool IsSelfSigned {
get {
if (m_issuername != m_subject)
return false;
try {
if (RSA != null)
return VerifySignature (RSA);
else if (DSA != null)
return VerifySignature (DSA);
else
return false; // e.g. a certificate with only DSA parameters
}
catch (CryptographicException) {
return false;
}
}
}
public ASN1 GetIssuerName ()
{
return issuer;
}
public ASN1 GetSubjectName ()
{
return subject;
}
protected X509Certificate (SerializationInfo info, StreamingContext context)
{
Parse ((byte[]) info.GetValue ("raw", typeof (byte[])));
}
[SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
{
info.AddValue ("raw", m_encodedcert);
// note: we NEVER serialize the private key
}
static byte[] PEM (string type, byte[] data)
{
string pem = Encoding.ASCII.GetString (data);
string header = String.Format ("-----BEGIN {0}-----", type);
string footer = String.Format ("-----END {0}-----", type);
int start = pem.IndexOf (header) + header.Length;
int end = pem.IndexOf (footer, start);
string base64 = pem.Substring (start, (end - start));
return Convert.FromBase64String (base64);
}
}
}
| |
using System;
using System.Xml;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using SharpVectors.Dom.Svg;
namespace SharpVectors.Renderers.Gdi
{
/// <summary>
/// Wraps a Graphics object since it's sealed
/// </summary>
public sealed class GdiGraphicsWrapper : IDisposable
{
#region Private Fields
private bool _isStatic;
private Graphics _graphics;
private Graphics _idMapGraphics;
private Bitmap _idMapImage;
#endregion
#region Constructors
private GdiGraphicsWrapper(Image image, bool isStatic)
{
this._isStatic = isStatic;
if (!IsStatic)
{
_idMapImage = new Bitmap(image.Width, image.Height);
_idMapGraphics = Graphics.FromImage(_idMapImage);
_idMapGraphics.InterpolationMode = InterpolationMode.NearestNeighbor;
_idMapGraphics.SmoothingMode = SmoothingMode.None;
_idMapGraphics.CompositingQuality = CompositingQuality.Invalid;
}
_graphics = Graphics.FromImage(image);
}
private GdiGraphicsWrapper(IntPtr hdc, bool isStatic)
{
this._isStatic = isStatic;
if (!IsStatic)
{
// This will get resized when the actual size is known
_idMapImage = new Bitmap(0, 0);
_idMapGraphics = Graphics.FromImage(_idMapImage);
_idMapGraphics.InterpolationMode = InterpolationMode.NearestNeighbor;
_idMapGraphics.SmoothingMode = SmoothingMode.None;
_idMapGraphics.CompositingQuality = CompositingQuality.Invalid;
}
_graphics = Graphics.FromHdc(hdc);
}
#endregion
public static GdiGraphicsWrapper FromImage(Image image, bool isStatic)
{
return new GdiGraphicsWrapper(image, isStatic);
}
public static GdiGraphicsWrapper FromHdc(IntPtr hdc, bool isStatic)
{
return new GdiGraphicsWrapper(hdc, isStatic);
}
#region Properties
public bool IsStatic
{
get { return _isStatic; }
set
{
_isStatic = value;
_idMapGraphics.Dispose();
_idMapGraphics = null;
}
}
public Graphics Graphics
{
get { return _graphics; }
set { _graphics = value; }
}
public Graphics IdMapGraphics
{
get { return _graphics; }
}
public Bitmap IdMapRaster
{
get { return _idMapImage; }
}
#endregion
#region Graphics members
public void Clear(Color color)
{
_graphics.Clear(color);
if (_idMapGraphics != null) _idMapGraphics.Clear(Color.Empty);
}
public void Dispose()
{
_graphics.Dispose();
if (_idMapGraphics != null) _idMapGraphics.Dispose();
}
public GdiGraphicsContainer BeginContainer()
{
GdiGraphicsContainer container = new GdiGraphicsContainer();
if (_idMapGraphics != null)
container.IdMap = _idMapGraphics.BeginContainer();
container.Main = _graphics.BeginContainer();
return container;
}
public void EndContainer(GdiGraphicsContainer container)
{
if (_idMapGraphics != null)
_idMapGraphics.EndContainer(container.IdMap);
_graphics.EndContainer(container.Main);
}
public SmoothingMode SmoothingMode
{
get { return _graphics.SmoothingMode; }
set { _graphics.SmoothingMode = value; }
}
public Matrix Transform
{
get { return _graphics.Transform; }
set
{
if (_idMapGraphics != null) _idMapGraphics.Transform = value;
_graphics.Transform = value;
}
}
public void SetClip(GraphicsPath path)
{
_graphics.SetClip(path);
}
public void SetClip(RectangleF rect)
{
if (_idMapGraphics != null) _idMapGraphics.SetClip(rect);
_graphics.SetClip(rect);
}
public void SetClip(Region region, CombineMode combineMode)
{
if (_idMapGraphics != null) _idMapGraphics.SetClip(region, combineMode);
_graphics.SetClip(region, combineMode);
}
public void TranslateClip(float x, float y)
{
if (_idMapGraphics != null) _idMapGraphics.TranslateClip(x, y);
_graphics.TranslateClip(x, y);
}
public void ResetClip()
{
if (_idMapGraphics != null) _idMapGraphics.ResetClip();
_graphics.ResetClip();
}
public void FillPath(GdiRendering grNode, Brush brush, GraphicsPath path)
{
if (_idMapGraphics != null)
{
Brush idBrush = new SolidBrush(grNode.UniqueColor);
if (grNode.Element is SvgTextContentElement)
{
_idMapGraphics.FillRectangle(idBrush, path.GetBounds());
}
else
{
_idMapGraphics.FillPath(idBrush, path);
}
}
_graphics.FillPath(brush, path);
}
public void DrawPath(GdiRendering grNode, Pen pen, GraphicsPath path)
{
if (_idMapGraphics != null)
{
Pen idPen = new Pen(grNode.UniqueColor, pen.Width);
_idMapGraphics.DrawPath(idPen, path);
}
_graphics.DrawPath(pen, path);
}
public void TranslateTransform(float dx, float dy)
{
if (_idMapGraphics != null) _idMapGraphics.TranslateTransform(dx, dy);
_graphics.TranslateTransform(dx, dy);
}
public void ScaleTransform(float sx, float sy)
{
if (_idMapGraphics != null) _idMapGraphics.ScaleTransform(sx, sy);
_graphics.ScaleTransform(sx, sy);
}
public void RotateTransform(float angle)
{
if (_idMapGraphics != null) _idMapGraphics.RotateTransform(angle);
_graphics.RotateTransform(angle);
}
public void DrawImage(GdiRendering grNode, Image image, Rectangle destRect,
float srcX, float srcY, float srcWidth, float srcHeight,
GraphicsUnit graphicsUnit, ImageAttributes imageAttributes)
{
if (_idMapGraphics != null)
{
// This handles pointer-events for visibleFill visibleStroke and visible
/*Brush idBrush = new SolidBrush(grNode.UniqueColor);
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(destRect);
_idMapGraphics.FillPath(idBrush, gp);*/
Color unique = grNode.UniqueColor;
float r = (float)unique.R / 255;
float g = (float)unique.G / 255;
float b = (float)unique.B / 255;
ColorMatrix colorMatrix = new ColorMatrix(
new float[][] { new float[] {0f, 0f, 0f, 0f, 0f},
new float[] {0f, 0f, 0f, 0f, 0f},
new float[] {0f, 0f, 0f, 0f, 0f},
new float[] {0f, 0f, 0f, 1f, 0f},
new float[] {r, g, b, 0f, 1f} });
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
_idMapGraphics.DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, graphicsUnit, ia);
}
_graphics.DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, graphicsUnit, imageAttributes);
}
#endregion
}
/// <summary>
/// Wraps a GraphicsContainer because it is sealed.
/// This is a helper for GraphicsWrapper so that it can save
/// multiple container states. It holds the containers
/// for both the idMapGraphics and the main graphics
/// being rendered in the GraphicsWrapper.
/// </summary>
public sealed class GdiGraphicsContainer
{
internal GraphicsContainer IdMap;
internal GraphicsContainer Main;
public GdiGraphicsContainer()
{
}
public GdiGraphicsContainer(GraphicsContainer idmap, GraphicsContainer main)
{
this.IdMap = idmap;
this.Main = main;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
namespace Miracle.FileZilla.Api
{
/// <summary>
/// Class used for low level communication with FileZilla admin interface
/// Note! BufferSize must be set to a value large enough to handle incomming data from FileZilla server.
/// </summary>
public class FileZillaServerProtocol : SocketCommunication
{
private int _receiveMessageRetryCount = 10;
/// <summary>
/// Versions used to develop this API
/// </summary>
public readonly int[] SupportedProtocolVersions =
{
ProtocolVersions.Initial,
ProtocolVersions.User16M,
ProtocolVersions.TLS,
ProtocolVersions.Sha512,
ProtocolVersions.UserControl24
};
/// <summary>
/// Defailt IP
/// </summary>
public const string DefaultIp = "127.0.0.1";
/// <summary>
/// Default port
/// </summary>
public const int DefaultPort = 14147;
/// <summary>
/// Server version. Populated by Connect method.
/// </summary>
public int ServerVersion { get; private set; }
/// <summary>
/// Protocol version. Populated by Connect method.
/// </summary>
public int ProtocolVersion { get; private set; }
/// <summary>
/// How many times to try to get a message of a particular type before giving up.
/// </summary>
public int ReceiveMessageRetryCount
{
get { return _receiveMessageRetryCount; }
set
{
if(value < 1) throw new ArgumentException("Must be a number greater than 0");
_receiveMessageRetryCount = value;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="address">IP address of FileZilla server</param>
/// <param name="port">Port number that admin interface is listening to</param>
public FileZillaServerProtocol(IPAddress address, int port)
: base(address, port)
{
}
/// <summary>
/// Send command to FileZilla
/// </summary>
/// <param name="messageType">Type of FileZilla message to send</param>
public void SendCommand(MessageType messageType)
{
SendCommand(messageType, new byte[] { });
}
/// <summary>
/// Send command with byte data to FileZilla
/// </summary>
/// <param name="messageType">Type of FileZilla message to send</param>
/// <param name="data">Byte data to send with command</param>
public void SendCommand(MessageType messageType, byte data)
{
SendCommand(messageType, new[] { data });
}
/// <summary>
/// Send command with bytes to FileZilla
/// </summary>
/// <param name="messageType">Type of FileZilla message to send</param>
/// <param name="data">Byte data to send with command</param>
public void SendCommand(MessageType messageType, byte[] data)
{
SendCommand(messageType, writer => writer.Write(data));
}
/// <summary>
/// Send command to FileZilla using an dataAction method
/// </summary>
/// <param name="messageType">Type of FileZilla message to send</param>
/// <param name="dataAction">Method that writes the raw data to the command. Length is automatically generated for the data written by dataAction</param>
public void SendCommand(MessageType messageType, Action<BinaryWriter> dataAction)
{
using (var stream = new MemoryStream())
{
using (var writer = new BinaryWriter(stream))
{
var cmd = (byte) (((int) MessageOrigin.ClientRequest) | ((byte) messageType << 2));
writer.Write(cmd);
writer.WriteLength(dataAction);
}
if (Log != null)
Log.WriteLine("Send: {0}", messageType);
Send(stream.ToArray());
}
}
/// <summary>
/// Receive FileZilla of specific message type, and expect an empty (length=0) response.
/// </summary>
/// <param name="messageType">Type of FileZilla message to receive</param>
/// <exception cref="ProtocolException">If length other than 0</exception>
public void Receive(MessageType messageType)
{
var message = ReceiveMessage(messageType);
if (message.RawData.Length != 0)
throw new ProtocolException("Expected message with length 0, actual " + message.RawData.Length);
}
/// <summary>
/// Receive FileZilla of specific message type, and expect a message body of generic type T.
/// </summary>
/// <param name="messageType">Type of FileZilla message to receive</param>
/// <typeparam name="T">The expected budy type</typeparam>
/// <returns>The body of the message</returns>
public T Receive<T>(MessageType messageType)
{
var message = ReceiveMessage(messageType);
return (T)message.Body;
}
private void Receive(Action<BinaryReader> action)
{
var data = Receive();
using (var reader = new BinaryReader(new MemoryStream(data)))
{
action(reader);
}
}
/// <summary>
/// Receive specific message matching MessageType. Note! This filters away all ServerMessages to get to that particular message.
/// </summary>
/// <param name="messageType">The type of message to find</param>
/// <returns>FileZilla message matching MessageType</returns>
public FileZillaMessage ReceiveMessage(MessageType messageType)
{
for (int retry = 0; retry < ReceiveMessageRetryCount; retry++)
{
var messages = ReceiveMessages();
FileZillaMessage fileZillaMessage = null;
bool allMessagesHandled = true;
foreach (FileZillaMessage check in messages)
{
if (check.MessageOrigin == MessageOrigin.ServerReply && check.MessageType == messageType)
{
if (fileZillaMessage != null)
throw new ProtocolException("Multiple commands matched");
fileZillaMessage = check;
}
else
{
if (!HandleUnmatchedMessage(messageType, check))
{
allMessagesHandled = false;
break;
}
}
}
if (!allMessagesHandled)
throw ProtocolException.Create(messageType, messages);
if (fileZillaMessage != null)
return fileZillaMessage;
// Jedi mind trick: This is not the message you are looking for: Do it all again
}
throw new ProtocolException("Unable to receive message: " + messageType);
}
/// <summary>
/// Handle unmatched messages when calling ReceiveMessage method. Override to provide your own implementation (e.g. for logging)
/// </summary>
/// <param name="messageType">messageType sought</param>
/// <param name="message">actual message</param>
/// <returns>True if message can safely be ignored, False if message reception should be terminated.</returns>
protected virtual bool HandleUnmatchedMessage(MessageType messageType, FileZillaMessage message)
{
#if DEBUG
LogData(string.Format("Unmatched message: {0}/{1} with length {2}", message.MessageOrigin, message.MessageType, message.RawData.Length), message.RawData);
#endif
return message.MessageOrigin == MessageOrigin.ServerMessage
|| (message.MessageOrigin == MessageOrigin.ServerReply && message.MessageType == MessageType.Authenticate);
}
/// <summary>
/// Get parsed messages from FileZilla admin interface
/// </summary>
/// <returns></returns>
public FileZillaMessage[] ReceiveMessages()
{
var data = Receive();
var list = new List<FileZillaMessage>();
using (var memoryStream = new MemoryStream())
{
memoryStream.Append(data);
using (var reader = new BinaryReader(memoryStream))
{
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
var b = reader.ReadByte();
var count = reader.ReadInt32();
while ((reader.BaseStream.Length - reader.BaseStream.Position) < count)
{
var buffer = Receive();
memoryStream.Append(buffer);
}
byte[] payload = reader.ReadBytes(count);
var message = new FileZillaMessage((MessageOrigin) (b & 0x3), (MessageType) (b >> 2), payload, ProtocolVersion);
list.Add(message);
}
}
}
return list.ToArray();
}
/// <summary>
/// Connect to FileZilla admin interface
/// </summary>
/// <param name="password">FileZilla admin password</param>
public void Connect(string password)
{
Authentication authentication = null;
Connect();
Receive(reader =>
{
try
{
reader.Verify("FZS");
}
catch (ProtocolException ex)
{
throw new ApiException("That's not a FileZilla server listening on that port.", ex);
}
ServerVersion = reader.ReadLength(reader.ReadBigEndianInt16(), x => x.ReadInt32());
ProtocolVersion = reader.ReadLength(reader.ReadBigEndianInt16(), x => x.ReadInt32());
// Verify protocol version
if (!SupportedProtocolVersions.Contains(ProtocolVersion))
{
if(ProtocolVersion < ProtocolVersions.Initial)
throw new ApiException("FileZilla server is too old. Install FileZilla Server 0.9.43 or later");
throw new ApiException(
string.Format(
"Unsupported FileZilla protocol version:{0} server version:{1} (API version: {2}). Please report issue at https://github.com/PolarbearDK/Miracle.FileZilla.Api.",
FormatVersion(ProtocolVersion),
FormatVersion(ServerVersion),
this.GetType().GetTypeInfo().Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version));
}
authentication = reader.Read<Authentication>(ProtocolVersion);
});
if (!authentication.NoPasswordRequired)
{
SendCommand(MessageType.Authenticate, authentication.HashPassword(password));
Receive(MessageType.Authenticate);
}
}
private string FormatVersion(int serverVersion)
{
return string.Format("{0:X}.{1:X}.{2:X}.{3:X}",
(serverVersion >> 24) & 0xFF,
(serverVersion >> 16) & 0xFF,
(serverVersion >> 8) & 0xFF,
(serverVersion >> 0) & 0xFF);
}
}
}
| |
//
// UPnPContainerSource.cs
//
// Authors:
// Tobias 'topfs2' Arrskog <tobias.arrskog@gmail.com>
//
// Copyright (C) 2011 Tobias 'topfs2' Arrskog
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Mono.Upnp;
using Mono.Upnp.Dcp.MediaServer1.ContentDirectory1;
using Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.AV;
using Banshee.Configuration;
using Banshee.Sources;
using Hyena;
namespace Banshee.UPnPClient
{
public class UPnPServerSource : Source
{
private string udn;
private UPnPMusicSource music_source;
private UPnPVideoSource video_source;
private SchemaEntry<bool> expanded_schema;
public UPnPServerSource (Device device) : base (Catalog.GetString ("UPnP Share"), device.FriendlyName, 300)
{
Properties.SetStringList ("Icon.Name", "computer", "network-server");
TypeUniqueId = "upnp-container";
expanded_schema = new SchemaEntry<bool> ("plugins.upnp." + device.Udn, "expanded", true,
"UPnP Share expanded", "UPnP Share expanded" );
udn = device.Udn;
ContentDirectoryController content_directory = null;
foreach (Service service in device.Services) {
Log.Debug ("UPnPService \"" + device.FriendlyName + "\" Implements " + service.Type);
if (service.Type.Type == "ContentDirectory") {
content_directory = new ContentDirectoryController (service.GetController());
}
}
if (content_directory == null) {
throw new ArgumentNullException("content_directory");
}
ThreadAssist.Spawn (delegate {
Parse (device, content_directory);
});
}
~UPnPServerSource ()
{
if (music_source != null) {
RemoveChildSource (music_source);
music_source = null;
}
if (video_source != null) {
RemoveChildSource (video_source);
video_source = null;
}
}
delegate void ChunkHandler<T> (Results<T> results);
void HandleResults<T> (Results<T> results, RemoteContentDirectory remote_dir, ChunkHandler<T> chunkHandler)
{
bool has_results = results.Count > 0;
while (has_results) {
chunkHandler (results);
has_results = results.HasMoreResults;
if (has_results) {
results = results.GetMoreResults (remote_dir);
}
}
}
List<string[]> FindBrowseQuirks (Device device)
{
List<string[]> core = new List<string[]>();
if (device.ModelName == "MediaTomb" && device.ModelNumber == "0.12.1") {
core.Add (new string[2] { "Audio", "Albums" });
core.Add (new string[2] { "Video", "All Video" });
} else if (device.ModelName == "Coherence UPnP A/V MediaServer" && device.ModelNumber == "0.6.6.2") {
core.Add (new string[1] { "Albums" });
} else {
core.Add (new string[0]);
}
return core;
}
void Parse (Device device, ContentDirectoryController content_directory)
{
RemoteContentDirectory remote_dir = new RemoteContentDirectory (content_directory);
DateTime begin = DateTime.Now;
bool recursive_browse = !content_directory.CanSearch;
try {
Container root = remote_dir.GetRootObject ();
if (!recursive_browse) {
try {
Log.Debug ("Content directory is searchable, let's search");
HandleResults<MusicTrack> (remote_dir.Search<MusicTrack>(root, visitor => visitor.VisitDerivedFrom("upnp:class", "object.item.audioItem.musicTrack"), new ResultsSettings()),
remote_dir,
chunk => {
List<MusicTrack> music_tracks = new List<MusicTrack>();
foreach (var item in chunk) {
music_tracks.Add (item as MusicTrack);
}
AddMusic (music_tracks);
});
HandleResults<VideoItem> (remote_dir.Search<VideoItem>(root, visitor => visitor.VisitDerivedFrom("upnp:class", "object.item.videoItem"), new ResultsSettings()),
remote_dir,
chunk => {
List<VideoItem> video_tracks = new List<VideoItem>();
foreach (var item in chunk) {
video_tracks.Add (item as VideoItem);
}
AddVideo (video_tracks);
});
} catch (System.InvalidCastException exception) {
Log.Exception (exception);
recursive_browse = true;
}
}
if (recursive_browse) {
Log.Debug ("Content directory is not searchable, let's browse recursively");
List<MusicTrack> music_tracks = new List<MusicTrack> ();
List<VideoItem> video_tracks = new List<VideoItem> ();
foreach (var hierarchy in FindBrowseQuirks (device)) {
TraverseContainer (remote_dir, root, hierarchy, 0, music_tracks, video_tracks);
}
if (music_tracks.Count > 0) {
AddMusic (music_tracks);
}
if (video_tracks.Count > 0) {
AddVideo (video_tracks);
}
}
} catch (Exception exception) {
Log.Exception (exception);
}
Log.Debug ("Found all items on the service, took " + (DateTime.Now - begin).ToString());
}
void TraverseContainer (RemoteContentDirectory remote_dir, Container container, string[] hierarchy, int position, List<MusicTrack> music_tracks, List<VideoItem> video_tracks)
{
if (hierarchy != null && hierarchy.Length > position) {
HandleResults<Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.Object> (
remote_dir.GetChildren<Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.Object> (container),
remote_dir,
chunk => {
foreach (var upnp_object in chunk) {
if (upnp_object is Container && upnp_object.Title == hierarchy[position]) {
TraverseContainer (remote_dir, upnp_object as Container, hierarchy, position + 1, music_tracks, video_tracks);
}
}
});
} else {
ParseContainer (remote_dir, container, 0, music_tracks, video_tracks);
}
}
void ParseContainer (RemoteContentDirectory remote_dir, Container container, int depth, List<MusicTrack> music_tracks, List<VideoItem> video_tracks)
{
if (depth > 10 || (container.ChildCount != null && container.ChildCount == 0)) {
return;
}
HandleResults<Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.Object> (
remote_dir.GetChildren<Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.Object> (container),
remote_dir,
chunk => {
foreach (var upnp_object in chunk) {
if (upnp_object is Item) {
Item item = upnp_object as Item;
if (item.IsReference || item.Resources.Count == 0) {
continue;
}
if (item is MusicTrack) {
music_tracks.Add (item as MusicTrack);
} else if (item is VideoItem) {
video_tracks.Add (item as VideoItem);
}
} else if (upnp_object is Container) {
ParseContainer (remote_dir, upnp_object as Container, depth + 1, music_tracks, video_tracks);
}
if (music_tracks.Count > 500) {
AddMusic (music_tracks);
music_tracks.Clear ();
}
if (video_tracks.Count > 100) {
AddVideo (video_tracks);
video_tracks.Clear ();
}
}
});
}
public void Disconnect ()
{
if (music_source != null) {
music_source.Disconnect ();
}
if (video_source != null) {
video_source.Disconnect ();
}
}
private void AddMusic (List<MusicTrack> tracks)
{
if (music_source == null) {
music_source = new UPnPMusicSource (udn);
AddChildSource (music_source);
}
music_source.AddTracks (tracks);
}
private void AddVideo (List<VideoItem> tracks)
{
if (video_source == null) {
video_source = new UPnPVideoSource (udn);
AddChildSource (video_source);
}
video_source.AddTracks (tracks);
}
public override bool? AutoExpand {
get { return expanded_schema.Get (); }
}
public override bool Expanded {
get { return expanded_schema.Get (); }
set { expanded_schema.Set (value); }
}
public override bool CanActivate {
get { return false; }
}
public override bool CanRename {
get { return false; }
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:41:10 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
#pragma warning disable 1591
namespace DotSpatial.Projections.ProjectedCategories
{
/// <summary>
/// KrugerZian1980
/// </summary>
public class KrugerXian1980 : CoordinateSystemCategory
{
#region Private Variables
public readonly ProjectionInfo Xian19803DegreeGKCM102E;
public readonly ProjectionInfo Xian19803DegreeGKCM105E;
public readonly ProjectionInfo Xian19803DegreeGKCM108E;
public readonly ProjectionInfo Xian19803DegreeGKCM111E;
public readonly ProjectionInfo Xian19803DegreeGKCM114E;
public readonly ProjectionInfo Xian19803DegreeGKCM117E;
public readonly ProjectionInfo Xian19803DegreeGKCM120E;
public readonly ProjectionInfo Xian19803DegreeGKCM123E;
public readonly ProjectionInfo Xian19803DegreeGKCM126E;
public readonly ProjectionInfo Xian19803DegreeGKCM129E;
public readonly ProjectionInfo Xian19803DegreeGKCM132E;
public readonly ProjectionInfo Xian19803DegreeGKCM135E;
public readonly ProjectionInfo Xian19803DegreeGKCM75E;
public readonly ProjectionInfo Xian19803DegreeGKCM78E;
public readonly ProjectionInfo Xian19803DegreeGKCM81E;
public readonly ProjectionInfo Xian19803DegreeGKCM84E;
public readonly ProjectionInfo Xian19803DegreeGKCM87E;
public readonly ProjectionInfo Xian19803DegreeGKCM90E;
public readonly ProjectionInfo Xian19803DegreeGKCM93E;
public readonly ProjectionInfo Xian19803DegreeGKCM96E;
public readonly ProjectionInfo Xian19803DegreeGKCM99E;
public readonly ProjectionInfo Xian19803DegreeGKZone25;
public readonly ProjectionInfo Xian19803DegreeGKZone26;
public readonly ProjectionInfo Xian19803DegreeGKZone27;
public readonly ProjectionInfo Xian19803DegreeGKZone28;
public readonly ProjectionInfo Xian19803DegreeGKZone29;
public readonly ProjectionInfo Xian19803DegreeGKZone30;
public readonly ProjectionInfo Xian19803DegreeGKZone31;
public readonly ProjectionInfo Xian19803DegreeGKZone32;
public readonly ProjectionInfo Xian19803DegreeGKZone33;
public readonly ProjectionInfo Xian19803DegreeGKZone34;
public readonly ProjectionInfo Xian19803DegreeGKZone35;
public readonly ProjectionInfo Xian19803DegreeGKZone36;
public readonly ProjectionInfo Xian19803DegreeGKZone37;
public readonly ProjectionInfo Xian19803DegreeGKZone38;
public readonly ProjectionInfo Xian19803DegreeGKZone39;
public readonly ProjectionInfo Xian19803DegreeGKZone40;
public readonly ProjectionInfo Xian19803DegreeGKZone41;
public readonly ProjectionInfo Xian19803DegreeGKZone42;
public readonly ProjectionInfo Xian19803DegreeGKZone43;
public readonly ProjectionInfo Xian19803DegreeGKZone44;
public readonly ProjectionInfo Xian19803DegreeGKZone45;
public readonly ProjectionInfo Xian1980GKCM105E;
public readonly ProjectionInfo Xian1980GKCM111E;
public readonly ProjectionInfo Xian1980GKCM117E;
public readonly ProjectionInfo Xian1980GKCM123E;
public readonly ProjectionInfo Xian1980GKCM129E;
public readonly ProjectionInfo Xian1980GKCM135E;
public readonly ProjectionInfo Xian1980GKCM75E;
public readonly ProjectionInfo Xian1980GKCM81E;
public readonly ProjectionInfo Xian1980GKCM87E;
public readonly ProjectionInfo Xian1980GKCM93E;
public readonly ProjectionInfo Xian1980GKCM99E;
public readonly ProjectionInfo Xian1980GKZone13;
public readonly ProjectionInfo Xian1980GKZone14;
public readonly ProjectionInfo Xian1980GKZone15;
public readonly ProjectionInfo Xian1980GKZone16;
public readonly ProjectionInfo Xian1980GKZone17;
public readonly ProjectionInfo Xian1980GKZone18;
public readonly ProjectionInfo Xian1980GKZone19;
public readonly ProjectionInfo Xian1980GKZone20;
public readonly ProjectionInfo Xian1980GKZone21;
public readonly ProjectionInfo Xian1980GKZone22;
public readonly ProjectionInfo Xian1980GKZone23;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of KrugerZian1980
/// </summary>
public KrugerXian1980()
{
Xian19803DegreeGKCM102E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM105E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM108E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM111E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM114E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM117E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM120E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM123E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM126E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM129E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM132E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM135E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM75E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM78E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM81E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM84E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM87E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM90E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM93E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM96E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM99E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone25 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=25500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone26 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=26500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone27 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=27500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone28 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=28500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone29 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=29500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone30 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=30500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone31 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=31500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone32 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=32500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone33 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=33500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone34 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=34500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone35 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=35500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone36 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=36500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone37 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=37500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone38 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=38500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone39 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=39500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone40 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=40500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone41 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=41500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone42 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=42500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone43 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=43500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone44 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=44500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKZone45 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=45500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM105E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM111E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM117E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM123E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM129E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM135E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM75E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM81E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM87E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM93E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKCM99E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone13 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=13500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone14 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=14500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone15 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=15500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone16 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=16500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone17 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=17500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone18 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=18500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone19 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=19500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone20 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=20500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone21 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=21500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone22 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=22500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian1980GKZone23 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=23500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs ");
Xian19803DegreeGKCM102E.Name = "Xian_1980_3_Degree_GK_CM_102E";
Xian19803DegreeGKCM105E.Name = "Xian_1980_3_Degree_GK_CM_105E";
Xian19803DegreeGKCM108E.Name = "Xian_1980_3_Degree_GK_CM_108E";
Xian19803DegreeGKCM111E.Name = "Xian_1980_3_Degree_GK_CM_111E";
Xian19803DegreeGKCM114E.Name = "Xian_1980_3_Degree_GK_CM_114E";
Xian19803DegreeGKCM117E.Name = "Xian_1980_3_Degree_GK_CM_117E";
Xian19803DegreeGKCM120E.Name = "Xian_1980_3_Degree_GK_CM_120E";
Xian19803DegreeGKCM123E.Name = "Xian_1980_3_Degree_GK_CM_123E";
Xian19803DegreeGKCM126E.Name = "Xian_1980_3_Degree_GK_CM_126E";
Xian19803DegreeGKCM129E.Name = "Xian_1980_3_Degree_GK_CM_129E";
Xian19803DegreeGKCM132E.Name = "Xian_1980_3_Degree_GK_CM_132E";
Xian19803DegreeGKCM135E.Name = "Xian_1980_3_Degree_GK_CM_135E";
Xian19803DegreeGKCM75E.Name = "Xian_1980_3_Degree_GK_CM_75E";
Xian19803DegreeGKCM78E.Name = "Xian_1980_3_Degree_GK_CM_78E";
Xian19803DegreeGKCM81E.Name = "Xian_1980_3_Degree_GK_CM_81E";
Xian19803DegreeGKCM84E.Name = "Xian_1980_3_Degree_GK_CM_84E";
Xian19803DegreeGKCM87E.Name = "Xian_1980_3_Degree_GK_CM_87E";
Xian19803DegreeGKCM90E.Name = "Xian_1980_3_Degree_GK_CM_90E";
Xian19803DegreeGKCM93E.Name = "Xian_1980_3_Degree_GK_CM_93E";
Xian19803DegreeGKCM96E.Name = "Xian_1980_3_Degree_GK_CM_96E";
Xian19803DegreeGKCM99E.Name = "Xian_1980_3_Degree_GK_CM_99E";
Xian19803DegreeGKZone25.Name = "Xian_1980_3_Degree_GK_Zone_25";
Xian19803DegreeGKZone26.Name = "Xian_1980_3_Degree_GK_Zone_26";
Xian19803DegreeGKZone27.Name = "Xian_1980_3_Degree_GK_Zone_27";
Xian19803DegreeGKZone28.Name = "Xian_1980_3_Degree_GK_Zone_28";
Xian19803DegreeGKZone29.Name = "Xian_1980_3_Degree_GK_Zone_29";
Xian19803DegreeGKZone30.Name = "Xian_1980_3_Degree_GK_Zone_30";
Xian19803DegreeGKZone31.Name = "Xian_1980_3_Degree_GK_Zone_31";
Xian19803DegreeGKZone32.Name = "Xian_1980_3_Degree_GK_Zone_32";
Xian19803DegreeGKZone33.Name = "Xian_1980_3_Degree_GK_Zone_33";
Xian19803DegreeGKZone34.Name = "Xian_1980_3_Degree_GK_Zone_34";
Xian19803DegreeGKZone35.Name = "Xian_1980_3_Degree_GK_Zone_35";
Xian19803DegreeGKZone36.Name = "Xian_1980_3_Degree_GK_Zone_36";
Xian19803DegreeGKZone37.Name = "Xian_1980_3_Degree_GK_Zone_37";
Xian19803DegreeGKZone38.Name = "Xian_1980_3_Degree_GK_Zone_38";
Xian19803DegreeGKZone39.Name = "Xian_1980_3_Degree_GK_Zone_39";
Xian19803DegreeGKZone40.Name = "Xian_1980_3_Degree_GK_Zone_40";
Xian19803DegreeGKZone41.Name = "Xian_1980_3_Degree_GK_Zone_41";
Xian19803DegreeGKZone42.Name = "Xian_1980_3_Degree_GK_Zone_42";
Xian19803DegreeGKZone43.Name = "Xian_1980_3_Degree_GK_Zone_43";
Xian19803DegreeGKZone44.Name = "Xian_1980_3_Degree_GK_Zone_44";
Xian19803DegreeGKZone45.Name = "Xian_1980_3_Degree_GK_Zone_45";
Xian1980GKCM105E.Name = "Xian_1980_GK_CM_105E";
Xian1980GKCM111E.Name = "Xian_1980_GK_CM_111E";
Xian1980GKCM117E.Name = "Xian_1980_GK_CM_117E";
Xian1980GKCM123E.Name = "Xian_1980_GK_CM_123E";
Xian1980GKCM129E.Name = "Xian_1980_GK_CM_129E";
Xian1980GKCM135E.Name = "Xian_1980_GK_CM_135E";
Xian1980GKCM75E.Name = "Xian_1980_GK_CM_75E";
Xian1980GKCM81E.Name = "Xian_1980_GK_CM_81E";
Xian1980GKCM87E.Name = "Xian_1980_GK_CM_87E";
Xian1980GKCM93E.Name = "Xian_1980_GK_CM_93E";
Xian1980GKCM99E.Name = "Xian_1980_GK_CM_99E";
Xian1980GKZone13.Name = "Xian_1980_GK_Zone_13";
Xian1980GKZone14.Name = "Xian_1980_GK_Zone_14";
Xian1980GKZone15.Name = "Xian_1980_GK_Zone_15";
Xian1980GKZone16.Name = "Xian_1980_GK_Zone_16";
Xian1980GKZone17.Name = "Xian_1980_GK_Zone_17";
Xian1980GKZone18.Name = "Xian_1980_GK_Zone_18";
Xian1980GKZone19.Name = "Xian_1980_GK_Zone_19";
Xian1980GKZone20.Name = "Xian_1980_GK_Zone_20";
Xian1980GKZone21.Name = "Xian_1980_GK_Zone_21";
Xian1980GKZone22.Name = "Xian_1980_GK_Zone_22";
Xian1980GKZone23.Name = "Xian_1980_GK_Zone_23";
Xian19803DegreeGKCM102E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM105E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM108E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM111E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM114E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM117E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM120E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM123E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM126E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM129E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM132E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM135E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM75E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM78E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM81E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM84E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM87E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM90E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM93E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM96E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM99E.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone25.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone26.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone27.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone28.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone29.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone30.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone31.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone32.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone33.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone34.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone35.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone36.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone37.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone38.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone39.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone40.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone41.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone42.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone43.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone44.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKZone45.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM105E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM111E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM117E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM123E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM129E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM135E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM75E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM81E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM87E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM93E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKCM99E.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone13.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone14.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone15.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone16.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone17.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone18.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone19.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone20.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone21.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone22.GeographicInfo.Name = "GCS_Xian_1980";
Xian1980GKZone23.GeographicInfo.Name = "GCS_Xian_1980";
Xian19803DegreeGKCM102E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM105E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM108E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM111E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM114E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM117E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM120E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM123E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM126E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM129E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM132E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM135E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM75E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM78E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM81E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM84E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM87E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM90E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM93E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM96E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKCM99E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone25.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone26.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone27.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone28.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone29.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone30.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone31.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone32.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone33.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone34.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone35.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone36.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone37.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone38.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone39.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone40.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone41.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone42.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone43.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone44.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian19803DegreeGKZone45.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM105E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM111E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM117E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM123E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM129E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM135E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM75E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM81E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM87E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM93E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKCM99E.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone13.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone14.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone15.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone16.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone17.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone18.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone19.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone20.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone21.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone22.GeographicInfo.Datum.Name = "D_Xian_1980";
Xian1980GKZone23.GeographicInfo.Datum.Name = "D_Xian_1980";
}
#endregion
}
}
#pragma warning restore 1591
| |
// 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.Text;
namespace EncodingTests
{
public static class UTF7
{
private static readonly EncodingTestHelper s_encodingUtil_UTF7 = new EncodingTestHelper("UTF-7");
[Fact]
public static void GetByteCount_InvalidArgumentAndBoundaryValues()
{
s_encodingUtil_UTF7.GetByteCountTest(String.Empty, 0, 0, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest(String.Empty, 0, 1, 0));
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetByteCountTest((String)null, 0, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", -1, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", 0, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", -1, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", 1, -1, 0));
s_encodingUtil_UTF7.GetByteCountTest("abc", 3, 0, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", 3, 1, 0));
s_encodingUtil_UTF7.GetByteCountTest("abc", 2, 1, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", 4, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest("abc", 2, 2, 0));
}
[Fact]
public static void GetCharCount_InvalidArgumentAndBoundaryValues()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetCharCountTest((Byte[])null, 0, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, -1, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, -1, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 1, -1, 0));
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 3, 0, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 3, 1, 0));
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 2, 1, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 4, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61, 0x62, 0x63 }, 2, 2, 0));
}
[Fact]
public static void GetByteCount_InvalidArgumentAndBoundaryValues_Pointer()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetByteCountTest((String)null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetByteCountTest(String.Empty, -1, 0));
s_encodingUtil_UTF7.GetByteCountTest(String.Empty, 0, 0);
s_encodingUtil_UTF7.GetByteCountTest("a", 0, 0);
}
[Fact]
public static void GetCharCount_InvalidArgumentAndBoundaryValues_Pointer()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetCharCountTest((Byte[])null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { }, -1, 0));
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { }, 0, 0);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x61 }, 0, 0);
}
[Fact]
public static void GetBytes_InvalidConversionInput()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetBytesTest((String)null, 0, 0, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", -1, 0, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, -1, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", -1, -1, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 1, -1, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 4, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 1, 3, 0, 0, new Byte[] { }, 0));
}
[Fact]
public static void GetChars_InvalidConversionInput()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetCharsTest((Byte[])null, 0, 0, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, -1, 0, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, -1, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, -1, -1, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 1, -1, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 4, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 1, 3, 0, 0, String.Empty, 0));
}
[Fact]
public static void GetChars_BufferBoundary()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 3, -2, 0, String.Empty, 0));
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 3, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 3, -1, 1, String.Empty, 0));
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 3, 1, 0, String.Empty, 0));
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 0, 1, 1, "\u0000", 0);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 0, 1, 2, String.Empty, 0));
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 3, 5, 1, "\u0000\u0061\u0062\u0063\u0000", 3);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 0, -1, -1, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61, 0x62, 0x63 }, 0, 1, -1, -1, String.Empty, 0));
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, 0, 0, -1, 0, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, 0, 0, 0, 0, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61 }, 0, 0, 1, 0, "\u0000", 0);
}
[Fact]
public static void GetBytes_BufferBoundary()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 3, -2, 0, (Byte[])null, 0));
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 3, 0, 0, (Byte[])null, 0));
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 3, -1, 1, (Byte[])null, 0));
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 3, 1, 0, (Byte[])null, 0));
s_encodingUtil_UTF7.GetBytesTest("abc", 0, 0, 1, 1, new Byte[] { 0x00 }, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 0, 1, 2, (Byte[])null, 0));
s_encodingUtil_UTF7.GetBytesTest("abc", 0, 3, 5, 1, new Byte[] { 0x00, 0x61, 0x62, 0x63, 0x00 }, 3);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 0, -1, -1, (Byte[])null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest("abc", 0, 1, -1, -1, (Byte[])null, 0));
s_encodingUtil_UTF7.GetBytesTest(String.Empty, 0, 0, -1, 0, new Byte[] { }, 0);
s_encodingUtil_UTF7.GetBytesTest(String.Empty, 0, 0, 0, 0, new Byte[] { }, 0);
s_encodingUtil_UTF7.GetBytesTest("a", 0, 0, 1, 0, new Byte[] { 0x00 }, 0);
}
[Fact]
public static void GetChars_BufferBoundary_Pointer()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetCharsTest((Byte[])null, 0, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, -1, 0, 0, String.Empty, 0));
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, 0, -2, 0, (String)null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, 0, 0, -1, String.Empty, 0));
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, 0, 0, 0, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { }, 0, -1, -100, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61 }, 0, 1, 1, "\u0000", 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61 }, 1, -1, -100, "a", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61 }, 1, 2, 2, "\u0061\u0000", 1);
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x61 }, 1, 0, 0, String.Empty, 0));
}
[Fact]
public static void GetBytes_BufferBoundary_Pointer()
{
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetBytesTest((String)null, 0, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest(String.Empty, -1, 0, 0, new Byte[] { }, 0));
Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF7.GetBytesTest(String.Empty, 0, -2, 0, (Byte[])null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetBytesTest(String.Empty, 0, 0, -1, new Byte[] { }, 0));
s_encodingUtil_UTF7.GetBytesTest(String.Empty, 0, 0, 0, new Byte[] { }, 0);
s_encodingUtil_UTF7.GetBytesTest(String.Empty, 0, -1, -100, new Byte[] { }, 0);
s_encodingUtil_UTF7.GetBytesTest("a", 0, 1, 1, new Byte[] { 0x00 }, 0);
s_encodingUtil_UTF7.GetBytesTest("a", 1, -1, -100, new Byte[] { 0x61 }, 1);
s_encodingUtil_UTF7.GetBytesTest("a", 1, 2, 2, new Byte[] { 0x61, 0x00 }, 1);
Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF7.GetBytesTest("a", 1, 0, 0, new Byte[] { }, 0));
}
[Fact]
public static void CorrectClassesOfInput()
{
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x41, 0x09, 0x0D, 0x0A, 0x20, 0x2F, 0x7A }, 0, 7, -1, 0, "A\t\r\n /z", 7);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x41, 0x09, 0x0D, 0x0A, 0x20, 0x2F, 0x7A }, 0, 7, 7);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x45, 0x45, 0x41, 0x43, 0x51 }, 0, 7, -1, 0, "A\t", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x41, 0x45, 0x45, 0x41, 0x43, 0x51 }, 0, 7, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51 }, 0, 7, -1, 0, "!}", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51 }, 0, 7, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D }, 0, 8, -1, 0, "!}", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D }, 0, 8, 2);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x21, 0x7D }, 0, 2, -1, 0, "!}", 2);
s_encodingUtil_UTF7.GetCharCountTest(true, false, new Byte[] { 0x21, 0x7D }, 0, 2, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D }, 1, 2, -1, 0, "AC", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D }, 1, 2, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 0, 8, -1, 0, "\u0E59\u05D1", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51 }, 0, 7, 2);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 0, 8, -1, 0, "\u0E59\u05D1", 2);
s_encodingUtil_UTF7.GetCharCountTest(true, false, new Byte[] { 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51 }, 0, 7, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x41, 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D, 0x09, 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 0, 18, -1, 0, "\u0041\u0021\u007D\u0009\u0E59\u05D1", 6);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x41, 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D, 0x09, 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51 }, 0, 17, 6);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x41, 0x21, 0x7D, 0x09, 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 0, 12, -1, 0, "\u0041\u0021\u007D\u0009\u0E59\u05D1", 6);
s_encodingUtil_UTF7.GetCharCountTest(true, false, new Byte[] { 0x41, 0x21, 0x7D, 0x09, 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51 }, 0, 11, 6);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x32, 0x41, 0x41, 0x2D }, 0, 5, -1, 0, "\uD800", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x33, 0x2F, 0x38, 0x2D }, 0, 5, -1, 0, "\uDFFF", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x32, 0x41, 0x44, 0x66, 0x2F, 0x77, 0x2D }, 0, 8, -1, 0, "\uD800\uDFFF", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x2D }, 0, 2, -1, 0, "+", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x2D, 0x41 }, 0, 3, -1, 0, "+A", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x2B, 0x41, 0x41, 0x2D }, 0, 5, -1, 0, "\uF800", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2D }, 0, 1, -1, 0, "-", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x2D, 0x2D }, 0, 3, -1, 0, "+-", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x09 }, 0, 2, -1, 0, "\t", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x09, 0x2D }, 0, 3, -1, 0, "\t-", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x1E, 0x2D }, 0, 3, -1, 0, "
-", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x7F, 0x1E, 0x2D }, 0, 4, -1, 0, "
-", 3);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, -1, 0, "!-", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x80, 0x81 }, 0, 2, -1, 0, "\u0080\u0081", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x80, 0x81 }, 0, 2, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x1E }, 0, 1, -1, 0, "
", 1);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x1E }, 0, 1, 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x21 }, 0, 1, -1, 0, "!", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, -1, 0, "!-", 2);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, -1, 0, "!-", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x21, 0x41, 0x41, 0x2D }, 0, 5, -1, 0, "!AA-", 4);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x2B, 0x21, 0x41, 0x41, 0x2D }, 0, 5, -1, 0, "!AA-", 4);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x80, 0x81, 0x82, 0x2D }, 0, 5, -1, 0, "\u0080\u0081\u0082-", 4);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x80, 0x81, 0x82, 0x2D }, 0, 5, 4);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x80, 0x81, 0x82, 0x2D }, 0, 4, -1, 0, "\u0080\u0081\u0082", 3);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x80, 0x81, 0x82, 0x2D }, 0, 4, 3);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x2D }, 0, 5, -1, 0, "!", 1);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x21 }, 0, 1, -1, 0, "!", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B }, 0, 1, -1, 0, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x2D }, 0, 5, -1, 0, "!", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x2D }, 0, 2, -1, 0, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x2D }, 0, 3, -1, 0, String.Empty, 0);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x48, 0x2D }, 0, 5, -1, 0, "!", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x48, 0x35, 0x41, 0x41, 0x2D }, 0, 8, -1, 0, "\u0021\uF900", 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x41, 0x43, 0x48, 0x35, 0x41, 0x41, 0x2D }, 0, 4, -1, 0, "!", 1);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x80, 0x81, 0x82, 0x2D }, 0, 5, -1, 0, "\u0080\u0081\u0082-", 4);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x80, 0x81, 0x82, 0x2D }, 0, 5, 4);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x09, 0x2D }, 0, 3, -1, 0, "\t-", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x09, 0x2D }, 0, 3, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, -1, 0, "!-", 2);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, 2);
s_encodingUtil_UTF7.GetCharsTest(true, false, new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, -1, 0, "!-", 2);
s_encodingUtil_UTF7.GetCharCountTest(true, false, new Byte[] { 0x2B, 0x21, 0x2D }, 0, 3, 2);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x21, 0x80, 0x21, 0x2D }, 0, 5, -1, 0, "!\u0080!-", 4);
s_encodingUtil_UTF7.GetCharsTest(new Byte[] { 0x2B, 0x80, 0x21, 0x80, 0x21, 0x1E, 0x2D }, 0, 7, -1, 0, "\u0080!\u0080!
-", 6);
s_encodingUtil_UTF7.GetCharCountTest(new Byte[] { 0x2B, 0x21, 0x80, 0x21, 0x2D }, 0, 5, 4);
s_encodingUtil_UTF7.GetBytesTest("A\t\r\n /z", 0, 7, -1, 0, new Byte[] { 0x41, 0x09, 0x0D, 0x0A, 0x20, 0x2F, 0x7A }, 7);
s_encodingUtil_UTF7.GetByteCountTest("A\t\r\n /z", 0, 7, 7);
s_encodingUtil_UTF7.GetBytesTest("!}", 0, 2, -1, 0, new Byte[] { 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D }, 8);
s_encodingUtil_UTF7.GetByteCountTest("!}", 0, 2, 8);
s_encodingUtil_UTF7.GetBytesTest(true, false, "!}", 0, 2, -1, 0, new Byte[] { 0x21, 0x7D }, 2);
s_encodingUtil_UTF7.GetByteCountTest(true, false, "!}", 0, 2, 2);
s_encodingUtil_UTF7.GetBytesTest("
", 0, 1, -1, 0, new Byte[] { 0x2B, 0x41, 0x41, 0x77, 0x2D }, 5);
s_encodingUtil_UTF7.GetBytesTest("\u212B", 0, 1, -1, 0, new Byte[] { 0x2B, 0x49, 0x53, 0x73, 0x2D }, 5);
s_encodingUtil_UTF7.GetBytesTest("!}", 1, 1, -1, 0, new Byte[] { 0x2B, 0x41, 0x48, 0x30, 0x2D }, 5);
s_encodingUtil_UTF7.GetByteCountTest("!}", 1, 1, 5);
s_encodingUtil_UTF7.GetBytesTest("\u0E59\u05D1", 0, 2, -1, 0, new Byte[] { 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 8);
s_encodingUtil_UTF7.GetByteCountTest("\u0E59\u05D1", 0, 2, 8);
s_encodingUtil_UTF7.GetBytesTest(true, false, "\u0E59\u05D1", 0, 2, -1, 0, new Byte[] { 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 8);
s_encodingUtil_UTF7.GetByteCountTest(true, false, "\u0E59\u05D1", 0, 2, 8);
s_encodingUtil_UTF7.GetBytesTest("\u0041\u0021\u007D\u0009\u0E59\u05D1", 0, 6, -1, 0, new Byte[] { 0x41, 0x2B, 0x41, 0x43, 0x45, 0x41, 0x66, 0x51, 0x2D, 0x09, 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 18);
s_encodingUtil_UTF7.GetByteCountTest("\u0041\u0021\u007D\u0009\u0E59\u05D1", 0, 6, 18);
s_encodingUtil_UTF7.GetBytesTest(true, false, "\u0041\u0021\u007D\u0009\u0E59\u05D1", 0, 6, -1, 0, new Byte[] { 0x41, 0x21, 0x7D, 0x09, 0x2B, 0x44, 0x6C, 0x6B, 0x46, 0x30, 0x51, 0x2D }, 12);
s_encodingUtil_UTF7.GetByteCountTest(true, false, "\u0041\u0021\u007D\u0009\u0E59\u05D1", 0, 6, 12);
s_encodingUtil_UTF7.GetBytesTest("\uD800", 0, 1, -1, 0, new Byte[] { 0x2B, 0x32, 0x41, 0x41, 0x2D }, 5);
s_encodingUtil_UTF7.GetBytesTest("\uDFFF", 0, 1, -1, 0, new Byte[] { 0x2B, 0x33, 0x2F, 0x38, 0x2D }, 5);
s_encodingUtil_UTF7.GetBytesTest("\uD800\uDFFF", 0, 2, -1, 0, new Byte[] { 0x2B, 0x32, 0x41, 0x44, 0x66, 0x2F, 0x77, 0x2D }, 8);
s_encodingUtil_UTF7.GetBytesTest("+-", 0, 2, -1, 0, new Byte[] { 0x2B, 0x2D, 0x2D }, 3);
s_encodingUtil_UTF7.GetByteCountTest("+-", 0, 2, 3);
s_encodingUtil_UTF7.GetBytesTest("-", 0, 1, -1, 0, new Byte[] { 0x2D }, 1);
s_encodingUtil_UTF7.GetBytesTest("+-", 0, 2, -1, 0, new Byte[] { 0x2B, 0x2D, 0x2D }, 3);
}
[Fact]
public static void MaxCharCount()
{
s_encodingUtil_UTF7.GetMaxCharCountTest(0, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxCharCountTest(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxCharCountTest(-2147483648, 0));
s_encodingUtil_UTF7.GetMaxCharCountTest(2147483647, 2147483647);
s_encodingUtil_UTF7.GetMaxCharCountTest(10, 10);
}
[Fact]
public static void MaxByteCount()
{
s_encodingUtil_UTF7.GetMaxByteCountTest(0, 2);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxByteCountTest(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxByteCountTest(-2147483648, 0));
s_encodingUtil_UTF7.GetMaxByteCountTest(268435455, 805306367);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxByteCountTest(2147483647, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxByteCountTest(1717986918, 0));
s_encodingUtil_UTF7.GetMaxByteCountTest(10, 32);
s_encodingUtil_UTF7.GetMaxByteCountTest(715827881, 2147483645);
Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF7.GetMaxByteCountTest(805306367, 0));
}
[Fact]
public static void Preamble()
{
s_encodingUtil_UTF7.GetPreambleTest(new Byte[] { });
}
}
}
| |
using System.Drawing;
using System.Drawing.Imaging;
using Hydra.Framework.ImageProcessing.Analysis;
using Hydra.Framework.ImageProcessing.Analysis.Maths;
namespace Hydra.Framework.ImageProcessing.Analysis.Filters
{
//
//**********************************************************************
/// <summary>
/// LevelsLinear filter
/// </summary>
//**********************************************************************
//
public class LevelsLinear
: IFilter
{
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Input Red
/// </summary>
//**********************************************************************
//
private Range inRed_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Input Green
/// </summary>
//**********************************************************************
//
private Range inGreen_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Input Blue
/// </summary>
//**********************************************************************
//
private Range inBlue_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Output Red
/// </summary>
//**********************************************************************
//
private Range outRed_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Output Green
/// </summary>
//**********************************************************************
//
private Range outGreen_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Output Blue
/// </summary>
//**********************************************************************
//
private Range outBlue_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Map Red
/// </summary>
//**********************************************************************
//
private byte[] mapRed_m = new byte[256];
//
//**********************************************************************
/// <summary>
/// Map Green
/// </summary>
//**********************************************************************
//
private byte[] mapGreen_m = new byte[256];
//
//**********************************************************************
/// <summary>
/// Map Blue
/// </summary>
//**********************************************************************
//
private byte[] mapBlue_m = new byte[256];
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:LevelsLinear"/> class.
/// </summary>
//**********************************************************************
//
public LevelsLinear()
{
CalculateMap(inRed_m, outRed_m, mapRed_m);
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
CalculateMap(inBlue_m, outBlue_m, mapBlue_m);
}
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the Input properties (Red).
/// </summary>
/// <value>The in red.</value>
//**********************************************************************
//
public Range InRed
{
get
{
return inRed_m;
}
set
{
inRed_m = value;
CalculateMap(inRed_m, outRed_m, mapRed_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Input properties (Green).
/// </summary>
/// <value>The in green.</value>
//**********************************************************************
//
public Range InGreen
{
get
{
return inGreen_m;
}
set
{
inGreen_m = value;
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Input properties (Blue).
/// </summary>
/// <value>The in blue.</value>
//**********************************************************************
//
public Range InBlue
{
get
{
return inBlue_m;
}
set
{
inBlue_m = value;
CalculateMap(inBlue_m, outBlue_m, mapBlue_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Input properties (Gray).
/// </summary>
/// <value>The in gray.</value>
//**********************************************************************
//
public Range InGray
{
get
{
return inGreen_m;
}
set
{
inGreen_m = value;
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Sets the input range.
/// </summary>
/// <value>The input range.</value>
//**********************************************************************
//
public Range Input
{
set
{
inRed_m = value;
inGreen_m = value;
inBlue_m = value;
CalculateMap(inRed_m, outRed_m, mapRed_m);
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
CalculateMap(inBlue_m, outBlue_m, mapBlue_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Output properties (Red).
/// </summary>
/// <value>The out red.</value>
//**********************************************************************
//
public Range OutRed
{
get
{
return outRed_m;
}
set
{
outRed_m = value;
CalculateMap(inRed_m, outRed_m, mapRed_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Output properties (Green).
/// </summary>
/// <value>The out green.</value>
//**********************************************************************
//
public Range OutGreen
{
get
{
return outGreen_m;
}
set
{
outGreen_m = value;
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Output properties (Blue).
/// </summary>
/// <value>The out blue.</value>
//**********************************************************************
//
public Range OutBlue
{
get
{
return outBlue_m;
}
set
{
outBlue_m = value;
CalculateMap(inBlue_m, outBlue_m, mapBlue_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the Output properties (Gray).
/// </summary>
/// <value>The out gray.</value>
//**********************************************************************
//
public Range OutGray
{
get
{
return outGreen_m;
}
set
{
outGreen_m = value;
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Sets the output Range
/// </summary>
/// <value>The output Range.</value>
//**********************************************************************
//
public Range Output
{
set
{
outRed_m = value;
outGreen_m = value;
outBlue_m = value;
CalculateMap(inRed_m, outRed_m, mapRed_m);
CalculateMap(inGreen_m, outGreen_m, mapGreen_m);
CalculateMap(inBlue_m, outBlue_m, mapBlue_m);
}
}
#endregion
#region Private Methods
//
//**********************************************************************
/// <summary>
/// Calculates the map.
/// </summary>
/// <param name="inRange">The in range.</param>
/// <param name="outRange">The out range.</param>
/// <param name="map">The map.</param>
//**********************************************************************
//
private void CalculateMap(Range inRange, Range outRange, byte[] map)
{
double k = 0;
double b = 0;
if (inRange.Max != inRange.Min)
{
k = (double)(outRange.Max - outRange.Min) / (double)(inRange.Max - inRange.Min);
b = (double)(outRange.Min) - k * inRange.Min;
}
for (int i = 0; i < 256; i++)
{
byte v = (byte)i;
if (v >= inRange.Max)
v = (byte)outRange.Max;
else if (v <= inRange.Min)
v = (byte)outRange.Min;
else
v = (byte)(k * v + b);
map[i] = v;
}
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// Apply filter
/// </summary>
/// <param name="srcImg">The SRC img.</param>
/// <returns></returns>
//**********************************************************************
//
public Bitmap Apply(Bitmap srcImg)
{
//
// get source image size
//
int width = srcImg.Width;
int height = srcImg.Height;
PixelFormat fmt = (srcImg.PixelFormat == PixelFormat.Format8bppIndexed) ?
PixelFormat.Format8bppIndexed : PixelFormat.Format24bppRgb;
//
// lock source bitmap data
//
BitmapData srcData = srcImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, fmt);
//
// create new image
//
Bitmap dstImg = (fmt == PixelFormat.Format8bppIndexed) ?
Hydra.Framework.ImageProcessing.Analysis.Image.CreateGrayscaleImage(width, height) :
new Bitmap(width, height, fmt);
//
// lock destination bitmap data
//
BitmapData dstData = dstImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, fmt);
int offset = srcData.Stride - ((fmt == PixelFormat.Format8bppIndexed) ? width : width * 3);
//
// do the job (Warning Unsafe Code)
//
unsafe
{
byte* src = (byte*)srcData.Scan0.ToPointer();
byte* dst = (byte*)dstData.Scan0.ToPointer();
if (fmt == PixelFormat.Format8bppIndexed)
{
//
// grayscale image
//
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, src++, dst++)
{
//
// gray
//
*dst = mapGreen_m[*src];
}
src += offset;
dst += offset;
}
}
else
{
//
// RGB image
//
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, src += 3, dst += 3)
{
//
// red
//
dst[RGB.R] = mapRed_m[src[RGB.R]];
//
// green
//
dst[RGB.G] = mapGreen_m[src[RGB.G]];
//
// blue
//
dst[RGB.B] = mapBlue_m[src[RGB.B]];
}
src += offset;
dst += offset;
}
}
}
//
// unlock both images
//
dstImg.UnlockBits(dstData);
srcImg.UnlockBits(srcData);
return dstImg;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyByte
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ByteModel operations.
/// </summary>
public partial class ByteModel : IServiceOperations<AutoRestSwaggerBATByteService>, IByteModel
{
/// <summary>
/// Initializes a new instance of the ByteModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ByteModel(AutoRestSwaggerBATByteService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATByteService
/// </summary>
public AutoRestSwaggerBATByteService Client { get; private set; }
/// <summary>
/// Get null byte value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<byte[]>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/null").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<byte[]>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get empty byte value ''
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<byte[]>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/empty").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<byte[]>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6)
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<byte[]>> GetNonAsciiWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNonAscii", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/nonAscii").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<byte[]>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6)
/// </summary>
/// <param name='byteBody'>
/// Base64-encoded non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6)
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutNonAsciiWithHttpMessagesAsync(byte[] byteBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (byteBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "byteBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("byteBody", byteBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutNonAscii", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/nonAscii").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(byteBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(byteBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid byte value ':::SWAGGER::::'
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<byte[]>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/invalid").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<byte[]>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
namespace DukptNet
{
public static class Dukpt
{
#region Private Mask Constants
private static readonly BigInteger Reg3Mask = "1FFFFF".HexToBigInteger();
private static readonly BigInteger ShiftRegMask = "100000".HexToBigInteger();
private static readonly BigInteger Reg8Mask = "FFFFFFFFFFE00000".HexToBigInteger();
private static readonly BigInteger Ls16Mask = "FFFFFFFFFFFFFFFF".HexToBigInteger();
private static readonly BigInteger Ms16Mask = "FFFFFFFFFFFFFFFF0000000000000000".HexToBigInteger();
private static readonly BigInteger KeyMask = "C0C0C0C000000000C0C0C0C000000000".HexToBigInteger();
private static readonly BigInteger PekMask = "FF00000000000000FF".HexToBigInteger();
private static readonly BigInteger KsnMask = "FFFFFFFFFFFFFFE00000".HexToBigInteger();
private static readonly BigInteger DekMask = "0000000000FF00000000000000FF0000".HexToBigInteger();
#endregion
#region Private Methods
/// <summary>
/// Create Initial PIN Encryption Key
/// </summary>
/// <param name="ksn">Key Serial Number</param>
/// <param name="bdk">Base Derivation Key</param>
/// <returns>Initial PIN Encryption Key</returns>
private static BigInteger CreateIpek(BigInteger ksn, BigInteger bdk)
{
return Transform("TripleDES", true, bdk, (ksn & KsnMask) >> 16) << 64
| Transform("TripleDES", true, bdk ^ KeyMask, (ksn & KsnMask) >> 16);
}
/// <summary>
/// Create Session Key with PEK Mask
/// </summary>
/// <param name="ipek">Initial PIN Encryption Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <returns>Session Key</returns>
private static BigInteger CreateSessionKeyPEK(BigInteger ipek, BigInteger ksn)
{
return DeriveKey(ipek, ksn) ^ PekMask;
}
/// <summary>
/// Create Session Key with DEK Mask
/// </summary>
/// <param name="ipek">Initial PIN Encryption Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <returns>Session Key</returns>
private static BigInteger CreateSessionKeyDEK(BigInteger ipek, BigInteger ksn)
{
BigInteger key = DeriveKey(ipek, ksn) ^ DekMask;
return Transform("TripleDES", true, key, (key & Ms16Mask) >> 64) << 64
| Transform("TripleDES", true, key, (key & Ls16Mask));
}
/// <summary>
/// Create Session Key
/// </summary>
/// <param name="bdk">Base Derivation Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <param name="DUKPTVariant">DUKPT variant used to determine session key creation method</param>
/// <returns>Session Key</returns>
private static BigInteger CreateSessionKey(string bdk, string ksn, DUKPTVariant DUKPTVariant)
{
BigInteger ksnBigInt = ksn.HexToBigInteger();
BigInteger ipek = CreateIpek(ksnBigInt, bdk.HexToBigInteger());
BigInteger sessionKey;
if (DUKPTVariant == DUKPTVariant.Data)
{
sessionKey = CreateSessionKeyDEK(ipek, ksnBigInt);
}
else
{
sessionKey = CreateSessionKeyPEK(ipek, ksnBigInt);
}
return sessionKey;
}
/// <summary>
/// Derive Key from IPEK and KSN
/// </summary>
/// <param name="ipek">Initial PIN Encryption Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <returns>Key derived from IPEK and KSN</returns>
private static BigInteger DeriveKey(BigInteger ipek, BigInteger ksn)
{
BigInteger ksnReg = ksn & Ls16Mask & Reg8Mask;
BigInteger curKey = ipek;
for (BigInteger shiftReg = ShiftRegMask; shiftReg > 0; shiftReg >>= 1)
{
if ((shiftReg & ksn & Reg3Mask) > 0)
{
ksnReg = ksnReg | shiftReg;
curKey = GenerateKey(curKey, ksnReg);
}
}
return curKey;
}
/// <summary>
/// Generate Key
/// </summary>
/// <param name="key">Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <returns>Key generated from provided key and KSN</returns>
private static BigInteger GenerateKey(BigInteger key, BigInteger ksn)
{
return EncryptRegister(key ^ KeyMask, ksn) << 64 | EncryptRegister(key, ksn);
}
/// <summary>
/// Encrypt Register
/// </summary>
/// <param name="key">Key</param>
/// <param name="reg8">Register which to encrypt</param>
/// <returns>Encrypted register value</returns>
private static BigInteger EncryptRegister(BigInteger key, BigInteger reg8)
{
return (key & Ls16Mask) ^ Transform("DES", true, (key & Ms16Mask) >> 64, (key & Ls16Mask ^ reg8));
}
/// <summary>
/// Transform Data
/// </summary>
/// <param name="name">Encryption algorithm name</param>
/// <param name="encrypt">Encrypt data flag</param>
/// <param name="key">Encryption key</param>
/// <param name="message">Data to encrypt or decrypt</param>
/// <returns>Result of transformation (encryption or decryption)</returns>
private static BigInteger Transform(string name, bool encrypt, BigInteger key, BigInteger message)
{
using (SymmetricAlgorithm cipher = SymmetricAlgorithm.Create(name))
{
byte[] k = key.GetBytes();
cipher.Key = new byte[Math.Max(0, GetNearestWholeMultiple(k.Length, 8) - k.Length)].Concat(key.GetBytes()).ToArray();
cipher.IV = new byte[8];
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.Zeros;
using (ICryptoTransform crypto = encrypt ? cipher.CreateEncryptor() : cipher.CreateDecryptor())
{
byte[] data = message.GetBytes();
data = new byte[Math.Max(0, GetNearestWholeMultiple(data.Length, 8) - data.Length)].Concat(message.GetBytes()).ToArray();
return crypto.TransformFinalBlock(data, 0, data.Length).ToBigInteger();
}
}
}
/// <summary>
/// Get nearest whole value of provided decimal value which is a multiple of provided integer
/// </summary>
/// <param name="input">Number which to determine nearest whole multiple</param>
/// <param name="multiple">Multiple in which to divide input</param>
/// <returns>Whole integer value of input nearest to a multiple of provided decimal</returns>
private static int GetNearestWholeMultiple(decimal input, int multiple)
{
decimal output = Math.Round(input / multiple);
if (output == 0 && input > 0)
{
output += 1;
}
output *= multiple;
return (int)output;
}
#endregion
#region Public Methods
/// <summary>
/// Encrypt data using TDES DUKPT.
/// </summary>
/// <param name="bdk">Base Derivation Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <param name="data">Data to encrypt</param>
/// <param name="variant">DUKPT transaction key variant</param>
/// <returns>Encrypted data</returns>
/// <exception cref="ArgumentNullException">Thrown for null or empty parameter values</exception>
public static byte[] Encrypt(string bdk, string ksn, byte[] data, DUKPTVariant variant)
{
if (string.IsNullOrEmpty(bdk))
{
throw new ArgumentNullException(nameof(bdk));
}
if (string.IsNullOrEmpty(ksn))
{
throw new ArgumentNullException(nameof(ksn));
}
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
return Transform("TripleDES", true, CreateSessionKey(bdk, ksn, variant), data.ToBigInteger()).GetBytes();
}
/// <summary>
/// Encrypt data using TDES DUKPT PIN variant.
/// </summary>
/// <param name="bdk">Base Derivation Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <param name="data">Data to encrypt</param>
/// <returns>Encrypted data</returns>
/// <exception cref="ArgumentNullException">Thrown for null or empty parameter values</exception>
public static byte[] Encrypt(string bdk, string ksn, byte[] data)
{
return Encrypt(bdk, ksn, data, DUKPTVariant.PIN);
}
/// <summary>
/// Decrypt data using TDES DUKPT.
/// </summary>
/// <param name="bdk">Base Derivation Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <param name="encryptedData">Data to decrypt</param>
/// <param name="variant">DUKPT transaction key variant</param>
/// <returns>Decrypted data</returns>
/// <exception cref="ArgumentNullException">Thrown for null or empty parameter values</exception>
public static byte[] Decrypt(string bdk, string ksn, byte[] encryptedData, DUKPTVariant variant)
{
if (string.IsNullOrEmpty(bdk))
{
throw new ArgumentNullException(nameof(bdk));
}
if (string.IsNullOrEmpty(ksn))
{
throw new ArgumentNullException(nameof(ksn));
}
if (encryptedData == null)
{
throw new ArgumentNullException(nameof(encryptedData));
}
return Transform("TripleDES", false, CreateSessionKey(bdk, ksn, variant), encryptedData.ToBigInteger()).GetBytes();
}
/// <summary>
/// Decrypt data using TDES DUKPT PIN variant.
/// </summary>
/// <param name="bdk">Base Derivation Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <param name="encryptedData">Data to decrypt</param>
/// <returns>Decrypted data</returns>
/// <exception cref="ArgumentNullException">Thrown for null or empty parameter values</exception>
public static byte[] Decrypt(string bdk, string ksn, byte[] encryptedData)
{
return Decrypt(bdk, ksn, encryptedData, DUKPTVariant.PIN);
}
/// <summary>
/// Decrypt data using TDES DUKPT Data variant.
/// Backwards-compatible with previous versions of Dukpt.NET.
/// </summary>
/// <param name="bdk">Base Derivation Key</param>
/// <param name="ksn">Key Serial Number</param>
/// <param name="data">Data to decrypt</param>
/// <returns>Decrypted data</returns>
public static byte[] DecryptIdTech(string bdk, string ksn, byte[] encryptedData)
{
return Decrypt(bdk, ksn, encryptedData, DUKPTVariant.Data);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using System;
namespace UMA.CharacterSystem.Editors
{
[CustomEditor(typeof(DynamicCharacterAvatar), true)]
public partial class DynamicCharacterAvatarEditor : Editor
{
public bool showHelp = false;
protected DynamicCharacterAvatar thisDCA;
protected RaceSetterPropertyDrawer _racePropDrawer = new RaceSetterPropertyDrawer();
protected WardrobeRecipeListPropertyDrawer _wardrobePropDrawer = new WardrobeRecipeListPropertyDrawer();
protected RaceAnimatorListPropertyDrawer _animatorPropDrawer = new RaceAnimatorListPropertyDrawer();
public void OnEnable()
{
thisDCA = target as DynamicCharacterAvatar;
if (thisDCA.context == null)
{
thisDCA.context = UMAContext.FindInstance();
if (thisDCA.context == null)
{
thisDCA.context = thisDCA.CreateEditorContext();
}
}
else if (thisDCA.context.gameObject.name == "UMAEditorContext")
{
//this will set also the existing Editorcontext if there is one
thisDCA.CreateEditorContext();
}
else if (thisDCA.context.gameObject.transform.parent != null)
{
//this will set also the existing Editorcontext if there is one
if (thisDCA.context.gameObject.transform.parent.gameObject.name == "UMAEditorContext")
thisDCA.CreateEditorContext();
}
_racePropDrawer.thisDCA = thisDCA;
_racePropDrawer.thisDynamicRaceLibrary = (DynamicRaceLibrary)thisDCA.context.raceLibrary as DynamicRaceLibrary;
_wardrobePropDrawer.thisDCA = thisDCA;
_wardrobePropDrawer.thisDCS = (DynamicCharacterSystem)thisDCA.context.dynamicCharacterSystem as DynamicCharacterSystem;
_animatorPropDrawer.thisDCA = thisDCA;
}
public void SetNewColorCount(int colorCount)
{
var newcharacterColors = new List<DynamicCharacterAvatar.ColorValue>();
for (int i = 0; i < colorCount; i++)
{
if (thisDCA.characterColors.Colors.Count > i)
{
newcharacterColors.Add(thisDCA.characterColors.Colors[i]);
}
else
{
newcharacterColors.Add(new DynamicCharacterAvatar.ColorValue(3));
}
}
thisDCA.characterColors.Colors = newcharacterColors;
}
protected bool characterAvatarLoadSaveOpen;
public override void OnInspectorGUI()
{
serializedObject.Update();
Editor.DrawPropertiesExcluding(serializedObject, new string[] { "hide", "loadBlendShapes","activeRace","defaultChangeRaceOptions","cacheCurrentState", "rebuildSkeleton", "preloadWardrobeRecipes", "raceAnimationControllers",
"characterColors","BoundsOffset","_buildCharacterEnabled",
/*LoadOtions fields*/ "defaultLoadOptions", "loadPathType", "loadPath", "loadFilename", "loadString", "loadFileOnStart", "waitForBundles", /*"buildAfterLoad",*/
/*SaveOptions fields*/ "defaultSaveOptions", "savePathType","savePath", "saveFilename", "makeUniqueFilename","ensureSharedColors",
/*Moved into AdvancedOptions*/"context","umaData","umaRecipe", "umaAdditionalRecipes","umaGenerator", "animationController",
/*Moved into CharacterEvents*/"CharacterCreated", "CharacterUpdated", "CharacterDestroyed", "CharacterDnaUpdated", "RecipeUpdated",
/*PlaceholderOptions fields*/"showPlaceholder", "previewModel", "customModel", "customRotation", "previewColor"});
//The base DynamicAvatar properties- get these early because changing the race changes someof them
SerializedProperty context = serializedObject.FindProperty("context");
SerializedProperty umaData = serializedObject.FindProperty("umaData");
SerializedProperty umaGenerator = serializedObject.FindProperty("umaGenerator");
SerializedProperty umaRecipe = serializedObject.FindProperty("umaRecipe");
SerializedProperty umaAdditionalRecipes = serializedObject.FindProperty("umaAdditionalRecipes");
SerializedProperty animationController = serializedObject.FindProperty("animationController");
EditorGUI.BeginChangeCheck();
showHelp = EditorGUILayout.Toggle("Show Help", showHelp);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty thisRaceSetter = serializedObject.FindProperty("activeRace");
Rect currentRect = EditorGUILayout.GetControlRect(false, _racePropDrawer.GetPropertyHeight(thisRaceSetter, GUIContent.none));
EditorGUI.BeginChangeCheck();
_racePropDrawer.OnGUI(currentRect, thisRaceSetter, new GUIContent(thisRaceSetter.displayName));
if (EditorGUI.EndChangeCheck())
{
thisDCA.ChangeRace((string)thisRaceSetter.FindPropertyRelative("name").stringValue);
//Changing the race may cause umaRecipe, animationController to change so forcefully update these too
umaRecipe.objectReferenceValue = thisDCA.umaRecipe;
animationController.objectReferenceValue = thisDCA.animationController;
serializedObject.ApplyModifiedProperties();
}
if (showHelp)
{
EditorGUILayout.HelpBox("Active Race: Sets the race of the character, which defines the base recipe to build the character, the available DNA, and the available wardrobe.", MessageType.Info);
}
//the ChangeRaceOptions
SerializedProperty defaultChangeRaceOptions = serializedObject.FindProperty("defaultChangeRaceOptions");
EditorGUI.indentLevel++;
defaultChangeRaceOptions.isExpanded = EditorGUILayout.Foldout(defaultChangeRaceOptions.isExpanded, new GUIContent("Race Change Options", "The default options for when the Race is changed. These can be overidden when calling 'ChangeRace' directly."));
if (defaultChangeRaceOptions.isExpanded)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(defaultChangeRaceOptions, GUIContent.none);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(serializedObject.FindProperty("cacheCurrentState"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("rebuildSkeleton"));
EditorGUI.indentLevel--;
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.indentLevel--;
//Other DCA propertyDrawers
//in order for the "preloadWardrobeRecipes" prop to properly check if it can load the recipies it gets assigned to it
//it needs to know that its part of this DCA
GUILayout.Space(2f);
SerializedProperty thisPreloadWardrobeRecipes = serializedObject.FindProperty("preloadWardrobeRecipes");
Rect pwrCurrentRect = EditorGUILayout.GetControlRect(false, _wardrobePropDrawer.GetPropertyHeight(thisPreloadWardrobeRecipes, GUIContent.none));
_wardrobePropDrawer.OnGUI(pwrCurrentRect, thisPreloadWardrobeRecipes, new GUIContent(thisPreloadWardrobeRecipes.displayName));
if (showHelp)
{
EditorGUILayout.HelpBox("Preload Wardrobe: Sets the default wardrobe recipes to use on the Avatar. This is useful when creating specific Avatar prefabs.", MessageType.Info);
}
if (_wardrobePropDrawer.changed)
{
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying)
{
thisDCA.ClearSlots();
thisDCA.LoadDefaultWardrobe();
thisDCA.BuildCharacter(true);
}
}
SerializedProperty thisRaceAnimationControllers = serializedObject.FindProperty("raceAnimationControllers");
Rect racCurrentRect = EditorGUILayout.GetControlRect(false, _animatorPropDrawer.GetPropertyHeight(thisRaceAnimationControllers, GUIContent.none));
EditorGUI.BeginChangeCheck();
_animatorPropDrawer.OnGUI(racCurrentRect, thisRaceAnimationControllers, new GUIContent(thisRaceAnimationControllers.displayName));
if (showHelp)
{
EditorGUILayout.HelpBox("Race Animation Controllers: This sets the animation controllers used for each race. When changing the race, the animation controller for the active race will be used by default.", MessageType.Info);
}
//EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(serializedObject.FindProperty("raceAnimationControllers"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying)
{
thisDCA.SetExpressionSet();//this triggers any expressions to reset.
thisDCA.SetAnimatorController();
}
}
GUILayout.Space(2f);
//NewCharacterColors
SerializedProperty characterColors = serializedObject.FindProperty("characterColors");
SerializedProperty newCharacterColors = characterColors.FindPropertyRelative("_colors");
//for ColorValues as OverlayColorDatas we need to outout something that looks like a list but actully uses a method to add/remove colors because we need the new OverlayColorData to have 3 channels
newCharacterColors.isExpanded = EditorGUILayout.Foldout(newCharacterColors.isExpanded, new GUIContent("Character Colors"));
var n_origArraySize = newCharacterColors.arraySize;
var n_newArraySize = n_origArraySize;
EditorGUI.BeginChangeCheck();
if (newCharacterColors.isExpanded)
{
n_newArraySize = EditorGUILayout.DelayedIntField(new GUIContent("Size"), n_origArraySize);
EditorGUILayout.Space();
EditorGUI.indentLevel++;
if (n_origArraySize > 0)
{
for(int i = 0; i < n_origArraySize; i++)
{
EditorGUILayout.PropertyField(newCharacterColors.GetArrayElementAtIndex(i));
}
}
EditorGUI.indentLevel--;
}
if (showHelp)
{
EditorGUILayout.HelpBox("Character Colors: This lets you set predefined colors to be used when building the Avatar. The colors will be assigned to the Shared Colors on the overlays as they are applied to the Avatar.", MessageType.Info);
}
if (EditorGUI.EndChangeCheck())
{
if (n_newArraySize != n_origArraySize)
{
SetNewColorCount(n_newArraySize);//this is not prompting a save so mark the scene dirty...
if (!Application.isPlaying)
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying)
thisDCA.UpdateColors(true);
}
GUILayout.Space(2f);
//Load save fields
EditorGUI.BeginChangeCheck();
SerializedProperty loadPathType = serializedObject.FindProperty("loadPathType");
loadPathType.isExpanded = EditorGUILayout.Foldout(loadPathType.isExpanded, "Load/Save Options");
if (loadPathType.isExpanded)
{
SerializedProperty loadString = serializedObject.FindProperty("loadString");
SerializedProperty loadPath = serializedObject.FindProperty("loadPath");
SerializedProperty loadFilename = serializedObject.FindProperty("loadFilename");
SerializedProperty loadFileOnStart = serializedObject.FindProperty("loadFileOnStart");
SerializedProperty savePathType = serializedObject.FindProperty("savePathType");
SerializedProperty savePath = serializedObject.FindProperty("savePath");
SerializedProperty saveFilename = serializedObject.FindProperty("saveFilename");
//LoadSave Flags
SerializedProperty defaultLoadOptions = serializedObject.FindProperty("defaultLoadOptions");
SerializedProperty defaultSaveOptions = serializedObject.FindProperty("defaultSaveOptions");
//extra LoadSave Options in addition to flags
SerializedProperty waitForBundles = serializedObject.FindProperty("waitForBundles");
SerializedProperty makeUniqueFilename = serializedObject.FindProperty("makeUniqueFilename");
SerializedProperty ensureSharedColors = serializedObject.FindProperty("ensureSharedColors");
EditorGUILayout.PropertyField(loadPathType);
if (loadPathType.enumValueIndex == Convert.ToInt32(DynamicCharacterAvatar.loadPathTypes.String))
{
EditorGUILayout.PropertyField(loadString);
}
else
{
if (loadPathType.enumValueIndex <= 1)
{
EditorGUILayout.PropertyField(loadPath);
}
}
EditorGUILayout.PropertyField(loadFilename);
if (loadFilename.stringValue != "")
{
EditorGUILayout.PropertyField(loadFileOnStart);
}
EditorGUI.indentLevel++;
//LoadOptionsFlags
defaultLoadOptions.isExpanded = EditorGUILayout.Foldout(defaultLoadOptions.isExpanded, new GUIContent("Load Options", "The default options for when a character is loaded from an UMATextRecipe asset or a recipe string. Can be overidden when calling 'LoadFromRecipe' or 'LoadFromString' directly."));
if (defaultLoadOptions.isExpanded)
{
EditorGUILayout.PropertyField(defaultLoadOptions, GUIContent.none);
EditorGUI.indentLevel++;
//waitForBundles.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(waitForBundles.displayName, waitForBundles.tooltip), waitForBundles.boolValue);
//buildAfterLoad.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(buildAfterLoad.displayName, buildAfterLoad.tooltip), buildAfterLoad.boolValue);
//just drawing these as propertyFields because the toolTip on toggle left doesn't work
EditorGUILayout.PropertyField(waitForBundles);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
if (Application.isPlaying)
{
if (GUILayout.Button("Perform Load"))
{
thisDCA.DoLoad();
}
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(savePathType);
if (savePathType.enumValueIndex <= 2)
{
EditorGUILayout.PropertyField(savePath);
}
EditorGUILayout.PropertyField(saveFilename);
EditorGUI.indentLevel++;
defaultSaveOptions.isExpanded = EditorGUILayout.Foldout(defaultSaveOptions.isExpanded, new GUIContent("Save Options", "The default options for when a character is save to UMATextRecipe asset or a txt. Can be overidden when calling 'DoSave' directly."));
if (defaultSaveOptions.isExpanded)
{
EditorGUILayout.PropertyField(defaultSaveOptions, GUIContent.none);
EditorGUI.indentLevel++;
//ensureSharedColors.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(ensureSharedColors.displayName, ensureSharedColors.tooltip), ensureSharedColors.boolValue);
//makeUniqueFilename.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(makeUniqueFilename.displayName, makeUniqueFilename.tooltip), makeUniqueFilename.boolValue);
//just drawing these as propertyFields because the toolTip on toggle left doesn't work
EditorGUILayout.PropertyField(ensureSharedColors);
EditorGUILayout.PropertyField(makeUniqueFilename);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
if (Application.isPlaying)
{
if (GUILayout.Button("Perform Save"))
{
thisDCA.DoSave();
}
}
EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
GUILayout.Space(2f);
//for CharacterEvents
EditorGUI.BeginChangeCheck();
SerializedProperty CharacterCreated = serializedObject.FindProperty("CharacterCreated");
CharacterCreated.isExpanded = EditorGUILayout.Foldout(CharacterCreated.isExpanded, "Character Events");
if (CharacterCreated.isExpanded)
{
SerializedProperty CharacterUpdated = serializedObject.FindProperty("CharacterUpdated");
SerializedProperty CharacterDestroyed= serializedObject.FindProperty("CharacterDestroyed");
SerializedProperty CharacterDnaUpdated = serializedObject.FindProperty ("CharacterDnaUpdated");
SerializedProperty RecipeUpdated = serializedObject.FindProperty("RecipeUpdated");
EditorGUILayout.PropertyField(CharacterCreated);
EditorGUILayout.PropertyField(CharacterUpdated);
EditorGUILayout.PropertyField(CharacterDestroyed);
EditorGUILayout.PropertyField (CharacterDnaUpdated);
EditorGUILayout.PropertyField(RecipeUpdated);
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
GUILayout.Space(2f);
//for AdvancedOptions
EditorGUI.BeginChangeCheck();
context.isExpanded = EditorGUILayout.Foldout(context.isExpanded, "Advanced Options");
if (context.isExpanded)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedObject.FindProperty("hide"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
if (showHelp)
{
EditorGUILayout.HelpBox("Hide: This disables the display of the Avatar without preventing it from being generated. If you want to prevent the character from being generated at all disable the DynamicCharacterAvatar component itself.", MessageType.Info);
}
//for _buildCharacterEnabled we want to set the value using the DCS BuildCharacterEnabled property because this actually triggers BuildCharacter
var buildCharacterEnabled = serializedObject.FindProperty("_buildCharacterEnabled");
var buildCharacterEnabledValue = buildCharacterEnabled.boolValue;
EditorGUI.BeginChangeCheck();
var buildCharacterEnabledNewValue = EditorGUILayout.Toggle(new GUIContent(buildCharacterEnabled.displayName, "Builds the character on recipe load or race changed. If you want to load multiple recipes into a character you can disable this and enable it when you are done. By default this should be true."), buildCharacterEnabledValue);
if (EditorGUI.EndChangeCheck())
{
if (buildCharacterEnabledNewValue != buildCharacterEnabledValue)
thisDCA.BuildCharacterEnabled = buildCharacterEnabledNewValue;
serializedObject.ApplyModifiedProperties();
}
if (showHelp)
{
EditorGUILayout.HelpBox("Build Character Enabled: Builds the character on recipe load or race changed. If you want to load multiple recipes into a character you can disable this and enable it when you are done. By default this should be true.", MessageType.Info);
}
EditorGUILayout.PropertyField(serializedObject.FindProperty("loadBlendShapes"), new GUIContent("Load BlendShapes (experimental)"));
EditorGUILayout.PropertyField(context);
EditorGUILayout.PropertyField(umaData);
EditorGUILayout.PropertyField(umaGenerator);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(umaRecipe);
EditorGUILayout.PropertyField(umaAdditionalRecipes, true);
EditorGUILayout.PropertyField(animationController);
EditorGUILayout.PropertyField(serializedObject.FindProperty("BoundsOffset"));
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
GUILayout.Space(2f);
//for PlaceholderOptions
EditorGUI.BeginChangeCheck();
SerializedProperty gizmo = serializedObject.FindProperty("showPlaceholder");
SerializedProperty enableGizmo = serializedObject.FindProperty("showPlaceholder");
SerializedProperty previewModel = serializedObject.FindProperty("previewModel");
SerializedProperty customModel = serializedObject.FindProperty("customModel");
SerializedProperty customRotation = serializedObject.FindProperty("customRotation");
SerializedProperty previewColor = serializedObject.FindProperty("previewColor");
gizmo.isExpanded = EditorGUILayout.Foldout(gizmo.isExpanded, "Placeholder Options");
if (gizmo.isExpanded)
{
EditorGUILayout.PropertyField(enableGizmo);
EditorGUILayout.PropertyField(previewModel);
if(previewModel.enumValueIndex == 2)
{
EditorGUILayout.PropertyField(customModel);
EditorGUILayout.PropertyField(customRotation);
}
EditorGUILayout.PropertyField(previewColor);
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
if (Application.isPlaying)
{
EditorGUILayout.LabelField("AssetBundles used by Avatar");
string assetBundlesUsed = "";
if (thisDCA.assetBundlesUsedbyCharacter.Count == 0)
{
assetBundlesUsed = "None";
}
else
{
for (int i = 0; i < thisDCA.assetBundlesUsedbyCharacter.Count; i++)
{
assetBundlesUsed = assetBundlesUsed + thisDCA.assetBundlesUsedbyCharacter[i];
if (i < (thisDCA.assetBundlesUsedbyCharacter.Count - 1))
assetBundlesUsed = assetBundlesUsed + "\n";
}
}
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.TextArea(assetBundlesUsed);
EditorGUI.EndDisabledGroup();
}
}
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public class FloatWindow : Form, INestedPanesContainer, IDockDragSource
{
private NestedPaneCollection m_nestedPanes;
internal const int WM_CHECKDISPOSE = (int)(Win32.Msgs.WM_USER + 1);
internal protected FloatWindow(DockPanel dockPanel, DockPane pane)
{
InternalConstruct(dockPanel, pane, false, Rectangle.Empty);
}
internal protected FloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds)
{
InternalConstruct(dockPanel, pane, true, bounds);
}
private void InternalConstruct(DockPanel dockPanel, DockPane pane, bool boundsSpecified, Rectangle bounds)
{
if (dockPanel == null)
throw(new ArgumentNullException(Strings.FloatWindow_Constructor_NullDockPanel));
m_nestedPanes = new NestedPaneCollection(this);
FormBorderStyle = FormBorderStyle.SizableToolWindow;
ShowInTaskbar = false;
if (dockPanel.RightToLeft != RightToLeft)
RightToLeft = dockPanel.RightToLeft;
if (RightToLeftLayout != dockPanel.RightToLeftLayout)
RightToLeftLayout = dockPanel.RightToLeftLayout;
SuspendLayout();
if (boundsSpecified)
{
Bounds = bounds;
StartPosition = FormStartPosition.Manual;
}
else
{
StartPosition = FormStartPosition.WindowsDefaultLocation;
Size = dockPanel.DefaultFloatWindowSize;
}
m_dockPanel = dockPanel;
Owner = DockPanel.FindForm();
DockPanel.AddFloatWindow(this);
if (pane != null)
pane.FloatWindow = this;
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (DockPanel != null)
DockPanel.RemoveFloatWindow(this);
m_dockPanel = null;
}
base.Dispose(disposing);
}
private bool m_allowEndUserDocking = true;
public bool AllowEndUserDocking
{
get { return m_allowEndUserDocking; }
set { m_allowEndUserDocking = value; }
}
public NestedPaneCollection NestedPanes
{
get { return m_nestedPanes; }
}
public VisibleNestedPaneCollection VisibleNestedPanes
{
get { return NestedPanes.VisibleNestedPanes; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
public DockState DockState
{
get { return DockState.Float; }
}
public bool IsFloat
{
get { return DockState == DockState.Float; }
}
internal bool IsDockStateValid(DockState dockState)
{
foreach (DockPane pane in NestedPanes)
foreach (IDockContent content in pane.Contents)
if (!DockHelper.IsDockStateValid(dockState, content.DockHandler.DockAreas))
return false;
return true;
}
protected override void OnActivated(EventArgs e)
{
DockPanel.FloatWindows.BringWindowToFront(this);
base.OnActivated (e);
// Propagate the Activated event to the visible panes content objects
foreach (DockPane pane in VisibleNestedPanes)
foreach (IDockContent content in pane.Contents)
content.OnActivated(e);
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
// Propagate the Deactivate event to the visible panes content objects
foreach (DockPane pane in VisibleNestedPanes)
foreach (IDockContent content in pane.Contents)
content.OnDeactivate(e);
}
protected override void OnLayout(LayoutEventArgs levent)
{
VisibleNestedPanes.Refresh();
RefreshChanges();
Visible = (VisibleNestedPanes.Count > 0);
SetText();
base.OnLayout(levent);
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
internal void SetText()
{
DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null;
if (theOnlyPane == null)
Text = " "; // use " " instead of string.Empty because the whole title bar will disappear when ControlBox is set to false.
else if (theOnlyPane.ActiveContent == null)
Text = " ";
else
Text = theOnlyPane.ActiveContent.DockHandler.TabText;
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
Rectangle rectWorkArea = SystemInformation.VirtualScreen;
if (y + height > rectWorkArea.Bottom)
y -= (y + height) - rectWorkArea.Bottom;
if (y < rectWorkArea.Top)
y += rectWorkArea.Top - y;
base.SetBoundsCore (x, y, width, height, specified);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDOWN)
{
if (IsDisposed)
return;
uint result = Win32Helper.IsRunningOnMono ? 0 : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result == 2 && DockPanel.AllowEndUserDocking && this.AllowEndUserDocking) // HITTEST_CAPTION
{
Activate();
m_dockPanel.BeginDrag(this);
}
else
base.WndProc(ref m);
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_NCRBUTTONDOWN)
{
uint result = Win32Helper.IsRunningOnMono ? 0 : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result == 2) // HITTEST_CAPTION
{
DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null;
if (theOnlyPane != null && theOnlyPane.ActiveContent != null)
{
theOnlyPane.ShowTabPageContextMenu(this, PointToClient(Control.MousePosition));
return;
}
}
base.WndProc(ref m);
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_CLOSE)
{
if (NestedPanes.Count == 0)
{
base.WndProc(ref m);
return;
}
for (int i = NestedPanes.Count - 1; i >= 0; i--)
{
DockContentCollection contents = NestedPanes[i].Contents;
for (int j = contents.Count - 1; j >= 0; j--)
{
IDockContent content = contents[j];
if (content.DockHandler.DockState != DockState.Float)
continue;
if (!content.DockHandler.CloseButton)
continue;
if (content.DockHandler.HideOnClose)
content.DockHandler.Hide();
else
content.DockHandler.Close();
}
}
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDBLCLK)
{
uint result = Win32Helper.IsRunningOnMono ? 0: NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result != 2) // HITTEST_CAPTION
{
base.WndProc(ref m);
return;
}
DockPanel.SuspendLayout(true);
// Restore to panel
foreach (DockPane pane in NestedPanes)
{
if (pane.DockState != DockState.Float)
continue;
pane.RestoreToPanel();
}
DockPanel.ResumeLayout(true, true);
return;
}
else if (m.Msg == WM_CHECKDISPOSE)
{
if (NestedPanes.Count == 0)
Dispose();
return;
}
base.WndProc(ref m);
}
internal void RefreshChanges()
{
if (IsDisposed)
return;
if (VisibleNestedPanes.Count == 0)
{
ControlBox = true;
return;
}
for (int i=VisibleNestedPanes.Count - 1; i>=0; i--)
{
DockContentCollection contents = VisibleNestedPanes[i].Contents;
for (int j=contents.Count - 1; j>=0; j--)
{
IDockContent content = contents[j];
if (content.DockHandler.DockState != DockState.Float)
continue;
if (content.DockHandler.CloseButton && content.DockHandler.CloseButtonVisible)
{
ControlBox = true;
return;
}
}
}
//Only if there is a ControlBox do we turn it off
//old code caused a flash of the window.
if (ControlBox)
ControlBox = false;
}
public virtual Rectangle DisplayingRectangle
{
get { return ClientRectangle; }
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
{
if (VisibleNestedPanes.Count == 1)
{
DockPane pane = VisibleNestedPanes[0];
if (!dragSource.CanDockTo(pane))
return;
Point ptMouse = Control.MousePosition;
uint lParam = Win32Helper.MakeLong(ptMouse.X, ptMouse.Y);
if (!Win32Helper.IsRunningOnMono)
if (NativeMethods.SendMessage(Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, lParam) == (uint)Win32.HitTest.HTCAPTION)
dockOutline.Show(VisibleNestedPanes[0], -1);
}
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState)
{
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane)
{
if (!IsDockStateValid(pane.DockState))
return false;
if (pane.FloatWindow == this)
return false;
return true;
}
Rectangle IDockDragSource.BeginDrag(Point ptMouse)
{
return Bounds;
}
public void FloatAt(Rectangle floatWindowBounds)
{
Bounds = floatWindowBounds;
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
{
if (dockStyle == DockStyle.Fill)
{
for (int i = NestedPanes.Count - 1; i >= 0; i--)
{
DockPane paneFrom = NestedPanes[i];
for (int j = paneFrom.Contents.Count - 1; j >= 0; j--)
{
IDockContent c = paneFrom.Contents[j];
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
c.DockHandler.Activate();
}
}
}
else
{
DockAlignment alignment = DockAlignment.Left;
if (dockStyle == DockStyle.Left)
alignment = DockAlignment.Left;
else if (dockStyle == DockStyle.Right)
alignment = DockAlignment.Right;
else if (dockStyle == DockStyle.Top)
alignment = DockAlignment.Top;
else if (dockStyle == DockStyle.Bottom)
alignment = DockAlignment.Bottom;
MergeNestedPanes(VisibleNestedPanes, pane.NestedPanesContainer.NestedPanes, pane, alignment, 0.5);
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
if (panel != DockPanel)
throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");
NestedPaneCollection nestedPanesTo = null;
if (dockStyle == DockStyle.Top)
nestedPanesTo = DockPanel.DockWindows[DockState.DockTop].NestedPanes;
else if (dockStyle == DockStyle.Bottom)
nestedPanesTo = DockPanel.DockWindows[DockState.DockBottom].NestedPanes;
else if (dockStyle == DockStyle.Left)
nestedPanesTo = DockPanel.DockWindows[DockState.DockLeft].NestedPanes;
else if (dockStyle == DockStyle.Right)
nestedPanesTo = DockPanel.DockWindows[DockState.DockRight].NestedPanes;
else if (dockStyle == DockStyle.Fill)
nestedPanesTo = DockPanel.DockWindows[DockState.Document].NestedPanes;
DockPane prevPane = null;
for (int i = nestedPanesTo.Count - 1; i >= 0; i--)
if (nestedPanesTo[i] != VisibleNestedPanes[0])
prevPane = nestedPanesTo[i];
MergeNestedPanes(VisibleNestedPanes, nestedPanesTo, prevPane, DockAlignment.Left, 0.5);
}
private static void MergeNestedPanes(VisibleNestedPaneCollection nestedPanesFrom, NestedPaneCollection nestedPanesTo, DockPane prevPane, DockAlignment alignment, double proportion)
{
if (nestedPanesFrom.Count == 0)
return;
int count = nestedPanesFrom.Count;
DockPane[] panes = new DockPane[count];
DockPane[] prevPanes = new DockPane[count];
DockAlignment[] alignments = new DockAlignment[count];
double[] proportions = new double[count];
for (int i = 0; i < count; i++)
{
panes[i] = nestedPanesFrom[i];
prevPanes[i] = nestedPanesFrom[i].NestedDockingStatus.PreviousPane;
alignments[i] = nestedPanesFrom[i].NestedDockingStatus.Alignment;
proportions[i] = nestedPanesFrom[i].NestedDockingStatus.Proportion;
}
DockPane pane = panes[0].DockTo(nestedPanesTo.Container, prevPane, alignment, proportion);
panes[0].DockState = nestedPanesTo.DockState;
for (int i = 1; i < count; i++)
{
for (int j = i; j < count; j++)
{
if (prevPanes[j] == panes[i - 1])
prevPanes[j] = pane;
}
pane = panes[i].DockTo(nestedPanesTo.Container, prevPanes[i], alignments[i], proportions[i]);
panes[i].DockState = nestedPanesTo.DockState;
}
}
#endregion
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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.Linq;
using NUnit.Framework;
using Sensus.Extensions;
using Sensus.Probes.User.Scripts;
namespace Sensus.Tests.Scripts
{
[TestFixture]
public class ScheduleTriggerTests
{
[Test]
public void Deserialize1PointTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00" };
Assert.AreEqual(1, schedule.WindowCount);
Assert.AreEqual("10:00", schedule.WindowsString);
}
[Test]
public void Deserialize1WindowTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00-10:30" };
Assert.AreEqual(1, schedule.WindowCount);
Assert.AreEqual("10:00-10:30", schedule.WindowsString);
}
[Test]
public void Deserialize1PointTrailingCommaTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00" };
Assert.AreEqual(1, schedule.WindowCount);
Assert.AreEqual("10:00", schedule.WindowsString);
}
[Test]
public void Deserialize1Point1WindowTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00,10:10-10:20" };
Assert.AreEqual(2, schedule.WindowCount);
Assert.AreEqual("10:00, 10:10-10:20", schedule.WindowsString);
}
[Test]
public void Deserialize1Point1WindowSpacesTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" };
Assert.AreEqual(2, schedule.WindowCount);
Assert.AreEqual("10:00, 10:10-10:20", schedule.WindowsString);
}
[Test]
public void SchedulesAllFutureTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" };
var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0);
var afterDate = new DateTime(1986, 4, 18, 0, 0, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray();
Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0));
Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0));
Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0));
}
[Test]
public void SchedulesOneFutureTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:20-10:30" };
var referenceDate = new DateTime(1986, 4, 18, 10, 10, 0);
var afterDate = new DateTime(1986, 4, 18, 10, 10, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray();
Assert.IsTrue(new TimeSpan(0, 0, 10, 0) <= triggerTimes[0].ReferenceTillTrigger && triggerTimes[0].ReferenceTillTrigger <= new TimeSpan(0, 0, 20, 0));
Assert.AreEqual(new TimeSpan(0, 23, 50, 0), triggerTimes[1].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(1, 0, 10, 0) <= triggerTimes[2].ReferenceTillTrigger && triggerTimes[2].ReferenceTillTrigger <= new TimeSpan(1, 0, 20, 0));
Assert.AreEqual(new TimeSpan(1, 23, 50, 0), triggerTimes[3].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 0, 10, 0) <= triggerTimes[4].ReferenceTillTrigger && triggerTimes[4].ReferenceTillTrigger <= new TimeSpan(2, 0, 20, 0));
Assert.AreEqual(new TimeSpan(2, 23, 50, 0), triggerTimes[5].ReferenceTillTrigger);
}
[Test]
public void SchedulesAfterOneDayTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:20-10:30" };
var referenceDate = new DateTime(1986, 4, 18, 10, 10, 0);
var afterDate = new DateTime(1986, 4, 19, 10, 10, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray();
Assert.IsTrue(new TimeSpan(1, 0, 10, 0) <= triggerTimes[0].ReferenceTillTrigger && triggerTimes[0].ReferenceTillTrigger <= new TimeSpan(1, 0, 20, 0));
Assert.AreEqual(new TimeSpan(1, 23, 50, 0), triggerTimes[1].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 0, 10, 0) <= triggerTimes[2].ReferenceTillTrigger && triggerTimes[2].ReferenceTillTrigger <= new TimeSpan(2, 0, 20, 0));
Assert.AreEqual(new TimeSpan(2, 23, 50, 0), triggerTimes[3].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(3, 0, 10, 0) <= triggerTimes[4].ReferenceTillTrigger && triggerTimes[4].ReferenceTillTrigger <= new TimeSpan(3, 0, 20, 0));
Assert.AreEqual(new TimeSpan(3, 23, 50, 0), triggerTimes[5].ReferenceTillTrigger);
}
[Test]
public void SchedulesPullsOnlySevenDays()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00" };
var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0);
var afterDate = new DateTime(1986, 4, 19, 0, 0, 0);
var triggerTimeCount = schedule.GetTriggerTimes(referenceDate, afterDate).Count();
Assert.AreEqual(7, triggerTimeCount);
}
[Test]
public void SchedulesAllFutureNoExpirationsTest()
{
var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" };
var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0);
var afterDate = new DateTime(1986, 4, 18, 0, 0, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray();
Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0));
Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0));
Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0));
Assert.AreEqual(null, triggerTimes[0].Expiration);
Assert.AreEqual(null, triggerTimes[1].Expiration);
Assert.AreEqual(null, triggerTimes[2].Expiration);
Assert.AreEqual(null, triggerTimes[3].Expiration);
Assert.AreEqual(null, triggerTimes[4].Expiration);
Assert.AreEqual(null, triggerTimes[5].Expiration);
}
[Test]
public void SchedulesAllFutureExpirationAgeTest()
{
var schedule = new ScheduleTrigger
{
WindowsString = "10:00, 10:10-10:20"
};
var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0);
var afterDate = new DateTime(1986, 4, 18, 0, 0, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate, TimeSpan.FromMinutes(10)).Take(6).ToArray();
Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0));
Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0));
Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0));
Assert.AreEqual(referenceDate + triggerTimes[0].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[0].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[1].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[1].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[2].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[2].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[3].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[3].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[4].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[4].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[5].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[5].Expiration);
}
[Test]
public void SchedulesAllFutureExpirationWindowTest()
{
var schedule = new ScheduleTrigger
{
WindowExpiration = true,
WindowsString = "10:00, 10:10-10:20"
};
var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0);
var afterDate = new DateTime(1986, 4, 18, 0, 0, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray();
Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0));
Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0));
Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0));
Assert.AreEqual(null, triggerTimes[0].Expiration);
Assert.AreEqual(new DateTime(1986, 4, 18, 10, 20, 00), triggerTimes[1].Expiration);
Assert.AreEqual(null, triggerTimes[2].Expiration);
Assert.AreEqual(new DateTime(1986, 4, 19, 10, 20, 00), triggerTimes[3].Expiration);
Assert.AreEqual(null, triggerTimes[4].Expiration);
Assert.AreEqual(new DateTime(1986, 4, 20, 10, 20, 00), triggerTimes[5].Expiration);
}
[Test]
public void SchedulesAllFutureExpirationWindowAndAgeTest()
{
var schedule = new ScheduleTrigger
{
WindowExpiration = true,
WindowsString = "10:00, 10:10-10:20"
};
var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0);
var afterDate = new DateTime(1986, 4, 18, 0, 0, 0);
var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate, TimeSpan.FromMinutes(5)).Take(6).ToArray();
Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0));
Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0));
Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger);
Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0));
Assert.AreEqual(referenceDate + triggerTimes[0].ReferenceTillTrigger + TimeSpan.FromMinutes(5), triggerTimes[0].Expiration);
Assert.AreEqual(new DateTime(1986, 4, 18, 10, 20, 00).Min(referenceDate + triggerTimes[1].ReferenceTillTrigger + TimeSpan.FromMinutes(5)), triggerTimes[1].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[2].ReferenceTillTrigger + TimeSpan.FromMinutes(5), triggerTimes[2].Expiration);
Assert.AreEqual(new DateTime(1986, 4, 19, 10, 20, 00).Min(referenceDate + triggerTimes[3].ReferenceTillTrigger + TimeSpan.FromMinutes(5)), triggerTimes[3].Expiration);
Assert.AreEqual(referenceDate + triggerTimes[4].ReferenceTillTrigger + TimeSpan.FromMinutes(5), triggerTimes[4].Expiration);
Assert.AreEqual(new DateTime(1986, 4, 20, 10, 20, 00).Min(referenceDate + triggerTimes[5].ReferenceTillTrigger + TimeSpan.FromMinutes(5)), triggerTimes[5].Expiration);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: operations/rpc/out_of_order_record_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Operations.RPC {
public static partial class OutOfOrderRecordSvc
{
static readonly string __ServiceName = "holms.types.operations.rpc.OutOfOrderRecordSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> __Marshaller_PropertyIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse> __Marshaller_OutOfOrderRecordSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator> __Marshaller_OutOfOrderRecordIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse> __Marshaller_OutOfOrderRecordGetByIdResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest> __Marshaller_OutOfOrderRecordSvcCreateRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse> __Marshaller_OutOfOrderRecordCreateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest> __Marshaller_OutOfOrderRecordSvcUpdateRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse> __Marshaller_OutOfOrderRecordUpdateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse> __Marshaller_OutOfOrderRecordDeleteResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse> __Method_All = new grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_PropertyIndicator,
__Marshaller_OutOfOrderRecordSvcAllResponse);
static readonly grpc::Method<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse> __Method_GetById = new grpc::Method<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_OutOfOrderRecordIndicator,
__Marshaller_OutOfOrderRecordGetByIdResponse);
static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse> __Method_Create = new grpc::Method<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_OutOfOrderRecordSvcCreateRequest,
__Marshaller_OutOfOrderRecordCreateResponse);
static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse> __Method_Update = new grpc::Method<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_OutOfOrderRecordSvcUpdateRequest,
__Marshaller_OutOfOrderRecordUpdateResponse);
static readonly grpc::Method<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse> __Method_Delete = new grpc::Method<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator, global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_OutOfOrderRecordIndicator,
__Marshaller_OutOfOrderRecordDeleteResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of OutOfOrderRecordSvc</summary>
public abstract partial class OutOfOrderRecordSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse> All(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse> GetById(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse> Create(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse> Update(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse> Delete(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for OutOfOrderRecordSvc</summary>
public partial class OutOfOrderRecordSvcClient : grpc::ClientBase<OutOfOrderRecordSvcClient>
{
/// <summary>Creates a new client for OutOfOrderRecordSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public OutOfOrderRecordSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for OutOfOrderRecordSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public OutOfOrderRecordSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected OutOfOrderRecordSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected OutOfOrderRecordSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse All(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse All(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse> AllAsync(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse> AllAsync(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse GetById(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse GetById(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse> GetByIdAsync(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse> GetByIdAsync(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse Create(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse Create(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse> CreateAsync(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse> CreateAsync(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse Update(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse Update(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse> UpdateAsync(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse> UpdateAsync(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse Delete(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse Delete(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse> DeleteAsync(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse> DeleteAsync(global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override OutOfOrderRecordSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new OutOfOrderRecordSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(OutOfOrderRecordSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete).Build();
}
}
}
#endregion
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Evans.Demo.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using QuantConnect.Brokerages;
using QuantConnect.Brokerages.Backtesting;
using QuantConnect.Data.Market;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Securities;
using QuantConnect.Tests.Engine.DataFeeds;
namespace QuantConnect.Tests.Engine.BrokerageTransactionHandlerTests
{
[TestFixture]
public class BacktestingTransactionHandlerTests
{
private const string Ticker = "EURUSD";
private BrokerageTransactionHandlerTests.TestAlgorithm _algorithm;
[SetUp]
public void Initialize()
{
_algorithm = new BrokerageTransactionHandlerTests.TestAlgorithm
{
HistoryProvider = new BrokerageTransactionHandlerTests.EmptyHistoryProvider()
};
_algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm));
_algorithm.SetBrokerageModel(BrokerageName.FxcmBrokerage);
_algorithm.SetCash(100000);
_algorithm.AddSecurity(SecurityType.Forex, Ticker);
_algorithm.SetFinishedWarmingUp();
TestPartialFilledModel.FilledOrders = new Dictionary<int, Order>();
}
[Test]
public void InvalidOrderRequestWontSetTicketAsProcessed()
{
//Initializes the transaction handler
var transactionHandler = new BacktestingTransactionHandler();
transactionHandler.Initialize(_algorithm, new BacktestingBrokerage(_algorithm), new BacktestingResultHandler());
// Creates the order
var security = _algorithm.Securities[Ticker];
var orderRequest = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, 600, 0, 0, 0, DateTime.Now, "");
// Mock the the order processor
var orderProcessorMock = new Mock<IOrderProcessor>();
orderProcessorMock.Setup(m => m.GetOrderTicket(It.IsAny<int>())).Returns(new OrderTicket(_algorithm.Transactions, orderRequest));
_algorithm.Transactions.SetOrderProcessor(orderProcessorMock.Object);
var ticket = transactionHandler.AddOrder(orderRequest);
var ticket2 = transactionHandler.AddOrder(orderRequest);
// 600 after round off becomes 0 -> order is not placed
Assert.IsTrue(orderRequest.Response.IsProcessed);
Assert.IsTrue(orderRequest.Response.IsError);
Assert.IsTrue(orderRequest.Response.ErrorMessage
.Contains("Cannot process submit request because order with id {0} already exists"));
}
[Test]
public void SendingNewOrderFromOnOrderEvent()
{
//Initializes the transaction handler
var transactionHandler = new BacktestingTransactionHandler();
var brokerage = new BacktestingBrokerage(_algorithm);
transactionHandler.Initialize(_algorithm, brokerage, new BacktestingResultHandler());
// Creates a market order
var security = _algorithm.Securities[Ticker];
var price = 1.12m;
security.SetMarketPrice(new Tick(DateTime.UtcNow.AddDays(-1), security.Symbol, price, price, price));
var orderRequest = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, 1000, 0, 0, 0, DateTime.UtcNow, "");
var orderRequest2 = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, -1000, 0, 0, 0, DateTime.UtcNow, "");
orderRequest.SetOrderId(1);
orderRequest2.SetOrderId(2);
// Mock the the order processor
var orderProcessorMock = new Mock<IOrderProcessor>();
orderProcessorMock.Setup(m => m.GetOrderTicket(It.Is<int>(i => i == 1))).Returns(new OrderTicket(_algorithm.Transactions, orderRequest));
orderProcessorMock.Setup(m => m.GetOrderTicket(It.Is<int>(i => i == 2))).Returns(new OrderTicket(_algorithm.Transactions, orderRequest2));
_algorithm.Transactions.SetOrderProcessor(orderProcessorMock.Object);
var orderEventCalls = 0;
brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
orderEventCalls++;
switch (orderEventCalls)
{
case 1:
Assert.AreEqual(1, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Submitted, orderEvent.Status);
// we send a new order request
var ticket2 = transactionHandler.Process(orderRequest2);
break;
case 2:
Assert.AreEqual(2, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Submitted, orderEvent.Status);
break;
case 3:
Assert.AreEqual(1, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Filled, orderEvent.Status);
break;
case 4:
Assert.AreEqual(2, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Filled, orderEvent.Status);
break;
}
Log.Trace($"{orderEvent}");
};
var ticket = transactionHandler.Process(orderRequest);
Assert.IsTrue(orderRequest.Response.IsProcessed);
Assert.IsTrue(orderRequest.Response.IsSuccess);
Assert.AreEqual(OrderRequestStatus.Processed, orderRequest.Status);
Assert.IsTrue(orderRequest2.Response.IsProcessed);
Assert.IsTrue(orderRequest2.Response.IsSuccess);
Assert.AreEqual(OrderRequestStatus.Processed, orderRequest2.Status);
var order1 = transactionHandler.GetOrderById(1);
Assert.AreEqual(OrderStatus.Filled, order1.Status);
var order2 = transactionHandler.GetOrderById(2);
Assert.AreEqual(OrderStatus.Filled, order2.Status);
// 2 submitted and 2 filled
Assert.AreEqual(4, orderEventCalls);
}
[Test]
public void SendingNewOrderFromPartiallyFilledOnOrderEvent()
{
//Initializes the transaction handler
var transactionHandler = new BacktestingTransactionHandler();
var brokerage = new BacktestingBrokerage(_algorithm);
transactionHandler.Initialize(_algorithm, brokerage, new BacktestingResultHandler());
// Creates a market order
var security = _algorithm.Securities[Ticker];
security.FillModel = new TestPartialFilledModel();
var price = 1.12m;
security.SetMarketPrice(new Tick(DateTime.UtcNow.AddDays(-1), security.Symbol, price, price, price));
var orderRequest = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, 2000, 0, 0, 9, DateTime.UtcNow, "");
var orderRequest2 = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, -2000, 0, 0, 9, DateTime.UtcNow, "");
orderRequest.SetOrderId(1);
orderRequest2.SetOrderId(2);
// Mock the the order processor
var orderProcessorMock = new Mock<IOrderProcessor>();
orderProcessorMock.Setup(m => m.GetOrderTicket(It.Is<int>(i => i == 1))).Returns(new OrderTicket(_algorithm.Transactions, orderRequest));
orderProcessorMock.Setup(m => m.GetOrderTicket(It.Is<int>(i => i == 2))).Returns(new OrderTicket(_algorithm.Transactions, orderRequest2));
_algorithm.Transactions.SetOrderProcessor(orderProcessorMock.Object);
var orderEventCalls = 0;
brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
orderEventCalls++;
switch (orderEventCalls)
{
case 1:
Assert.AreEqual(1, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Submitted, orderEvent.Status);
// we send a new order request
var ticket2 = transactionHandler.Process(orderRequest2);
break;
case 2:
Assert.AreEqual(2, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Submitted, orderEvent.Status);
break;
case 3:
Assert.AreEqual(1, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.PartiallyFilled, orderEvent.Status);
break;
case 4:
Assert.AreEqual(2, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.PartiallyFilled, orderEvent.Status);
break;
case 5:
Assert.AreEqual(1, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Filled, orderEvent.Status);
break;
case 6:
Assert.AreEqual(2, orderEvent.OrderId);
Assert.AreEqual(OrderStatus.Filled, orderEvent.Status);
break;
}
Log.Trace($"{orderEvent}");
};
var ticket = transactionHandler.Process(orderRequest);
Assert.IsTrue(orderRequest.Response.IsProcessed);
Assert.IsTrue(orderRequest.Response.IsSuccess);
Assert.AreEqual(OrderRequestStatus.Processed, orderRequest.Status);
Assert.IsTrue(orderRequest2.Response.IsProcessed);
Assert.IsTrue(orderRequest2.Response.IsSuccess);
Assert.AreEqual(OrderRequestStatus.Processed, orderRequest2.Status);
var order1 = transactionHandler.GetOrderById(1);
Assert.AreEqual(OrderStatus.Filled, order1.Status);
var order2 = transactionHandler.GetOrderById(2);
Assert.AreEqual(OrderStatus.Filled, order2.Status);
// 2 submitted and 2 PartiallyFilled and 2 Filled
Assert.AreEqual(6, orderEventCalls);
}
internal class TestPartialFilledModel : IFillModel
{
public static Dictionary<int, Order> FilledOrders;
public Fill Fill(FillModelParameters parameters)
{
var order = parameters.Order;
var status = OrderStatus.PartiallyFilled;
if (FilledOrders.ContainsKey(order.Id))
{
status = OrderStatus.Filled;
}
FilledOrders[order.Id] = order;
return new Fill(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero)
{
FillPrice = parameters.Security.Price,
FillQuantity = order.Quantity / 2,
Status = status
});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
namespace OmniSharp.Roslyn
{
public class BufferManager
{
private readonly OmnisharpWorkspace _workspace;
private readonly IDictionary<string, IEnumerable<DocumentId>> _transientDocuments = new Dictionary<string, IEnumerable<DocumentId>>(StringComparer.OrdinalIgnoreCase);
private readonly ISet<DocumentId> _transientDocumentIds = new HashSet<DocumentId>();
private readonly object _lock = new object();
public BufferManager(OmnisharpWorkspace workspace)
{
_workspace = workspace;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
}
public async Task UpdateBuffer(Request request)
{
var buffer = request.Buffer;
var changes = request.Changes;
var updateRequest = request as UpdateBufferRequest;
if (updateRequest != null && updateRequest.FromDisk)
{
buffer = File.ReadAllText(updateRequest.FileName);
}
if (request.FileName == null || (buffer == null && changes == null))
{
return;
}
var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(request.FileName);
if (!documentIds.IsEmpty)
{
if (changes == null)
{
var sourceText = SourceText.From(buffer);
foreach (var documentId in documentIds)
{
_workspace.OnDocumentChanged(documentId, sourceText);
}
}
else
{
foreach (var documentId in documentIds)
{
var document = _workspace.CurrentSolution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
foreach (var change in request.Changes)
{
var startOffset = sourceText.Lines.GetPosition(new LinePosition(change.StartLine, change.StartColumn));
var endOffset = sourceText.Lines.GetPosition(new LinePosition(change.EndLine, change.EndColumn));
sourceText = sourceText.WithChanges(new[] {
new TextChange(new TextSpan(startOffset, endOffset - startOffset), change.NewText)
});
}
_workspace.OnDocumentChanged(documentId, sourceText);
}
}
}
else if(buffer != null)
{
TryAddTransientDocument(request.FileName, buffer);
}
}
public async Task UpdateBuffer(ChangeBufferRequest request)
{
if (request.FileName == null)
{
return;
}
var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(request.FileName);
if (!documentIds.IsEmpty)
{
foreach (var documentId in documentIds)
{
var document = _workspace.CurrentSolution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
var startOffset = sourceText.Lines.GetPosition(new LinePosition(request.StartLine, request.StartColumn));
var endOffset = sourceText.Lines.GetPosition(new LinePosition(request.EndLine, request.EndColumn));
sourceText = sourceText.WithChanges(new[] {
new TextChange(new TextSpan(startOffset, endOffset - startOffset), request.NewText)
});
_workspace.OnDocumentChanged(documentId, sourceText);
}
}
else
{
// TODO@joh ensure the edit is an insert at offset zero
TryAddTransientDocument(request.FileName, request.NewText);
}
}
private bool TryAddTransientDocument(string fileName, string fileContent)
{
if (string.IsNullOrWhiteSpace(fileName))
{
return false;
}
var projects = FindProjectsByFileName(fileName);
if (projects.Count() == 0)
{
return false;
}
var sourceText = SourceText.From(fileContent);
var documents = new List<DocumentInfo>();
foreach (var project in projects)
{
var id = DocumentId.CreateNewId(project.Id);
var version = VersionStamp.Create();
var document = DocumentInfo.Create(id, fileName, filePath: fileName, loader: TextLoader.From(TextAndVersion.Create(sourceText, version)));
documents.Add(document);
}
lock (_lock)
{
var documentIds = documents.Select(document => document.Id);
_transientDocuments.Add(fileName, documentIds);
_transientDocumentIds.UnionWith(documentIds);
}
foreach (var document in documents)
{
_workspace.AddDocument(document);
}
return true;
}
private IEnumerable<Project> FindProjectsByFileName(string fileName)
{
var dirInfo = new FileInfo(fileName).Directory;
var candidates = _workspace.CurrentSolution.Projects
.GroupBy(project => new FileInfo(project.FilePath).Directory.FullName)
.ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());
List<Project> projects = null;
while (dirInfo != null)
{
if (candidates.TryGetValue(dirInfo.FullName, out projects))
{
return projects;
}
dirInfo = dirInfo.Parent;
}
return Enumerable.Empty<Project>();
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
string fileName = null;
if (args.Kind == WorkspaceChangeKind.DocumentAdded)
{
fileName = args.NewSolution.GetDocument(args.DocumentId).FilePath;
}
else if (args.Kind == WorkspaceChangeKind.DocumentRemoved)
{
fileName = args.OldSolution.GetDocument(args.DocumentId).FilePath;
}
if (fileName == null)
{
return;
}
lock (_lock)
{
if (_transientDocumentIds.Contains(args.DocumentId))
{
return;
}
IEnumerable<DocumentId> documentIds;
if (!_transientDocuments.TryGetValue(fileName, out documentIds))
{
return;
}
_transientDocuments.Remove(fileName);
foreach (var documentId in documentIds)
{
_workspace.RemoveDocument(documentId);
_transientDocumentIds.Remove(documentId);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.TrafficManager
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// GeographicHierarchiesOperations operations.
/// </summary>
internal partial class GeographicHierarchiesOperations : IServiceOperations<TrafficManagerManagementClient>, IGeographicHierarchiesOperations
{
/// <summary>
/// Initializes a new instance of the GeographicHierarchiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal GeographicHierarchiesOperations(TrafficManagerManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the TrafficManagerManagementClient
/// </summary>
public TrafficManagerManagementClient Client { get; private set; }
/// <summary>
/// Gets the default Geographic Hierarchy used by the Geographic traffic
/// routing method.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TrafficManagerGeographicHierarchy>> GetDefaultWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDefault", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Network/trafficManagerGeographicHierarchies/default").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TrafficManagerGeographicHierarchy>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrafficManagerGeographicHierarchy>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Net.Mime;
using System.Text;
namespace System.Net
{
internal sealed class Base64Stream : DelegatedStream, IEncodableStream
{
private static readonly byte[] s_base64DecodeMap = new byte[]
{
//0 1 2 3 4 5 6 7 8 9 A B C D E F
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 0
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 1
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, // 2
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255, // 3
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 4
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, // 5
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 6
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255, // 7
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 8
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 9
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // A
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // B
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // C
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // D
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // E
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // F
};
private static readonly byte[] s_base64EncodeMap = new byte[]
{
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47,
61
};
private readonly int _lineLength;
private readonly Base64WriteStateInfo _writeState;
private ReadStateInfo _readState;
//the number of bytes needed to encode three bytes (see algorithm description in Encode method below)
private const int SizeOfBase64EncodedChar = 4;
//bytes with this value in the decode map are invalid
private const byte InvalidBase64Value = 255;
internal Base64Stream(Stream stream, Base64WriteStateInfo writeStateInfo) : base(stream)
{
_writeState = new Base64WriteStateInfo();
_lineLength = writeStateInfo.MaxLineLength;
}
internal Base64Stream(Base64WriteStateInfo writeStateInfo) : base(new MemoryStream())
{
_lineLength = writeStateInfo.MaxLineLength;
_writeState = writeStateInfo;
}
private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo());
internal Base64WriteStateInfo WriteState
{
get
{
Debug.Assert(_writeState != null, "_writeState was null");
return _writeState;
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var result = new ReadAsyncResult(this, buffer, offset, count, callback, state);
result.Read();
return result;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var result = new WriteAsyncResult(this, buffer, offset, count, callback, state);
result.Write();
return result;
}
public override void Close()
{
if (_writeState != null && WriteState.Length > 0)
{
switch (WriteState.Padding)
{
case 1:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits], s_base64EncodeMap[64]);
break;
case 2:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits], s_base64EncodeMap[64], s_base64EncodeMap[64]);
break;
}
WriteState.Padding = 0;
FlushInternal();
}
base.Close();
}
public unsafe int DecodeBytes(byte[] buffer, int offset, int count)
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* source = start;
byte* dest = start;
byte* end = start + count;
while (source < end)
{
//space and tab are ok because folding must include a whitespace char.
if (*source == '\r' || *source == '\n' || *source == '=' || *source == ' ' || *source == '\t')
{
source++;
continue;
}
byte s = s_base64DecodeMap[*source];
if (s == InvalidBase64Value)
{
throw new FormatException(SR.MailBase64InvalidCharacter);
}
switch (ReadState.Pos)
{
case 0:
ReadState.Val = (byte)(s << 2);
ReadState.Pos++;
break;
case 1:
*dest++ = (byte)(ReadState.Val + (s >> 4));
ReadState.Val = unchecked((byte)(s << 4));
ReadState.Pos++;
break;
case 2:
*dest++ = (byte)(ReadState.Val + (s >> 2));
ReadState.Val = unchecked((byte)(s << 6));
ReadState.Pos++;
break;
case 3:
*dest++ = (byte)(ReadState.Val + s);
ReadState.Pos = 0;
break;
}
source++;
}
return (int)(dest - start);
}
}
public int EncodeBytes(byte[] buffer, int offset, int count) =>
EncodeBytes(buffer, offset, count, true, true);
internal int EncodeBytes(byte[] buffer, int offset, int count, bool dontDeferFinalBytes, bool shouldAppendSpaceToCRLF)
{
Debug.Assert(buffer != null, "buffer was null");
Debug.Assert(_writeState != null, "writestate was null");
Debug.Assert(_writeState.Buffer != null, "writestate.buffer was null");
// Add Encoding header, if any. e.g. =?encoding?b?
WriteState.AppendHeader();
int cur = offset;
switch (WriteState.Padding)
{
case 2:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits | ((buffer[cur] & 0xf0) >> 4)]);
if (count == 1)
{
WriteState.LastBits = (byte)((buffer[cur] & 0x0f) << 2);
WriteState.Padding = 1;
cur++;
return cur - offset;
}
WriteState.Append(s_base64EncodeMap[((buffer[cur] & 0x0f) << 2) | ((buffer[cur + 1] & 0xc0) >> 6)]);
WriteState.Append(s_base64EncodeMap[(buffer[cur + 1] & 0x3f)]);
cur += 2;
count -= 2;
WriteState.Padding = 0;
break;
case 1:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits | ((buffer[cur] & 0xc0) >> 6)]);
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0x3f)]);
cur++;
count--;
WriteState.Padding = 0;
break;
}
int calcLength = cur + (count - (count % 3));
// Convert three bytes at a time to base64 notation. This will output 4 chars.
for (; cur < calcLength; cur += 3)
{
if ((_lineLength != -1) && (WriteState.CurrentLineLength + SizeOfBase64EncodedChar + _writeState.FooterLength > _lineLength))
{
WriteState.AppendCRLF(shouldAppendSpaceToCRLF);
}
//how we actually encode: get three bytes in the
//buffer to be encoded. Then, extract six bits at a time and encode each six bit chunk as a base-64 character.
//this means that three bytes of data will be encoded as four base64 characters. It also means that to encode
//a character, we must have three bytes to encode so if the number of bytes is not divisible by three, we
//must pad the buffer (this happens below)
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0xfc) >> 2]);
WriteState.Append(s_base64EncodeMap[((buffer[cur] & 0x03) << 4) | ((buffer[cur + 1] & 0xf0) >> 4)]);
WriteState.Append(s_base64EncodeMap[((buffer[cur + 1] & 0x0f) << 2) | ((buffer[cur + 2] & 0xc0) >> 6)]);
WriteState.Append(s_base64EncodeMap[(buffer[cur + 2] & 0x3f)]);
}
cur = calcLength; //Where we left off before
// See if we need to fold before writing the last section (with possible padding)
if ((count % 3 != 0) && (_lineLength != -1) && (WriteState.CurrentLineLength + SizeOfBase64EncodedChar + _writeState.FooterLength >= _lineLength))
{
WriteState.AppendCRLF(shouldAppendSpaceToCRLF);
}
//now pad this thing if we need to. Since it must be a number of bytes that is evenly divisble by 3,
//if there are extra bytes, pad with '=' until we have a number of bytes divisible by 3
switch (count % 3)
{
case 2: //One character padding needed
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0xFC) >> 2]);
WriteState.Append(s_base64EncodeMap[((buffer[cur] & 0x03) << 4) | ((buffer[cur + 1] & 0xf0) >> 4)]);
if (dontDeferFinalBytes)
{
WriteState.Append(s_base64EncodeMap[((buffer[cur + 1] & 0x0f) << 2)]);
WriteState.Append(s_base64EncodeMap[64]);
WriteState.Padding = 0;
}
else
{
WriteState.LastBits = (byte)((buffer[cur + 1] & 0x0F) << 2);
WriteState.Padding = 1;
}
cur += 2;
break;
case 1: // Two character padding needed
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0xFC) >> 2]);
if (dontDeferFinalBytes)
{
WriteState.Append(s_base64EncodeMap[(byte)((buffer[cur] & 0x03) << 4)]);
WriteState.Append(s_base64EncodeMap[64]);
WriteState.Append(s_base64EncodeMap[64]);
WriteState.Padding = 0;
}
else
{
WriteState.LastBits = (byte)((buffer[cur] & 0x03) << 4);
WriteState.Padding = 2;
}
cur++;
break;
}
// Write out the last footer, if any. e.g. ?=
WriteState.AppendFooter();
return cur - offset;
}
public string GetEncodedString() => Encoding.ASCII.GetString(WriteState.Buffer, 0, WriteState.Length);
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
return ReadAsyncResult.End(asyncResult);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
WriteAsyncResult.End(asyncResult);
}
public override void Flush()
{
if (_writeState != null && WriteState.Length > 0)
{
FlushInternal();
}
base.Flush();
}
private void FlushInternal()
{
base.Write(WriteState.Buffer, 0, WriteState.Length);
WriteState.Reset();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(count));
while (true)
{
// read data from the underlying stream
int read = base.Read(buffer, offset, count);
// if the underlying stream returns 0 then there
// is no more data - ust return 0.
if (read == 0)
{
return 0;
}
// while decoding, we may end up not having
// any bytes to return pending additional data
// from the underlying stream.
read = DecodeBytes(buffer, offset, read);
if (read > 0)
{
return read;
}
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
int written = 0;
// do not append a space when writing from a stream since this means
// it's writing the email body
while (true)
{
written += EncodeBytes(buffer, offset + written, count - written, false, false);
if (written < count)
{
FlushInternal();
}
else
{
break;
}
}
}
private sealed class ReadAsyncResult : LazyAsyncResult
{
private readonly Base64Stream _parent;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _read;
private static readonly AsyncCallback s_onRead = OnRead;
internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
_offset = offset;
_count = count;
}
private bool CompleteRead(IAsyncResult result)
{
_read = _parent.BaseStream.EndRead(result);
// if the underlying stream returns 0 then there
// is no more data - ust return 0.
if (_read == 0)
{
InvokeCallback();
return true;
}
// while decoding, we may end up not having
// any bytes to return pending additional data
// from the underlying stream.
_read = _parent.DecodeBytes(_buffer, _offset, _read);
if (_read > 0)
{
InvokeCallback();
return true;
}
return false;
}
internal void Read()
{
while (true)
{
IAsyncResult result = _parent.BaseStream.BeginRead(_buffer, _offset, _count, s_onRead, this);
if (!result.CompletedSynchronously || CompleteRead(result))
{
break;
}
}
}
private static void OnRead(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
try
{
if (!thisPtr.CompleteRead(result))
{
thisPtr.Read();
}
}
catch (Exception e)
{
if (thisPtr.IsCompleted)
{
throw;
}
thisPtr.InvokeCallback(e);
}
}
}
internal static int End(IAsyncResult result)
{
ReadAsyncResult thisPtr = (ReadAsyncResult)result;
thisPtr.InternalWaitForCompletion();
return thisPtr._read;
}
}
private sealed class WriteAsyncResult : LazyAsyncResult
{
private static readonly AsyncCallback s_onWrite = OnWrite;
private readonly Base64Stream _parent;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _written;
internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
_offset = offset;
_count = count;
}
internal void Write()
{
while (true)
{
// do not append a space when writing from a stream since this means
// it's writing the email body
_written += _parent.EncodeBytes(_buffer, _offset + _written, _count - _written, false, false);
if (_written < _count)
{
IAsyncResult result = _parent.BaseStream.BeginWrite(_parent.WriteState.Buffer, 0, _parent.WriteState.Length, s_onWrite, this);
if (!result.CompletedSynchronously)
{
break;
}
CompleteWrite(result);
}
else
{
InvokeCallback();
break;
}
}
}
private void CompleteWrite(IAsyncResult result)
{
_parent.BaseStream.EndWrite(result);
_parent.WriteState.Reset();
}
private static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
try
{
thisPtr.CompleteWrite(result);
thisPtr.Write();
}
catch (Exception e)
{
if (thisPtr.IsCompleted)
{
throw;
}
thisPtr.InvokeCallback(e);
}
}
}
internal static void End(IAsyncResult result)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result;
thisPtr.InternalWaitForCompletion();
Debug.Assert(thisPtr._written == thisPtr._count);
}
}
private sealed class ReadStateInfo
{
internal byte Val { get; set; }
internal byte Pos { get; set; }
}
}
}
| |
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using MatterHackers.Agg.Image;
namespace MatterHackers.Agg.UI
{
internal class WindowsFormsBitmapBackBuffer
{
internal ImageBuffer backingImageBufferByte;
internal ImageBufferFloat backingImageBufferFloat;
internal Bitmap windowsBitmap;
private BitmapData bitmapData = null;
private bool externallyLocked = false;
private bool currentlyLocked = false;
internal void Lock()
{
bitmapData = windowsBitmap.LockBits(new Rectangle(0, 0, windowsBitmap.Width, windowsBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, windowsBitmap.PixelFormat);
externallyLocked = true;
}
internal void Unlock()
{
windowsBitmap.UnlockBits(bitmapData);
externallyLocked = false;
}
private int numInFunction = 0;
internal void UpdateHardwareSurface(RectangleInt rect)
{
numInFunction++;
if (backingImageBufferByte != null)
{
if (!externallyLocked && !currentlyLocked)
{
currentlyLocked = true;
bitmapData = windowsBitmap.LockBits(new Rectangle(0, 0, windowsBitmap.Width, windowsBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, windowsBitmap.PixelFormat);
}
int backBufferStrideInBytes = backingImageBufferByte.StrideInBytes();
int backBufferStrideInInts = backBufferStrideInBytes / 4;
int backBufferHeight = backingImageBufferByte.Height;
int backBufferHeightMinusOne = backBufferHeight - 1;
int bitmapDataStride = bitmapData.Stride;
int offset;
byte[] buffer = backingImageBufferByte.GetBuffer(out offset);
switch (backingImageBufferByte.BitDepth)
{
case 24:
{
unsafe
{
byte* bitmapDataScan0 = (byte*)bitmapData.Scan0;
fixed (byte* pSourceFixed = &buffer[offset])
{
byte* pSource = pSourceFixed;
byte* pDestBuffer = bitmapDataScan0 + bitmapDataStride * backBufferHeightMinusOne;
for (int y = 0; y < backBufferHeight; y++)
{
int* pSourceInt = (int*)pSource;
int* pDestBufferInt = (int*)pDestBuffer;
for (int x = 0; x < backBufferStrideInInts; x++)
{
pDestBufferInt[x] = pSourceInt[x];
}
for (int x = backBufferStrideInInts * 4; x < backBufferStrideInBytes; x++)
{
pDestBuffer[x] = pSource[x];
}
pDestBuffer -= bitmapDataStride;
pSource += backBufferStrideInBytes;
}
}
}
}
break;
case 32:
{
unsafe
{
byte* bitmapDataScan0 = (byte*)bitmapData.Scan0;
fixed (byte* pSourceFixed = &buffer[offset])
{
byte* pSource = pSourceFixed;
byte* pDestBuffer = bitmapDataScan0 + bitmapDataStride * backBufferHeightMinusOne;
for (int y = rect.Bottom; y < rect.Top; y++)
{
int* pSourceInt = (int*)pSource;
pSourceInt += backBufferStrideInBytes * y / 4;
int* pDestBufferInt = (int*)pDestBuffer;
pDestBufferInt -= bitmapDataStride * y / 4;
for (int x = rect.Left; x < rect.Right; x++)
{
pDestBufferInt[x] = pSourceInt[x];
}
}
}
}
}
break;
default:
throw new NotImplementedException();
}
if (!externallyLocked)
{
windowsBitmap.UnlockBits(bitmapData);
currentlyLocked = false;
}
}
else
{
switch (backingImageBufferFloat.BitDepth)
{
case 128:
{
BitmapData bitmapData = windowsBitmap.LockBits(new Rectangle(0, 0, windowsBitmap.Width, windowsBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, windowsBitmap.PixelFormat);
int index = 0;
unsafe
{
unchecked
{
int offset;
float[] buffer = backingImageBufferFloat.GetBuffer(out offset);
fixed (float* pSource = &buffer[offset])
{
for (int y = 0; y < backingImageBufferFloat.Height; y++)
{
byte* pDestBuffer = (byte*)bitmapData.Scan0 + (bitmapData.Stride * (backingImageBufferFloat.Height - 1 - y));
for (int x = 0; x < backingImageBufferFloat.Width; x++)
{
#if true
pDestBuffer[x * 4 + 0] = (byte)(pSource[index * 4 + 0] * 255);
pDestBuffer[x * 4 + 1] = (byte)(pSource[index * 4 + 1] * 255);
pDestBuffer[x * 4 + 2] = (byte)(pSource[index * 4 + 2] * 255);
pDestBuffer[x * 4 + 3] = (byte)(pSource[index * 4 + 3] * 255);
index++;
#else
pDestBuffer[x * 4 + 0] = (byte)255;
pDestBuffer[x * 4 + 1] = (byte)0;
pDestBuffer[x * 4 + 2] = (byte)128;
pDestBuffer[x * 4 + 3] = (byte)255;
#endif
}
}
}
}
}
windowsBitmap.UnlockBits(bitmapData);
}
break;
default:
throw new NotImplementedException();
}
}
numInFunction--;
}
internal void Initialize(int width, int height, int bitDepth)
{
if (width > 0 && height > 0)
{
switch (bitDepth)
{
case 24:
windowsBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
backingImageBufferByte = new ImageBuffer(width, height, 24, new BlenderBGR());
break;
case 32:
windowsBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
// widowsBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
// widowsBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// 32bppPArgb
backingImageBufferByte = new ImageBuffer(width, height);
break;
case 128:
windowsBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
backingImageBufferByte = null;
backingImageBufferFloat = new ImageBufferFloat(width, height, 128, new BlenderBGRAFloat());
break;
default:
throw new NotImplementedException("Don't support this bit depth yet.");
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.FreeDesktop.DBusMenu;
using Avalonia.Input;
using Avalonia.Threading;
using Tmds.DBus;
#pragma warning disable 1998
namespace Avalonia.FreeDesktop
{
public class DBusMenuExporter
{
public static ITopLevelNativeMenuExporter TryCreate(IntPtr xid)
{
if (DBusHelper.Connection == null)
return null;
return new DBusMenuExporterImpl(DBusHelper.Connection, xid);
}
class DBusMenuExporterImpl : ITopLevelNativeMenuExporter, IDBusMenu, IDisposable
{
private readonly Connection _dbus;
private readonly uint _xid;
private IRegistrar _registar;
private bool _disposed;
private uint _revision = 1;
private NativeMenu _menu;
private Dictionary<int, NativeMenuItemBase> _idsToItems = new Dictionary<int, NativeMenuItemBase>();
private Dictionary<NativeMenuItemBase, int> _itemsToIds = new Dictionary<NativeMenuItemBase, int>();
private readonly HashSet<NativeMenu> _menus = new HashSet<NativeMenu>();
private bool _resetQueued;
private int _nextId = 1;
public DBusMenuExporterImpl(Connection dbus, IntPtr xid)
{
_dbus = dbus;
_xid = (uint)xid.ToInt32();
ObjectPath = new ObjectPath("/net/avaloniaui/dbusmenu/"
+ Guid.NewGuid().ToString().Replace("-", ""));
SetNativeMenu(new NativeMenu());
Init();
}
async void Init()
{
try
{
await _dbus.RegisterObjectAsync(this);
_registar = DBusHelper.Connection.CreateProxy<IRegistrar>(
"com.canonical.AppMenu.Registrar",
"/com/canonical/AppMenu/Registrar");
if (!_disposed)
await _registar.RegisterWindowAsync(_xid, ObjectPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
// It's not really important if this code succeeds,
// and it's not important to know if it succeeds
// since even if we register the window it's not guaranteed that
// menu will be actually exported
}
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_dbus.UnregisterObject(this);
// Fire and forget
_registar?.UnregisterWindowAsync(_xid);
}
public bool IsNativeMenuExported { get; private set; }
public event EventHandler OnIsNativeMenuExportedChanged;
public void SetNativeMenu(NativeMenu menu)
{
if (menu == null)
menu = new NativeMenu();
if (_menu != null)
((INotifyCollectionChanged)_menu.Items).CollectionChanged -= OnMenuItemsChanged;
_menu = menu;
((INotifyCollectionChanged)_menu.Items).CollectionChanged += OnMenuItemsChanged;
DoLayoutReset();
}
/*
This is basic initial implementation, so we don't actually track anything and
just reset the whole layout on *ANY* change
This is not how it should work and will prevent us from implementing various features,
but that's the fastest way to get things working, so...
*/
void DoLayoutReset()
{
_resetQueued = false;
foreach (var i in _idsToItems.Values)
i.PropertyChanged -= OnItemPropertyChanged;
foreach(var menu in _menus)
((INotifyCollectionChanged)menu.Items).CollectionChanged -= OnMenuItemsChanged;
_menus.Clear();
_idsToItems.Clear();
_itemsToIds.Clear();
_revision++;
LayoutUpdated?.Invoke((_revision, 0));
}
void QueueReset()
{
if(_resetQueued)
return;
_resetQueued = true;
Dispatcher.UIThread.Post(DoLayoutReset, DispatcherPriority.Background);
}
private (NativeMenuItemBase item, NativeMenu menu) GetMenu(int id)
{
if (id == 0)
return (null, _menu);
_idsToItems.TryGetValue(id, out var item);
return (item, (item as NativeMenuItem)?.Menu);
}
private void EnsureSubscribed(NativeMenu menu)
{
if(menu!=null && _menus.Add(menu))
((INotifyCollectionChanged)menu.Items).CollectionChanged += OnMenuItemsChanged;
}
private int GetId(NativeMenuItemBase item)
{
if (_itemsToIds.TryGetValue(item, out var id))
return id;
id = _nextId++;
_idsToItems[id] = item;
_itemsToIds[item] = id;
item.PropertyChanged += OnItemPropertyChanged;
if (item is NativeMenuItem nmi)
EnsureSubscribed(nmi.Menu);
return id;
}
private void OnMenuItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
QueueReset();
}
private void OnItemPropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e)
{
QueueReset();
}
public ObjectPath ObjectPath { get; }
async Task<object> IFreeDesktopDBusProperties.GetAsync(string prop)
{
if (prop == "Version")
return 2;
if (prop == "Status")
return "normal";
return 0;
}
async Task<DBusMenuProperties> IFreeDesktopDBusProperties.GetAllAsync()
{
return new DBusMenuProperties
{
Version = 2,
Status = "normal",
};
}
private static string[] AllProperties = new[]
{
"type", "label", "enabled", "visible", "shortcut", "toggle-type", "children-display", "toggle-state", "icon-data"
};
object GetProperty((NativeMenuItemBase item, NativeMenu menu) i, string name)
{
var (it, menu) = i;
if (it is NativeMenuItemSeperator)
{
if (name == "type")
return "separator";
}
else if (it is NativeMenuItem item)
{
if (name == "type")
{
return null;
}
if (name == "label")
return item?.Header ?? "<null>";
if (name == "enabled")
{
if (item == null)
return null;
if (item.Menu != null && item.Menu.Items.Count == 0)
return false;
if (item.IsEnabled == false)
return false;
return null;
}
if (name == "shortcut")
{
if (item?.Gesture == null)
return null;
if (item.Gesture.KeyModifiers == 0)
return null;
var lst = new List<string>();
var mod = item.Gesture;
if ((mod.KeyModifiers & KeyModifiers.Control) != 0)
lst.Add("Control");
if ((mod.KeyModifiers & KeyModifiers.Alt) != 0)
lst.Add("Alt");
if ((mod.KeyModifiers & KeyModifiers.Shift) != 0)
lst.Add("Shift");
if ((mod.KeyModifiers & KeyModifiers.Meta) != 0)
lst.Add("Super");
lst.Add(item.Gesture.Key.ToString());
return new[] { lst.ToArray() };
}
if (name == "toggle-type")
{
if (item.ToggleType == NativeMenuItemToggleType.CheckBox)
return "checkmark";
if (item.ToggleType == NativeMenuItemToggleType.Radio)
return "radio";
}
if (name == "toggle-state")
{
if (item.ToggleType != NativeMenuItemToggleType.None)
return item.IsChecked ? 1 : 0;
}
if (name == "icon-data")
{
if (item.Icon != null)
{
var ms = new MemoryStream();
item.Icon.Save(ms);
return ms.ToArray();
}
}
if (name == "children-display")
return menu != null ? "submenu" : null;
}
return null;
}
private List<KeyValuePair<string, object>> _reusablePropertyList = new List<KeyValuePair<string, object>>();
KeyValuePair<string, object>[] GetProperties((NativeMenuItemBase item, NativeMenu menu) i, string[] names)
{
if (names?.Length > 0 != true)
names = AllProperties;
_reusablePropertyList.Clear();
foreach (var n in names)
{
var v = GetProperty(i, n);
if (v != null)
_reusablePropertyList.Add(new KeyValuePair<string, object>(n, v));
}
return _reusablePropertyList.ToArray();
}
public Task SetAsync(string prop, object val) => Task.CompletedTask;
public Task<(uint revision, (int, KeyValuePair<string, object>[], object[]) layout)> GetLayoutAsync(
int ParentId, int RecursionDepth, string[] PropertyNames)
{
var menu = GetMenu(ParentId);
var rv = (_revision, GetLayout(menu.item, menu.menu, RecursionDepth, PropertyNames));
if (!IsNativeMenuExported)
{
IsNativeMenuExported = true;
Dispatcher.UIThread.Post(() =>
{
OnIsNativeMenuExportedChanged?.Invoke(this, EventArgs.Empty);
});
}
return Task.FromResult(rv);
}
(int, KeyValuePair<string, object>[], object[]) GetLayout(NativeMenuItemBase item, NativeMenu menu, int depth, string[] propertyNames)
{
var id = item == null ? 0 : GetId(item);
var props = GetProperties((item, menu), propertyNames);
var children = (depth == 0 || menu == null) ? new object[0] : new object[menu.Items.Count];
if(menu != null)
for (var c = 0; c < children.Length; c++)
{
var ch = menu.Items[c];
children[c] = GetLayout(ch, (ch as NativeMenuItem)?.Menu, depth == -1 ? -1 : depth - 1, propertyNames);
}
return (id, props, children);
}
public Task<(int, KeyValuePair<string, object>[])[]> GetGroupPropertiesAsync(int[] Ids, string[] PropertyNames)
{
var arr = new (int, KeyValuePair<string, object>[])[Ids.Length];
for (var c = 0; c < Ids.Length; c++)
{
var id = Ids[c];
var item = GetMenu(id);
var props = GetProperties(item, PropertyNames);
arr[c] = (id, props);
}
return Task.FromResult(arr);
}
public async Task<object> GetPropertyAsync(int Id, string Name)
{
return GetProperty(GetMenu(Id), Name) ?? 0;
}
public void HandleEvent(int id, string eventId, object data, uint timestamp)
{
if (eventId == "clicked")
{
var item = GetMenu(id).item;
if (item is NativeMenuItem menuItem && item is INativeMenuItemExporterEventsImplBridge bridge)
{
if (menuItem?.IsEnabled == true)
bridge?.RaiseClicked();
}
}
}
public Task EventAsync(int Id, string EventId, object Data, uint Timestamp)
{
HandleEvent(Id, EventId, Data, Timestamp);
return Task.CompletedTask;
}
public Task<int[]> EventGroupAsync((int id, string eventId, object data, uint timestamp)[] Events)
{
foreach (var e in Events)
HandleEvent(e.id, e.eventId, e.data, e.timestamp);
return Task.FromResult(new int[0]);
}
public async Task<bool> AboutToShowAsync(int Id)
{
return false;
}
public async Task<(int[] updatesNeeded, int[] idErrors)> AboutToShowGroupAsync(int[] Ids)
{
return (new int[0], new int[0]);
}
#region Events
private event Action<((int, IDictionary<string, object>)[] updatedProps, (int, string[])[] removedProps)>
ItemsPropertiesUpdated;
private event Action<(uint revision, int parent)> LayoutUpdated;
private event Action<(int id, uint timestamp)> ItemActivationRequested;
private event Action<PropertyChanges> PropertiesChanged;
async Task<IDisposable> IDBusMenu.WatchItemsPropertiesUpdatedAsync(Action<((int, IDictionary<string, object>)[] updatedProps, (int, string[])[] removedProps)> handler, Action<Exception> onError)
{
ItemsPropertiesUpdated += handler;
return Disposable.Create(() => ItemsPropertiesUpdated -= handler);
}
async Task<IDisposable> IDBusMenu.WatchLayoutUpdatedAsync(Action<(uint revision, int parent)> handler, Action<Exception> onError)
{
LayoutUpdated += handler;
return Disposable.Create(() => LayoutUpdated -= handler);
}
async Task<IDisposable> IDBusMenu.WatchItemActivationRequestedAsync(Action<(int id, uint timestamp)> handler, Action<Exception> onError)
{
ItemActivationRequested+= handler;
return Disposable.Create(() => ItemActivationRequested -= handler);
}
async Task<IDisposable> IFreeDesktopDBusProperties.WatchPropertiesAsync(Action<PropertyChanges> handler)
{
PropertiesChanged += handler;
return Disposable.Create(() => PropertiesChanged -= handler);
}
#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 Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace System.Net.NetworkInformation
{
internal class SystemNetworkInterface : NetworkInterface
{
private readonly string _name;
private readonly string _id;
private readonly string _description;
private readonly byte[] _physicalAddress;
private readonly uint _addressLength;
private readonly NetworkInterfaceType _type;
private readonly OperationalStatus _operStatus;
private readonly long _speed;
// Any interface can have two completely different valid indexes for ipv4 and ipv6.
private readonly uint _index = 0;
private readonly uint _ipv6Index = 0;
private readonly Interop.IpHlpApi.AdapterFlags _adapterFlags;
private readonly SystemIPInterfaceProperties _interfaceProperties = null;
internal static int InternalLoopbackInterfaceIndex
{
get
{
return GetBestInterfaceForAddress(IPAddress.Loopback);
}
}
internal static int InternalIPv6LoopbackInterfaceIndex
{
get
{
return GetBestInterfaceForAddress(IPAddress.IPv6Loopback);
}
}
private static int GetBestInterfaceForAddress(IPAddress addr)
{
int index;
Internals.SocketAddress address = new Internals.SocketAddress(addr);
int error = (int)Interop.IpHlpApi.GetBestInterfaceEx(address.Buffer, out index);
if (error != 0)
{
throw new NetworkInformationException(error);
}
return index;
}
internal static bool InternalGetIsNetworkAvailable()
{
try
{
NetworkInterface[] networkInterfaces = GetNetworkInterfaces();
foreach (NetworkInterface netInterface in networkInterfaces)
{
if (netInterface.OperationalStatus == OperationalStatus.Up && netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel
&& netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
return true;
}
}
}
catch (NetworkInformationException nie)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie);
}
return false;
}
internal static NetworkInterface[] GetNetworkInterfaces()
{
AddressFamily family = AddressFamily.Unspecified;
uint bufferSize = 0;
SafeLocalAllocHandle buffer = null;
Interop.IpHlpApi.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo();
List<SystemNetworkInterface> interfaceList = new List<SystemNetworkInterface>();
Interop.IpHlpApi.GetAdaptersAddressesFlags flags =
Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeGateways
| Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeWins;
// Figure out the right buffer size for the adapter information.
uint result = Interop.IpHlpApi.GetAdaptersAddresses(
family, (uint)flags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref bufferSize);
while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW)
{
// Allocate the buffer and get the adapter info.
using (buffer = SafeLocalAllocHandle.LocalAlloc((int)bufferSize))
{
result = Interop.IpHlpApi.GetAdaptersAddresses(
family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize);
// If succeeded, we're going to add each new interface.
if (result == Interop.IpHlpApi.ERROR_SUCCESS)
{
// Linked list of interfaces.
IntPtr ptr = buffer.DangerousGetHandle();
while (ptr != IntPtr.Zero)
{
// Traverse the list, marshal in the native structures, and create new NetworkInterfaces.
Interop.IpHlpApi.IpAdapterAddresses adapterAddresses = Marshal.PtrToStructure<Interop.IpHlpApi.IpAdapterAddresses>(ptr);
interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses));
ptr = adapterAddresses.next;
}
}
}
}
// If we don't have any interfaces detected, return empty.
if (result == Interop.IpHlpApi.ERROR_NO_DATA || result == Interop.IpHlpApi.ERROR_INVALID_PARAMETER)
{
return new SystemNetworkInterface[0];
}
// Otherwise we throw on an error.
if (result != Interop.IpHlpApi.ERROR_SUCCESS)
{
throw new NetworkInformationException((int)result);
}
return interfaceList.ToArray();
}
internal SystemNetworkInterface(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses)
{
// Store the common API information.
_id = ipAdapterAddresses.AdapterName;
_name = ipAdapterAddresses.friendlyName;
_description = ipAdapterAddresses.description;
_index = ipAdapterAddresses.index;
_physicalAddress = ipAdapterAddresses.address;
_addressLength = ipAdapterAddresses.addressLength;
_type = ipAdapterAddresses.type;
_operStatus = ipAdapterAddresses.operStatus;
_speed = unchecked((long)ipAdapterAddresses.receiveLinkSpeed);
// API specific info.
_ipv6Index = ipAdapterAddresses.ipv6Index;
_adapterFlags = ipAdapterAddresses.flags;
_interfaceProperties = new SystemIPInterfaceProperties(fixedInfo, ipAdapterAddresses);
}
public override string Id { get { return _id; } }
public override string Name { get { return _name; } }
public override string Description { get { return _description; } }
public override PhysicalAddress GetPhysicalAddress()
{
byte[] newAddr = new byte[_addressLength];
// Buffer.BlockCopy only supports int while addressLength is uint (see IpAdapterAddresses).
// Will throw OverflowException if addressLength > Int32.MaxValue.
Buffer.BlockCopy(_physicalAddress, 0, newAddr, 0, checked((int)_addressLength));
return new PhysicalAddress(newAddr);
}
public override NetworkInterfaceType NetworkInterfaceType { get { return _type; } }
public override IPInterfaceProperties GetIPProperties()
{
return _interfaceProperties;
}
public override IPv4InterfaceStatistics GetIPv4Statistics()
{
return new SystemIPv4InterfaceStatistics(_index);
}
public override IPInterfaceStatistics GetIPStatistics()
{
return new SystemIPInterfaceStatistics(_index);
}
public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
{
if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6
&& ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0))
{
return true;
}
if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4
&& ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0))
{
return true;
}
return false;
}
// We cache this to be consistent across all platforms.
public override OperationalStatus OperationalStatus
{
get
{
return _operStatus;
}
}
public override long Speed
{
get
{
return _speed;
}
}
public override bool IsReceiveOnly
{
get
{
return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.ReceiveOnly) > 0);
}
}
/// <summary>The interface doesn't allow multicast.</summary>
public override bool SupportsMulticast
{
get
{
return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.NoMulticast) == 0);
}
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using cs_leaktest;
namespace cs_unittest
{
[TestClass]
public class TestWrapped : TestWrappedBase
{
[TestCategory("Command line through marshalling")]
[TestMethod]
public void Test1and2()
{
Run("cs_test.Test1and2Class", "Test1and2");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test1()
{
Run("cs_unittest.TestAll", "CommandLine_Test1");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test2()
{
Run("cs_unittest.TestAll", "CommandLine_Test2");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test3()
{
Run("cs_unittest.TestAll", "CommandLine_Test3");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test4()
{
Run("cs_unittest.TestAll", "CommandLine_Test4");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test5()
{
Run("cs_unittest.TestAll", "CommandLine_Test5");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test6()
{
Run("cs_unittest.TestAll", "CommandLine_Test6");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test7()
{
Run("cs_unittest.TestAll", "CommandLine_Test7");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test8()
{
Run("cs_unittest.TestAll", "CommandLine_Test8");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test11()
{
Run("cs_unittest.TestAll", "CommandLine_Test11");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test12()
{
Run("cs_unittest.TestAll", "CommandLine_Test12");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test15()
{
Run("cs_unittest.TestAll", "CommandLine_Test15");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test21()
{
Run("cs_unittest.TestAll", "CommandLine_Test21");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test22()
{
Run("cs_unittest.TestAll", "CommandLine_Test22");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test27()
{
Run("cs_unittest.TestAll", "CommandLine_Test27");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test28()
{
Run("cs_unittest.TestAll", "CommandLine_Test28");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test29()
{
Run("cs_unittest.TestAll", "CommandLine_Test29");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test30()
{
Run("cs_unittest.TestAll", "CommandLine_Test30");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test35()
{
Run("cs_unittest.TestAll", "CommandLine_Test35");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test36()
{
Run("cs_unittest.TestAll", "CommandLine_Test36");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test37()
{
Run("cs_unittest.TestAll", "CommandLine_Test37");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test38()
{
Run("cs_unittest.TestAll", "CommandLine_Test38");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test39()
{
Run("cs_unittest.TestAll", "CommandLine_Test39");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test40()
{
Run("cs_unittest.TestAll", "CommandLine_Test40");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test41()
{
Run("cs_unittest.TestAll", "CommandLine_Test41");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test62()
{
Run("cs_unittest.TestAll", "CommandLine_Test62");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test63()
{
Run("cs_unittest.TestAll", "CommandLine_Test63");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test64()
{
Run("cs_unittest.TestAll", "CommandLine_Test64");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test72()
{
Run("cs_unittest.TestAll", "CommandLine_Test72");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test73()
{
Run("cs_unittest.TestAll", "CommandLine_Test73");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test74()
{
Run("cs_unittest.TestAll", "CommandLine_Test74");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test75()
{
Run("cs_unittest.TestAll", "CommandLine_Test75");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test76()
{
Run("cs_unittest.TestAll", "CommandLine_Test76");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test78()
{
Run("cs_unittest.TestAll", "CommandLine_Test78");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test79()
{
Run("cs_unittest.TestAll", "CommandLine_Test79");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test80()
{
Run("cs_unittest.TestAll", "CommandLine_Test80");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test81()
{
Run("cs_unittest.TestAll", "CommandLine_Test81");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test82()
{
Run("cs_unittest.TestAll", "CommandLine_Test82");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test83()
{
Run("cs_unittest.TestAll", "CommandLine_Test83");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test88()
{
Run("cs_unittest.TestAll", "CommandLine_Test88");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test90()
{
Run("cs_unittest.TestAll", "CommandLine_Test90");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test94()
{
Run("cs_unittest.TestAll", "CommandLine_Test94");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test95()
{
Run("cs_unittest.TestAll", "CommandLine_Test95");
}
[TestCategory("Command line")]
[TestMethod]
public void CommandLine_Test97()
{
Run("cs_unittest.TestAll", "CommandLine_Test97");
}
[TestMethod]
public void TestAllReduce()
{
Run("cs_unittest.TestAllReduceClass", "TestAllReduce");
}
[TestMethod]
public void TestExampleCacheForLearning()
{
Run("cs_unittest.TestExampleCacheCases", "TestExampleCacheForLearning");
}
[TestMethod]
public void TestExampleCacheDisabledForLearning()
{
Run("cs_unittest.TestExampleCacheCases", "TestExampleCacheDisabledForLearning");
}
[TestMethod]
public void TestExampleCache()
{
Run("cs_unittest.TestExampleCacheCases", "TestExampleCache");
}
[TestMethod]
public void TestHash()
{
Run("cs_unittest.TestManagedHash", "TestHash");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestEnumerize()
{
Run("cs_unittest.TestMarshalling", "TestEnumerize");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestString()
{
Run("cs_unittest.TestMarshalling", "TestString");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestStringFeatureGroup()
{
Run("cs_unittest.TestMarshalling", "TestStringFeatureGroup");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestStringNamespace()
{
Run("cs_unittest.TestMarshalling", "TestStringNamespace");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestStringEscape()
{
Run("cs_unittest.TestMarshalling", "TestStringEscape");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestStringSplit()
{
Run("cs_unittest.TestMarshalling", "TestStringSplit");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionary()
{
Run("cs_unittest.TestMarshalling", "TestDictionary");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestCustomType()
{
Run("cs_unittest.TestMarshalling", "TestCustomType");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestEnumerableString()
{
Run("cs_unittest.TestMarshalling", "TestEnumerableString");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestEnumerableKV()
{
Run("cs_unittest.TestMarshalling", "TestEnumerableKV");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestComplexType()
{
Run("cs_unittest.TestMarshalling", "TestComplexType");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestEnumerizePosition()
{
Run("cs_unittest.TestMarshalling", "TestEnumerizePosition");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestBool()
{
Run("cs_unittest.TestMarshalling", "TestBool");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt64Overflow()
{
Run("cs_unittest.TestMarshallingOverflow", "TestNumericInt64Overflow");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt64Overflow()
{
Run("cs_unittest.TestMarshallingOverflow", "TestNumericUInt64Overflow");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericDoubleOverflow()
{
Run("cs_unittest.TestMarshallingOverflow", "TestNumericDoubleOverflow");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt64OverflowArray()
{
Run("cs_unittest.TestMarshallingOverflow", "TestNumericInt64OverflowArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt64OverflowArray()
{
Run("cs_unittest.TestMarshallingOverflow", "TestNumericUInt64OverflowArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericDoubleOverflowArray()
{
Run("cs_unittest.TestMarshallingOverflow", "TestNumericDoubleOverflowArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16UInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16UInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16Single()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16Single");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16Int64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16Int64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16UInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16UInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16Double()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16Double");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericByteArray()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericByteArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericByteArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericByteArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericSByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericSByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericSByteArray()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericSByteArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericSByteArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericSByteArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt16Array()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt16Array");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt16ArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt16ArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt32Array()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt32Array");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt32ArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt32ArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt16Array()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt16Array");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt16ArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt16ArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt32Array()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt32Array");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt32ArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt32ArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericSingle()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericSingle");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericSingleArray()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericSingleArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericSingleArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericSingleArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt64Array()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt64Array");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericInt64ArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericInt64ArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt64Array()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt64Array");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericUInt64ArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericUInt64ArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericDouble()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericDouble");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericDoubleArray()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericDoubleArray");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestNumericDoubleArrayAnchor()
{
Run("cs_unittest.TestMarshalNumeric", "TestNumericDoubleArrayAnchor");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteString()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteString");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteSByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteSByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteUInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteUInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteUInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteUInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteSingle()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteSingle");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteUInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteUInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryByteDouble()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryByteDouble");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteString()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteString");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteSByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteSByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteUInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteUInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteUInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteUInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteSingle()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteSingle");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteUInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteUInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionarySByteDouble()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionarySByteDouble");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16String()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16String");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16Byte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16Byte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16SByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16SByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16Int16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16Int16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16Int32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16Int32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16UInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16UInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16UInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16UInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16Single()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16Single");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16Int64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16Int64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16UInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16UInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt16Double()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt16Double");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32String()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32String");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32Byte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32Byte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32SByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32SByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32Int16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32Int16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32Int32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32Int32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32UInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32UInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32UInt32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32UInt32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32Single()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32Single");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32Int64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32Int64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32UInt64()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32UInt64");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryInt32Double()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryInt32Double");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16String()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16String");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16Byte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16Byte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16SByte()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16SByte");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16Int16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16Int16");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16Int32()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16Int32");
}
[TestCategory("Marshal")]
[TestMethod]
public void TestDictionaryUInt16UInt16()
{
Run("cs_unittest.TestMarshalNumeric", "TestDictionaryUInt16UInt16");
}
[TestCategory("Model Loading")]
[TestMethod]
public void TestLoadModelCorrupt()
{
Run("cs_unittest.TestModelLoading", "TestLoadModelCorrupt");
}
[TestCategory("Model Loading")]
[TestMethod]
public void TestLoadModel()
{
Run("cs_unittest.TestModelLoading", "TestLoadModel");
}
[TestCategory("Model Loading")]
[TestMethod]
public void TestLoadModelRandomCorrupt()
{
Run("cs_unittest.TestModelLoading", "TestLoadModelRandomCorrupt");
}
[TestCategory("Model Loading")]
[TestMethod]
public void TestLoadModelInMemory()
{
Run("cs_unittest.TestModelLoading", "TestLoadModelInMemory");
}
[TestCategory("Model Loading")]
[TestMethod]
public void TestID()
{
Run("cs_unittest.TestModelLoading", "TestID");
}
[TestCategory("Model Loading")]
[TestMethod]
public void TestReload()
{
Run("cs_unittest.TestModelLoading", "TestReload");
}
[TestCategory("Null")]
[TestMethod]
public void TestNull1()
{
Run("cs_unittest.TestNull", "TestNull1");
}
[TestCategory("Null")]
[TestMethod]
public void TestNull2()
{
Run("cs_unittest.TestNull", "TestNull2");
}
[TestCategory("Null")]
[TestMethod]
public void TestNull3()
{
Run("cs_unittest.TestNull", "TestNull3");
}
[TestCategory("Null")]
[TestMethod]
public void TestNull4()
{
Run("cs_unittest.TestNull", "TestNull4");
}
[TestCategory("Null")]
[TestMethod]
public void TestNull5()
{
Run("cs_unittest.TestNull", "TestNull5");
}
[TestMethod]
public void TestCustomFeaturizer()
{
Run("cs_unittest.TestSerializer", "TestCustomFeaturizer");
}
[TestMethod]
public void TestCustomFeaturizerOverideMethod()
{
Run("cs_unittest.TestSerializer", "TestCustomFeaturizerOverideMethod");
}
[TestCategory("Command line through marshalling")]
[TestMethod]
public void Test3()
{
Run("cs_unittest.Test3Class", "Test3");
}
[TestCategory("Command line through marshalling")]
[TestMethod]
public void Test4and6()
{
Run("cs_unittest.Test3Class", "Test4and6");
}
[TestCategory("Command line through marshalling")]
[TestMethod]
public void Test5()
{
Run("cs_unittest.Test3Class", "Test5");
}
[TestCategory("Command line through marshalling")]
[TestMethod]
public void Test7and8()
{
Run("cs_unittest.Test3Class", "Test7and8");
}
[TestCategory("Command line through marshalling")]
[TestMethod]
public void Test87()
{
Run("cs_unittest.TestCbAdfClass", "Test87");
}
[TestMethod]
public void TestSharedModel()
{
Run("cs_unittest.TestCbAdfClass", "TestSharedModel");
}
[TestMethod]
public void TestAntlr()
{
Run("cs_unittest.TestAntlrClass", "TestAntlr");
}
[TestMethod]
public void VwCleanupTest()
{
Run("cs_unittest.TestWrapper", "VwCleanupTest");
}
[TestMethod]
public void VwCleanupTestError()
{
Run("cs_unittest.TestWrapper", "VwCleanupTestError");
}
[TestMethod]
public void VwModelRefCountingTest()
{
Run("cs_unittest.TestWrapper", "VwModelRefCountingTest");
}
}
}
| |
using System;
using System.Collections;
using xmljr.math;
namespace Pantry.Algorithms.Intersections
{
public class RayTriangle
{
public double Distance;
public Vector3 Point;
public object o;
public static RayTriangle Test(Vector3 V0, Vector3 V1, Vector3 V2, Vector3 Source, Vector3 Direction)
{
Vector3 D1 = V1 + (- V0);
Vector3 D2 = V2 + (- V0);
Vector3 N = Vector3.cross(D1,D2);
Vector3 R = Direction * 100000;
double Delta = - Vector3.dot3(R, N);
if(Math.Abs(Delta) > 0.00000001)
{
Vector3 B = Source + (- V0);
double Lambda = Vector3.dot3(B, N) / Delta;
if(0 <= Lambda && Lambda <= 1)
{
Vector3 U = Vector3.cross(B,R);
double u1 = Vector3.dot3(D2,U)/Delta;
double u2 = -Vector3.dot3(D1,U)/Delta;
if( (u1+u2) <= 1.00000001 && u1 >= -0.0000001 && u2 >= -0.0000001)
{
RayTriangle RIT = new RayTriangle();
RIT.Distance = Lambda * 100000;
RIT.Point = Source + R * Lambda;
return RIT;
}
}
}
return null;
}
}
/// <summary>
/// Summary description for TestBoxAndTriangle.
/// </summary>
class BoxTriangle
{
/*
#define AXISTEST_X01(a, b, fa, fb) \
p0 = a*v0[Y] - b*v0[Z]; \
p2 = a*v2[Y] - b*v2[Z]; \
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \
rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; \
if(min>rad || max<-rad) return 0;
*/
public static bool AxisTestX01(double a, double b, double FA, double FB, Vector3 V0, Vector3 V1, Vector3 V2, Vector3 HalfSize)
{
double p0 = a * V0.y - b * V0.z;
double p2 = a * V2.y - b * V2.z;
double min = p2;
double max = p0;
if(p0 < p2)
{
min = p0;
max = p2;
}
double rad = FA * HalfSize.y + FB * HalfSize.z;
if(min > rad || max < -rad) return true;
return false;
}
/*
#define AXISTEST_X2(a, b, fa, fb) \
p0 = a*v0[Y] - b*v0[Z]; \
p1 = a*v1[Y] - b*v1[Z]; \
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; \
if(min>rad || max<-rad) return 0;
*/
public static bool AxisTestX2(double a, double b, double FA, double FB, Vector3 V0, Vector3 V1, Vector3 V2, Vector3 HalfSize)
{
double p0 = a * V0.y - b * V0.z;
double p1 = a * V1.y - b * V1.z;
double min = p1;
double max = p0;
if(p0 < p1)
{
min = p0;
max = p1;
}
double rad = FA * HalfSize.y + FB * HalfSize.z;
if(min > rad || max < -rad) return true;
return false;
}
/*
#define AXISTEST_Y02(a, b, fa, fb) \
p0 = -a*v0[X] + b*v0[Z]; \
p2 = -a*v2[X] + b*v2[Z]; \
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \
rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; \
if(min>rad || max<-rad) return 0;
*/
public static bool AxisTestY02(double a, double b, double FA, double FB, Vector3 V0, Vector3 V1, Vector3 V2, Vector3 HalfSize)
{
double p0 = -a * V0.x + b * V0.z;
double p2 = -a * V2.x + b * V2.z;
double min = p2;
double max = p0;
if(p0 < p2)
{
min = p0;
max = p2;
}
double rad = FA * HalfSize.x + FB * HalfSize.z;
if(min > rad || max < -rad) return true;
return false;
}
/*
#define AXISTEST_Y1(a, b, fa, fb) \
p0 = -a*v0[X] + b*v0[Z]; \
p1 = -a*v1[X] + b*v1[Z]; \
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; \
if(min>rad || max<-rad) return 0;
*/
public static bool AxisTestY1(double a, double b, double FA, double FB, Vector3 V0, Vector3 V1, Vector3 V2, Vector3 HalfSize)
{
double p0 = -a * V0.x + b * V0.z;
double p1 = -a * V1.x + b * V1.z;
double min = p1;
double max = p0;
if(p0 < p1)
{
min = p0;
max = p1;
}
double rad = FA * HalfSize.x + FB * HalfSize.z;
if(min > rad || max < -rad) return true;
return false;
}
/*
#define AXISTEST_Z12(a, b, fa, fb) \
p1 = a*v1[X] - b*v1[Y]; \
p2 = a*v2[X] - b*v2[Y]; \
if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} \
rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; \
if(min>rad || max<-rad) return 0;
*/
public static bool AxisTestZ12(double a, double b, double FA, double FB, Vector3 V0, Vector3 V1, Vector3 V2, Vector3 HalfSize)
{
double p1 = a * V1.x - b * V1.y;
double p2 = a * V2.x - b * V2.y;
double min = p2;
double max = p1;
if(p1 < p2)
{
min = p1;
max = p2;
}
double rad = FA * HalfSize.x + FB * HalfSize.y;
if(min > rad || max < -rad) return true;
return false;
}
/*
#define AXISTEST_Z0(a, b, fa, fb) \
p0 = a*v0[X] - b*v0[Y]; \
p1 = a*v1[X] - b*v1[Y]; \
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; \
if(min>rad || max<-rad) return 0;
*/
public static bool AxisTestZ0(double a, double b, double FA, double FB, Vector3 V0, Vector3 V1, Vector3 V2, Vector3 HalfSize)
{
double p0 = a * V0.x - b * V0.y;
double p1 = a * V1.x - b * V1.y;
double min = p1;
double max = p0;
if(p0 < p1)
{
min = p0;
max = p1;
}
double rad = FA * HalfSize.x + FB * HalfSize.y;
if(min > rad || max < -rad) return true;
return false;
}
public static bool TestPlaneHalfSizeBox(Vector3 Normal, double D, Vector3 HalfSize)
{
bool Neg = false;
bool Pos = false;
Vector3 T = new Vector3();
T.x = HalfSize.x; T.y = HalfSize.y; T.z = HalfSize.z;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x; T.y = HalfSize.y; T.z = HalfSize.z * -1;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x; T.y = HalfSize.y * -1; T.z = HalfSize.z;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x; T.y = HalfSize.y * -1; T.z = HalfSize.z * -1;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x * -1; T.y = HalfSize.y; T.z = HalfSize.z;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x * -1; T.y = HalfSize.y; T.z = HalfSize.z * -1;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x * -1; T.y = HalfSize.y * -1; T.z = HalfSize.z;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
T.x = HalfSize.x * -1; T.y = HalfSize.y * -1; T.z = HalfSize.z * -1;
Neg = Neg || 0 > (Vector3.dot3(T, Normal) + D);
Pos = Pos || 0 <= (Vector3.dot3(T, Normal) + D);
if(Neg && Pos) return true;
return false;
}
public static bool TestTripleMinMax(double a, double b, double c, double h)
{
/*
FINDMINMAX(v0[X],v1[X],v2[X],min,max);
if(min>boxhalfsize[X] || max<-boxhalfsize[X]) return 0;
*/
double min = a;
if(b < min) min = b;
if(c < min) min = c;
double max = a;
if(b > max) max = b;
if(c > max) max = c;
return (min > h || max < -h);
}
public static bool TestBoxVsTriangle(Vector3 Center, Vector3 HalfSize, Vector3 A, Vector3 B, Vector3 C)
{
/*
SUB(v0,triverts[0],boxcenter);
SUB(v1,triverts[1],boxcenter);
SUB(v2,triverts[2],boxcenter);
*/
Vector3 V0 = (A as Vector3) + (-Center);
Vector3 V1 = (B as Vector3) + (-Center);
Vector3 V2 = (C as Vector3) + (-Center);
/*
SUB(e0,v1,v0);
SUB(e1,v2,v1);
SUB(e2,v0,v2);
*/
Vector3 E0 = V1 + (- V0);
Vector3 E1 = V2 + (- V1);
Vector3 E2 = V0 + (- V2);
/* Bullet 3: */
Vector3 FE;
FE = E0.copy(); FE.pos();
//AXISTEST_X01(e0[Z], e0[Y], fez, fey);
if(AxisTestX01(E0.z, E0.y, FE.z, FE.y, V0, V1, V2, HalfSize)) return false;
//AXISTEST_Y02(e0[Z], e0[X], fez, fex);
if(AxisTestY02(E0.z, E0.x, FE.z, FE.x, V0, V1, V2, HalfSize)) return false;
//AXISTEST_Z12(e0[Y], e0[X], fey, fex);
if(AxisTestZ12(E0.y, E0.x, FE.y, FE.x, V0, V1, V2, HalfSize)) return false;
FE = E1.copy(); FE.pos();
//AXISTEST_X01(e1[Z], e1[Y], fez, fey);
if(AxisTestX01(E1.z, E1.y, FE.z, FE.y, V0, V1, V2, HalfSize)) return false;
//AXISTEST_Y02(e1[Z], e1[X], fez, fex);
if(AxisTestY02(E1.z, E1.x, FE.z, FE.x, V0, V1, V2, HalfSize)) return false;
//AXISTEST_Z0(e1[Y], e1[X], fey, fex);
if(AxisTestZ0(E1.y, E1.x, FE.y, FE.x, V0, V1, V2, HalfSize)) return false;
FE = E2.copy(); FE.pos();
//AXISTEST_X2(e2[Z], e2[Y], fez, fey);
if(AxisTestX2(E2.z, E2.y, FE.z, FE.y, V0, V1, V2, HalfSize)) return false;
//AXISTEST_Y1(e2[Z], e2[X], fez, fex);
if(AxisTestY1(E2.z, E2.x, FE.z, FE.x, V0, V1, V2, HalfSize)) return false;
//AXISTEST_Z12(e2[Y], e2[X], fey, fex);
if(AxisTestZ12(E2.y, E2.x, FE.y, FE.x, V0, V1, V2, HalfSize)) return false;
/* Bullet 1: */
/*
FINDMINMAX(v0[X],v1[X],v2[X],min,max);
if(min>boxhalfsize[X] || max<-boxhalfsize[X]) return 0;
*/
if(TestTripleMinMax(V0.x,V1.x,V2.x,HalfSize.x)) return false;
/*
FINDMINMAX(v0[Y],v1[Y],v2[Y],min,max);
if(min>boxhalfsize[Y] || max<-boxhalfsize[Y]) return 0;
*/
if(TestTripleMinMax(V0.y,V1.y,V2.y,HalfSize.y)) return false;
/*
FINDMINMAX(v0[Z],v1[Z],v2[Z],min,max);
if(min>boxhalfsize[Z] || max<-boxhalfsize[Z]) return 0;
*/
if(TestTripleMinMax(V0.z,V1.z,V2.z,HalfSize.z)) return false;
/* Bullet 2: */
Vector3 Normal = Vector3.cross( E0, E1 );
double D = - Vector3.dot3(Normal, V0);
return TestPlaneHalfSizeBox(Normal, D, HalfSize);
}
public static bool TestBoxVsAllTriangles(Vector3 Center, Vector3 HalfSize, ArrayList Triangle)
{
// we build the box composed of m + \lambda d * <1,0,0> + \gamma d * <0,1,0> + \delta d <0,0,1> where <\lambda,\gamma,\delta> \in [0,1]x[0,1],[0,1]
for(int T = 0; T < Triangle.Count; T+=3)
{
if(TestBoxVsTriangle(Center, HalfSize, Triangle[T+0] as Vector3,
Triangle[T+1] as Vector3,
Triangle[T+2] as Vector3)) return true;
}
// ok, so I need to compile the BSP
return false;
}
public static bool TestX(AABB B, Vector3 H)
{
return (B.Position.x + B.Dimension.x <= -H.x) || (B.Position.x >= H.x);
}
public static bool TestY(AABB B, Vector3 H)
{
return (B.Position.y + B.Dimension.y <= -H.y) || (B.Position.y >= H.y);
}
public static bool TestZ(AABB B, Vector3 H)
{
return (B.Position.z + B.Dimension.z <= -H.z) || (B.Position.z >= H.z);
}
/*
public static bool TestBoxVsAABBNetwork(Vector3 Center, Vector3 HalfSize, AxisAlignedBoundingBoxNetwork N)
{
if(N==null) return false;
AABB NewB = new AABB();
NewB.Position = N.Bounds.Position + (-Center);
NewB.Dimension = N.Bounds.Dimension;
if(TestX(NewB,HalfSize)) return false;
if(TestY(NewB,HalfSize)) return false;
if(TestZ(NewB,HalfSize)) return false;
if(N.TL == null)
{
if(TestBoxVsAABBNetwork(Center,HalfSize, N.A)) return true;
if(TestBoxVsAABBNetwork(Center,HalfSize, N.B)) return true;
}
else
{
if(TestBoxVsTriangle(Center, HalfSize, N.TL.A, N.TL.B, N.TL.C)) return true;
}
return false;
}
*/
}
}
| |
using System;
using System.Xml;
using nHydrate.Generator.Common.GeneratorFramework;
using nHydrate.Generator.Common.Util;
namespace nHydrate.Generator.Models
{
/// <summary>
/// This is the base for all column classes
/// </summary>
public abstract class ColumnBase : BaseModelObject, ICodeFacadeObject
{
#region Member Variables
protected const System.Data.SqlDbType _def_type = System.Data.SqlDbType.VarChar;
protected const int _def_length = 50;
protected const int _def_scale = 0;
protected const bool _def_allowNull = true;
protected const string _def_description = "";
protected const string _def_prompt = "";
protected const string _def_codefacade = "";
protected System.Data.SqlDbType _dataType = _def_type;
protected int _length = _def_length;
protected int _scale = _def_scale;
protected bool _allowNull = _def_allowNull;
#endregion
#region Constructor
protected ColumnBase(INHydrateModelObject root)
: base(root)
{
}
#endregion
#region Property Implementations
public virtual string Description { get; set; } = _def_description;
public virtual string Prompt { get; set; } = _def_prompt;
public virtual int Length
{
get
{
var retval = this.PredefinedSize;
if (retval == -1) retval = _length;
return retval;
}
set
{
if (value < 0) value = 0;
_length = value;
}
}
public virtual int Scale
{
get
{
var retval = this.PredefinedScale;
if (retval == -1) retval = _scale;
return retval;
}
set
{
if (value < 0) value = 0;
_scale = value;
}
}
public virtual System.Data.SqlDbType DataType
{
get { return _dataType; }
set
{
_length = this.GetDefaultSize(value);
_dataType = value;
}
}
public virtual bool AllowNull
{
get { return this.DataType != System.Data.SqlDbType.Variant && _allowNull; }
set { _allowNull = value; }
}
public virtual string DatabaseType => this.GetSQLDefaultType();
#region ICodeFacadeObject Members
public string CodeFacade { get; set; } = _def_codefacade;
public string GetCodeFacade()
{
if (this.CodeFacade == string.Empty)
return this.Name;
else
return this.CodeFacade;
}
#endregion
#endregion
#region Methods
/// <summary>
/// Determines if this data type supports a user-defined size
/// </summary>
public virtual bool IsDefinedSize => this.PredefinedSize != -1;
/// <summary>
/// Determines if this data type supports a user-defined scale
/// </summary>
public virtual bool IsDefinedScale
{
get { return this.PredefinedScale == 0; }
}
/// <summary>
/// Determines if this field has no max length defined
/// </summary>
/// <returns></returns>
public virtual bool IsMaxLength()
{
switch (this.DataType)
{
case System.Data.SqlDbType.VarChar:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.VarBinary:
return (this.Length == 0);
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.NText:
return true;
default:
return false;
}
}
public virtual string GetLengthString()
{
if (this.DataType.SupportsMax() && this.Length == 0)
return "max";
else
return this.Length.ToString();
}
/// <summary>
/// This is the length used for annotations and meta data for class descriptions
/// </summary>
public virtual int GetAnnotationStringLength()
{
switch (this.DataType)
{
case System.Data.SqlDbType.NText:
return 1073741823;
case System.Data.SqlDbType.Text:
return int.MaxValue;
case System.Data.SqlDbType.Image:
return int.MaxValue;
}
if (this.DataType.SupportsMax() && this.Length == 0)
return int.MaxValue;
else
return this.Length;
}
public override string ToString()
{
var retval = this.Name;
return retval;
}
#endregion
public abstract override void XmlAppend(XmlNode node);
public abstract override void XmlLoad(XmlNode node);
#region Helpers
public abstract Reference CreateRef();
public abstract Reference CreateRef(string key);
public virtual string CamelName => StringHelper.FirstCharToLower(this.PascalName);
public virtual string PascalName
{
get
{
if (!string.IsNullOrEmpty(this.CodeFacade)) return this.CodeFacade;
else return this.Name;
}
}
public virtual string DatabaseName
{
get { return this.Name; }
}
/// <summary>
/// Gets the SQL Server type mapping for this data type
/// </summary>
public virtual string GetSQLDefaultType()
{
return GetSQLDefaultType(false);
}
/// <summary>
/// Gets the SQL Server type mapping for this data type
/// </summary>
/// <param name="isRaw">Determines if the square brackets '[]' are around the type</param>
/// <returns>The SQL ready datatype like '[Int]' or '[Varchar] (100)'</returns>
public virtual string GetSQLDefaultType(bool isRaw)
{
var retval = string.Empty;
if (!isRaw) retval += "[";
retval += this.DataType.ToString();
if (!isRaw) retval += "]";
if (this.DataType == System.Data.SqlDbType.Variant)
{
retval = string.Empty;
if (!isRaw) retval += "[";
retval += "sql_variant";
if (!isRaw) retval += "]";
}
else if (this.DataType == System.Data.SqlDbType.Binary ||
this.DataType == System.Data.SqlDbType.Char ||
this.DataType == System.Data.SqlDbType.Decimal ||
this.DataType == System.Data.SqlDbType.DateTime2 ||
this.DataType == System.Data.SqlDbType.NChar ||
this.DataType == System.Data.SqlDbType.NVarChar ||
this.DataType == System.Data.SqlDbType.VarBinary ||
this.DataType == System.Data.SqlDbType.VarChar)
{
if (this.DataType == System.Data.SqlDbType.Decimal)
retval += " (" + this.Length + ", " + this.Scale + ")";
else if (this.DataType == System.Data.SqlDbType.DateTime2)
retval += " (" + this.Length + ")";
else
retval += " (" + this.GetLengthString() + ")";
}
return retval;
}
/// <summary>
/// Gets a string reprsenting the data length for comments
/// </summary>
/// <remarks>This is not to be used for actual C# code or SQL</remarks>
public virtual string GetCommentLengthString()
{
if (this.DataType == System.Data.SqlDbType.Binary ||
this.DataType == System.Data.SqlDbType.Char ||
this.DataType == System.Data.SqlDbType.Decimal ||
this.DataType == System.Data.SqlDbType.DateTime2 ||
this.DataType == System.Data.SqlDbType.NChar ||
this.DataType == System.Data.SqlDbType.NVarChar ||
this.DataType == System.Data.SqlDbType.VarBinary ||
this.DataType == System.Data.SqlDbType.VarChar)
{
if (this.DataType == System.Data.SqlDbType.Decimal)
return this.Length + $" (scale:{this.Scale})";
else if (this.DataType == System.Data.SqlDbType.DateTime2)
return this.Length.ToString();
else
return this.GetLengthString();
}
return string.Empty;
}
public virtual string GetCodeType()
{
return GetCodeType(true, false);
}
public virtual string GetCodeType(bool allowNullable)
{
return GetCodeType(allowNullable, false);
}
public virtual string GetCodeType(bool allowNullable, bool forceNull)
{
var retval = string.Empty;
if (StringHelper.Match(this.DataType.ToString(), "bigint", true))
retval = "long";
else if (StringHelper.Match(this.DataType.ToString(), "binary", true))
return "System.Byte[]";
else if (StringHelper.Match(this.DataType.ToString(), "bit", true))
retval = "bool";
else if (StringHelper.Match(this.DataType.ToString(), "char", true))
return "string";
else if (StringHelper.Match(this.DataType.ToString(), "datetime", true))
retval = "DateTime";
else if (StringHelper.Match(this.DataType.ToString(), "datetime2", true))
retval = "DateTime";
else if (StringHelper.Match(this.DataType.ToString(), "date", true))
retval = "DateTime";
else if (StringHelper.Match(this.DataType.ToString(), "time", true))
retval = "TimeSpan";
else if (StringHelper.Match(this.DataType.ToString(), "datetimeoffset", true))
retval = "DateTimeOffset";
else if (StringHelper.Match(this.DataType.ToString(), "decimal", true))
retval = "decimal";
else if (StringHelper.Match(this.DataType.ToString(), "float", true))
retval = "double";
else if (StringHelper.Match(this.DataType.ToString(), "image", true))
return "System.Byte[]";
else if (StringHelper.Match(this.DataType.ToString(), "int", true))
retval = "int";
else if (StringHelper.Match(this.DataType.ToString(), "money", true))
retval = "decimal";
else if (StringHelper.Match(this.DataType.ToString(), "nchar", true))
return "string";
else if (StringHelper.Match(this.DataType.ToString(), "ntext", true))
return "string";
else if (StringHelper.Match(this.DataType.ToString(), "numeric", true))
retval = "decimal";
else if (StringHelper.Match(this.DataType.ToString(), "nvarchar", true))
return "string";
else if (StringHelper.Match(this.DataType.ToString(), "real", true))
retval = "System.Single";
else if (StringHelper.Match(this.DataType.ToString(), "smalldatetime", true))
retval = "DateTime";
else if (StringHelper.Match(this.DataType.ToString(), "smallint", true))
retval = "short";
else if (StringHelper.Match(this.DataType.ToString(), "smallmoney", true))
retval = "decimal";
else if (StringHelper.Match(this.DataType.ToString(), "variant", true))
retval = "object";
else if (StringHelper.Match(this.DataType.ToString(), "text", true))
return "string";
else if (StringHelper.Match(this.DataType.ToString(), "tinyint", true))
retval = "byte";
else if (StringHelper.Match(this.DataType.ToString(), "uniqueidentifier", true))
retval = "System.Guid";
else if (StringHelper.Match(this.DataType.ToString(), "varbinary", true))
return "System.Byte[]";
else if (StringHelper.Match(this.DataType.ToString(), "varchar", true))
return "string";
else if (StringHelper.Match(this.DataType.ToString(), "timestamp", true))
return "System.Byte[]";
else if (StringHelper.Match(this.DataType.ToString(), "xml", true))
return "string";
else
throw new Exception("Cannot Map Sql Value '" + this.DataType.ToString() + "' To C# Value");
if (allowNullable && (this.AllowNull || forceNull))
retval += "?";
return retval;
}
/// <summary>
/// Determines if the Datatype supports the 'Parse' method
/// </summary>
public virtual bool AllowStringParse
{
get
{
if (StringHelper.Match(this.DataType.ToString(), "bigint", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "binary", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "bit", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "char", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "datetime", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "datetime2", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "datetimeoffset", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "date", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "time", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "decimal", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "float", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "image", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "int", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "money", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "nchar", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "ntext", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "numeric", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "nvarchar", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "real", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "smalldatetime", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "smallint", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "smallmoney", true))
return true;
else if (StringHelper.Match(this.DataType.ToString(), "variant", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "text", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "tinyint", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "uniqueidentifier", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "varbinary", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "varchar", true))
return false;
else if (StringHelper.Match(this.DataType.ToString(), "timestamp", true))
return false;
else
return false;
}
}
public static int GetPredefinedSize(System.Data.SqlDbType dataType)
{
//Returns -1 if variable
switch (dataType)
{
case System.Data.SqlDbType.BigInt:
return 8;
case System.Data.SqlDbType.Bit:
return 1;
case System.Data.SqlDbType.DateTime:
return 8;
case System.Data.SqlDbType.Date:
return 3;
case System.Data.SqlDbType.Time:
return 5;
case System.Data.SqlDbType.DateTimeOffset:
return 10;
case System.Data.SqlDbType.Float:
return 8;
case System.Data.SqlDbType.Int:
return 4;
case System.Data.SqlDbType.Money:
return 8;
case System.Data.SqlDbType.Real:
return 4;
case System.Data.SqlDbType.SmallDateTime:
return 4;
case System.Data.SqlDbType.SmallInt:
return 2;
case System.Data.SqlDbType.SmallMoney:
return 4;
case System.Data.SqlDbType.Timestamp:
return 8;
case System.Data.SqlDbType.TinyInt:
return 1;
case System.Data.SqlDbType.UniqueIdentifier:
return 16;
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.Xml:
return 1;
default:
return -1;
}
}
/// <summary>
/// Gets the size of the data type
/// </summary>
/// <returns></returns>
/// <remarks>Returns -1 for variable types and 1 for blob fields</remarks>
public virtual int PredefinedSize => GetPredefinedSize(this.DataType);
public static int GetPredefinedScale(System.Data.SqlDbType dataType)
{
//Returns -1 if variable
switch (dataType)
{
case System.Data.SqlDbType.Decimal:
return -1;
default:
return 0;
}
}
public virtual int PredefinedScale => GetPredefinedScale(this.DataType);
private int GetDefaultSize(System.Data.SqlDbType dataType)
{
var size = _length;
switch (dataType)
{
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Real:
size = 18;
break;
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.VarBinary:
case System.Data.SqlDbType.VarChar:
size = 50;
break;
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.NChar:
size = 10;
break;
case System.Data.SqlDbType.DateTime2:
size = 7;
break;
}
return size;
}
#endregion
}
}
| |
using ImGuiNET;
using Num = System.Numerics;
namespace Nez.ImGuiTools
{
public static class NezImGuiThemes
{
public static void DefaultDarkTheme()
{
ImGui.StyleColorsDark();
}
public static void DefaultLightTheme()
{
ImGui.StyleColorsLight();
}
public static void DefaultClassic()
{
ImGui.StyleColorsClassic();
}
public static void DarkHighContrastTheme()
{
var style = ImGui.GetStyle();
style.WindowPadding = new Num.Vector2(15, 15);
style.WindowRounding = 5.0f;
style.FramePadding = new Num.Vector2(5, 5);
style.FrameRounding = 4.0f;
style.ItemSpacing = new Num.Vector2(12, 8);
style.ItemInnerSpacing = new Num.Vector2(8, 6);
style.ScrollbarSize = 15.0f;
style.ScrollbarRounding = 9.0f;
style.GrabMinSize = 5.0f;
style.GrabRounding = 3.0f;
style.Colors[(int) ImGuiCol.Text] = new Num.Vector4(0.80f, 0.80f, 0.83f, 1.00f);
style.Colors[(int) ImGuiCol.TextDisabled] = new Num.Vector4(0.24f, 0.23f, 0.29f, 1.00f);
style.Colors[(int) ImGuiCol.WindowBg] = new Num.Vector4(0.06f, 0.05f, 0.07f, 1.00f);
style.Colors[(int) ImGuiCol.ChildBg] = new Num.Vector4(0.07f, 0.07f, 0.09f, 1.00f);
style.Colors[(int) ImGuiCol.PopupBg] = new Num.Vector4(0.07f, 0.07f, 0.09f, 1.00f);
style.Colors[(int) ImGuiCol.Border] = new Num.Vector4(0.80f, 0.80f, 0.83f, 0.88f);
style.Colors[(int) ImGuiCol.BorderShadow] = new Num.Vector4(0.92f, 0.91f, 0.88f, 0.00f);
style.Colors[(int) ImGuiCol.FrameBg] = new Num.Vector4(0.10f, 0.09f, 0.12f, 1.00f);
style.Colors[(int) ImGuiCol.FrameBgHovered] = new Num.Vector4(0.24f, 0.23f, 0.29f, 1.00f);
style.Colors[(int) ImGuiCol.FrameBgActive] = new Num.Vector4(0.56f, 0.56f, 0.58f, 1.00f);
style.Colors[(int) ImGuiCol.TitleBg] = new Num.Vector4(0.10f, 0.09f, 0.12f, 1.00f);
style.Colors[(int) ImGuiCol.TitleBgCollapsed] = new Num.Vector4(1.00f, 0.98f, 0.95f, 0.75f);
style.Colors[(int) ImGuiCol.TitleBgActive] = new Num.Vector4(0.07f, 0.07f, 0.09f, 1.00f);
style.Colors[(int) ImGuiCol.MenuBarBg] = new Num.Vector4(0.10f, 0.09f, 0.12f, 1.00f);
style.Colors[(int) ImGuiCol.ScrollbarBg] = new Num.Vector4(0.10f, 0.09f, 0.12f, 1.00f);
style.Colors[(int) ImGuiCol.ScrollbarGrab] = new Num.Vector4(0.80f, 0.80f, 0.83f, 0.31f);
style.Colors[(int) ImGuiCol.ScrollbarGrabHovered] = new Num.Vector4(0.56f, 0.56f, 0.58f, 1.00f);
style.Colors[(int) ImGuiCol.ScrollbarGrabActive] = new Num.Vector4(0.06f, 0.05f, 0.07f, 1.00f);
style.Colors[(int) ImGuiCol.CheckMark] = new Num.Vector4(0.80f, 0.80f, 0.83f, 0.31f);
style.Colors[(int) ImGuiCol.SliderGrab] = new Num.Vector4(0.80f, 0.80f, 0.83f, 0.31f);
style.Colors[(int) ImGuiCol.SliderGrabActive] = new Num.Vector4(0.06f, 0.05f, 0.07f, 1.00f);
style.Colors[(int) ImGuiCol.Button] = new Num.Vector4(0.10f, 0.09f, 0.12f, 1.00f);
style.Colors[(int) ImGuiCol.ButtonHovered] = new Num.Vector4(0.24f, 0.23f, 0.29f, 1.00f);
style.Colors[(int) ImGuiCol.ButtonActive] = new Num.Vector4(0.56f, 0.56f, 0.58f, 1.00f);
style.Colors[(int) ImGuiCol.Header] = new Num.Vector4(0.10f, 0.09f, 0.12f, 1.00f);
style.Colors[(int) ImGuiCol.HeaderHovered] = new Num.Vector4(0.56f, 0.56f, 0.58f, 1.00f);
style.Colors[(int) ImGuiCol.HeaderActive] = new Num.Vector4(0.06f, 0.05f, 0.07f, 1.00f);
style.Colors[(int) ImGuiCol.ResizeGrip] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
style.Colors[(int) ImGuiCol.ResizeGripHovered] = new Num.Vector4(0.56f, 0.56f, 0.58f, 1.00f);
style.Colors[(int) ImGuiCol.ResizeGripActive] = new Num.Vector4(0.06f, 0.05f, 0.07f, 1.00f);
style.Colors[(int) ImGuiCol.PlotLines] = new Num.Vector4(0.40f, 0.39f, 0.38f, 0.63f);
style.Colors[(int) ImGuiCol.PlotLinesHovered] = new Num.Vector4(0.25f, 1.00f, 0.00f, 1.00f);
style.Colors[(int) ImGuiCol.PlotHistogram] = new Num.Vector4(0.40f, 0.39f, 0.38f, 0.63f);
style.Colors[(int) ImGuiCol.PlotHistogramHovered] = new Num.Vector4(0.25f, 1.00f, 0.00f, 1.00f);
style.Colors[(int) ImGuiCol.TextSelectedBg] = new Num.Vector4(0.25f, 1.00f, 0.00f, 0.43f);
style.Colors[(int) ImGuiCol.ModalWindowDimBg] = new Num.Vector4(1.00f, 0.98f, 0.95f, 0.73f);
}
public static void DarkTheme1()
{
var colors = ImGui.GetStyle().Colors;
colors[(int) ImGuiCol.Text] = new Num.Vector4(1.00f, 1.00f, 1.00f, 1.00f);
colors[(int) ImGuiCol.TextDisabled] = new Num.Vector4(0.50f, 0.50f, 0.50f, 1.00f);
colors[(int) ImGuiCol.WindowBg] = new Num.Vector4(0.06f, 0.06f, 0.06f, 0.94f);
colors[(int) ImGuiCol.ChildBg] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.00f);
colors[(int) ImGuiCol.PopupBg] = new Num.Vector4(0.08f, 0.08f, 0.08f, 0.94f);
colors[(int) ImGuiCol.Border] = new Num.Vector4(0.43f, 0.43f, 0.50f, 0.50f);
colors[(int) ImGuiCol.BorderShadow] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
colors[(int) ImGuiCol.FrameBg] = new Num.Vector4(0.20f, 0.21f, 0.22f, 0.54f);
colors[(int) ImGuiCol.FrameBgHovered] = new Num.Vector4(0.40f, 0.40f, 0.40f, 0.40f);
colors[(int) ImGuiCol.FrameBgActive] = new Num.Vector4(0.18f, 0.18f, 0.18f, 0.67f);
colors[(int) ImGuiCol.TitleBg] = new Num.Vector4(0.04f, 0.04f, 0.04f, 1.00f);
colors[(int) ImGuiCol.TitleBgActive] = new Num.Vector4(0.29f, 0.29f, 0.29f, 1.00f);
colors[(int) ImGuiCol.TitleBgCollapsed] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.51f);
colors[(int) ImGuiCol.MenuBarBg] = new Num.Vector4(0.14f, 0.14f, 0.14f, 1.00f);
colors[(int) ImGuiCol.ScrollbarBg] = new Num.Vector4(0.02f, 0.02f, 0.02f, 0.53f);
colors[(int) ImGuiCol.ScrollbarGrab] = new Num.Vector4(0.31f, 0.31f, 0.31f, 1.00f);
colors[(int) ImGuiCol.ScrollbarGrabHovered] = new Num.Vector4(0.41f, 0.41f, 0.41f, 1.00f);
colors[(int) ImGuiCol.ScrollbarGrabActive] = new Num.Vector4(0.51f, 0.51f, 0.51f, 1.00f);
colors[(int) ImGuiCol.CheckMark] = new Num.Vector4(0.94f, 0.94f, 0.94f, 1.00f);
colors[(int) ImGuiCol.SliderGrab] = new Num.Vector4(0.51f, 0.51f, 0.51f, 1.00f);
colors[(int) ImGuiCol.SliderGrabActive] = new Num.Vector4(0.86f, 0.86f, 0.86f, 1.00f);
colors[(int) ImGuiCol.Button] = new Num.Vector4(0.44f, 0.44f, 0.44f, 0.40f);
colors[(int) ImGuiCol.ButtonHovered] = new Num.Vector4(0.46f, 0.47f, 0.48f, 1.00f);
colors[(int) ImGuiCol.ButtonActive] = new Num.Vector4(0.42f, 0.42f, 0.42f, 1.00f);
colors[(int) ImGuiCol.Header] = new Num.Vector4(0.70f, 0.70f, 0.70f, 0.31f);
colors[(int) ImGuiCol.HeaderHovered] = new Num.Vector4(0.70f, 0.70f, 0.70f, 0.80f);
colors[(int) ImGuiCol.HeaderActive] = new Num.Vector4(0.48f, 0.50f, 0.52f, 1.00f);
colors[(int) ImGuiCol.Separator] = new Num.Vector4(0.43f, 0.43f, 0.50f, 0.50f);
colors[(int) ImGuiCol.SeparatorHovered] = new Num.Vector4(0.72f, 0.72f, 0.72f, 0.78f);
colors[(int) ImGuiCol.SeparatorActive] = new Num.Vector4(0.51f, 0.51f, 0.51f, 1.00f);
colors[(int) ImGuiCol.ResizeGrip] = new Num.Vector4(0.91f, 0.91f, 0.91f, 0.25f);
colors[(int) ImGuiCol.ResizeGripHovered] = new Num.Vector4(0.81f, 0.81f, 0.81f, 0.67f);
colors[(int) ImGuiCol.ResizeGripActive] = new Num.Vector4(0.46f, 0.46f, 0.46f, 0.95f);
colors[(int) ImGuiCol.PlotLines] = new Num.Vector4(0.61f, 0.61f, 0.61f, 1.00f);
colors[(int) ImGuiCol.PlotLinesHovered] = new Num.Vector4(1.00f, 0.43f, 0.35f, 1.00f);
colors[(int) ImGuiCol.PlotHistogram] = new Num.Vector4(0.73f, 0.60f, 0.15f, 1.00f);
colors[(int) ImGuiCol.PlotHistogramHovered] = new Num.Vector4(1.00f, 0.60f, 0.00f, 1.00f);
colors[(int) ImGuiCol.TextSelectedBg] = new Num.Vector4(0.87f, 0.87f, 0.87f, 0.35f);
colors[(int) ImGuiCol.ModalWindowDimBg] = new Num.Vector4(0.80f, 0.80f, 0.80f, 0.35f);
colors[(int) ImGuiCol.DragDropTarget] = new Num.Vector4(1.00f, 1.00f, 0.00f, 0.90f);
colors[(int) ImGuiCol.NavHighlight] = new Num.Vector4(0.60f, 0.60f, 0.60f, 1.00f);
colors[(int) ImGuiCol.NavWindowingHighlight] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.70f);
}
public static void DarkTheme2()
{
var st = ImGui.GetStyle();
var colors = st.Colors;
st.FrameBorderSize = 1.0f;
st.FramePadding = new Num.Vector2(4.0f, 2.0f);
st.ItemSpacing = new Num.Vector2(8.0f, 2.0f);
st.WindowBorderSize = 1.0f;
st.TabBorderSize = 1.0f;
st.WindowRounding = 1.0f;
st.ChildRounding = 1.0f;
st.FrameRounding = 1.0f;
st.ScrollbarRounding = 1.0f;
st.GrabRounding = 1.0f;
st.TabRounding = 1.0f;
colors[(int) ImGuiCol.Text] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.95f);
colors[(int) ImGuiCol.TextDisabled] = new Num.Vector4(0.50f, 0.50f, 0.50f, 1.00f);
colors[(int) ImGuiCol.WindowBg] = new Num.Vector4(0.13f, 0.12f, 0.12f, 1.00f);
colors[(int) ImGuiCol.ChildBg] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.00f);
colors[(int) ImGuiCol.PopupBg] = new Num.Vector4(0.05f, 0.05f, 0.05f, 0.94f);
colors[(int) ImGuiCol.Border] = new Num.Vector4(0.53f, 0.53f, 0.53f, 0.46f);
colors[(int) ImGuiCol.BorderShadow] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
colors[(int) ImGuiCol.FrameBg] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.85f);
colors[(int) ImGuiCol.FrameBgHovered] = new Num.Vector4(0.22f, 0.22f, 0.22f, 0.40f);
colors[(int) ImGuiCol.FrameBgActive] = new Num.Vector4(0.16f, 0.16f, 0.16f, 0.53f);
colors[(int) ImGuiCol.TitleBg] = new Num.Vector4(0.00f, 0.00f, 0.00f, 1.00f);
colors[(int) ImGuiCol.TitleBgActive] = new Num.Vector4(0.00f, 0.00f, 0.00f, 1.00f);
colors[(int) ImGuiCol.TitleBgCollapsed] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.51f);
colors[(int) ImGuiCol.MenuBarBg] = new Num.Vector4(0.12f, 0.12f, 0.12f, 1.00f);
colors[(int) ImGuiCol.ScrollbarBg] = new Num.Vector4(0.02f, 0.02f, 0.02f, 0.53f);
colors[(int) ImGuiCol.ScrollbarGrab] = new Num.Vector4(0.31f, 0.31f, 0.31f, 1.00f);
colors[(int) ImGuiCol.ScrollbarGrabHovered] = new Num.Vector4(0.41f, 0.41f, 0.41f, 1.00f);
colors[(int) ImGuiCol.ScrollbarGrabActive] = new Num.Vector4(0.48f, 0.48f, 0.48f, 1.00f);
colors[(int) ImGuiCol.CheckMark] = new Num.Vector4(0.79f, 0.79f, 0.79f, 1.00f);
colors[(int) ImGuiCol.SliderGrab] = new Num.Vector4(0.48f, 0.47f, 0.47f, 0.91f);
colors[(int) ImGuiCol.SliderGrabActive] = new Num.Vector4(0.56f, 0.55f, 0.55f, 0.62f);
colors[(int) ImGuiCol.Button] = new Num.Vector4(0.50f, 0.50f, 0.50f, 0.63f);
colors[(int) ImGuiCol.ButtonHovered] = new Num.Vector4(0.67f, 0.67f, 0.68f, 0.63f);
colors[(int) ImGuiCol.ButtonActive] = new Num.Vector4(0.26f, 0.26f, 0.26f, 0.63f);
colors[(int) ImGuiCol.Header] = new Num.Vector4(0.54f, 0.54f, 0.54f, 0.58f);
colors[(int) ImGuiCol.HeaderHovered] = new Num.Vector4(0.64f, 0.65f, 0.65f, 0.80f);
colors[(int) ImGuiCol.HeaderActive] = new Num.Vector4(0.25f, 0.25f, 0.25f, 0.80f);
colors[(int) ImGuiCol.Separator] = new Num.Vector4(0.58f, 0.58f, 0.58f, 0.50f);
colors[(int) ImGuiCol.SeparatorHovered] = new Num.Vector4(0.81f, 0.81f, 0.81f, 0.64f);
colors[(int) ImGuiCol.SeparatorActive] = new Num.Vector4(0.81f, 0.81f, 0.81f, 0.64f);
colors[(int) ImGuiCol.ResizeGrip] = new Num.Vector4(0.87f, 0.87f, 0.87f, 0.53f);
colors[(int) ImGuiCol.ResizeGripHovered] = new Num.Vector4(0.87f, 0.87f, 0.87f, 0.74f);
colors[(int) ImGuiCol.ResizeGripActive] = new Num.Vector4(0.87f, 0.87f, 0.87f, 0.74f);
colors[(int) ImGuiCol.Tab] = new Num.Vector4(0.01f, 0.01f, 0.01f, 0.86f);
colors[(int) ImGuiCol.TabHovered] = new Num.Vector4(0.29f, 0.29f, 0.29f, 1.00f);
colors[(int) ImGuiCol.TabActive] = new Num.Vector4(0.31f, 0.31f, 0.31f, 1.00f);
colors[(int) ImGuiCol.TabUnfocused] = new Num.Vector4(0.02f, 0.02f, 0.02f, 1.00f);
colors[(int) ImGuiCol.TabUnfocusedActive] = new Num.Vector4(0.19f, 0.19f, 0.19f, 1.00f);
colors[(int) ImGuiCol.PlotLines] = new Num.Vector4(0.61f, 0.61f, 0.61f, 1.00f);
colors[(int) ImGuiCol.PlotLinesHovered] = new Num.Vector4(0.68f, 0.68f, 0.68f, 1.00f);
colors[(int) ImGuiCol.PlotHistogram] = new Num.Vector4(0.90f, 0.77f, 0.33f, 1.00f);
colors[(int) ImGuiCol.PlotHistogramHovered] = new Num.Vector4(0.87f, 0.55f, 0.08f, 1.00f);
colors[(int) ImGuiCol.TextSelectedBg] = new Num.Vector4(0.47f, 0.60f, 0.76f, 0.47f);
colors[(int) ImGuiCol.DragDropTarget] = new Num.Vector4(0.58f, 0.58f, 0.58f, 0.90f);
colors[(int) ImGuiCol.NavHighlight] = new Num.Vector4(0.60f, 0.60f, 0.60f, 1.00f);
colors[(int) ImGuiCol.NavWindowingHighlight] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.70f);
colors[(int) ImGuiCol.NavWindowingDimBg] = new Num.Vector4(0.80f, 0.80f, 0.80f, 0.20f);
colors[(int) ImGuiCol.ModalWindowDimBg] = new Num.Vector4(0.80f, 0.80f, 0.80f, 0.35f);
}
public static void PhotoshopDark()
{
var style = ImGui.GetStyle();
var colors = style.Colors;
colors[(int) ImGuiCol.Text] = new Num.Vector4(1.000f, 1.000f, 1.000f, 1.000f);
colors[(int) ImGuiCol.TextDisabled] = new Num.Vector4(0.500f, 0.500f, 0.500f, 1.000f);
colors[(int) ImGuiCol.WindowBg] = new Num.Vector4(0.180f, 0.180f, 0.180f, 1.000f);
colors[(int) ImGuiCol.ChildBg] = new Num.Vector4(0.280f, 0.280f, 0.280f, 0.000f);
colors[(int) ImGuiCol.PopupBg] = new Num.Vector4(0.313f, 0.313f, 0.313f, 1.000f);
colors[(int) ImGuiCol.Border] = new Num.Vector4(0.266f, 0.266f, 0.266f, 1.000f);
colors[(int) ImGuiCol.BorderShadow] = new Num.Vector4(0.000f, 0.000f, 0.000f, 0.000f);
colors[(int) ImGuiCol.FrameBg] = new Num.Vector4(0.160f, 0.160f, 0.160f, 1.000f);
colors[(int) ImGuiCol.FrameBgHovered] = new Num.Vector4(0.200f, 0.200f, 0.200f, 1.000f);
colors[(int) ImGuiCol.FrameBgActive] = new Num.Vector4(0.280f, 0.280f, 0.280f, 1.000f);
colors[(int) ImGuiCol.TitleBg] = new Num.Vector4(0.148f, 0.148f, 0.148f, 1.000f);
colors[(int) ImGuiCol.TitleBgActive] = new Num.Vector4(0.148f, 0.148f, 0.148f, 1.000f);
colors[(int) ImGuiCol.TitleBgCollapsed] = new Num.Vector4(0.148f, 0.148f, 0.148f, 1.000f);
colors[(int) ImGuiCol.MenuBarBg] = new Num.Vector4(0.195f, 0.195f, 0.195f, 1.000f);
colors[(int) ImGuiCol.ScrollbarBg] = new Num.Vector4(0.160f, 0.160f, 0.160f, 1.000f);
colors[(int) ImGuiCol.ScrollbarGrab] = new Num.Vector4(0.277f, 0.277f, 0.277f, 1.000f);
colors[(int) ImGuiCol.ScrollbarGrabHovered] = new Num.Vector4(0.300f, 0.300f, 0.300f, 1.000f);
colors[(int) ImGuiCol.ScrollbarGrabActive] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.CheckMark] = new Num.Vector4(1.000f, 1.000f, 1.000f, 1.000f);
colors[(int) ImGuiCol.SliderGrab] = new Num.Vector4(0.391f, 0.391f, 0.391f, 1.000f);
colors[(int) ImGuiCol.SliderGrabActive] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.Button] = new Num.Vector4(1.000f, 1.000f, 1.000f, 0.000f);
colors[(int) ImGuiCol.ButtonHovered] = new Num.Vector4(1.000f, 1.000f, 1.000f, 0.156f);
colors[(int) ImGuiCol.ButtonActive] = new Num.Vector4(1.000f, 1.000f, 1.000f, 0.391f);
colors[(int) ImGuiCol.Header] = new Num.Vector4(0.313f, 0.313f, 0.313f, 1.000f);
colors[(int) ImGuiCol.HeaderHovered] = new Num.Vector4(0.469f, 0.469f, 0.469f, 1.000f);
colors[(int) ImGuiCol.HeaderActive] = new Num.Vector4(0.469f, 0.469f, 0.469f, 1.000f);
colors[(int) ImGuiCol.Separator] = colors[(int) ImGuiCol.Border];
colors[(int) ImGuiCol.SeparatorHovered] = new Num.Vector4(0.391f, 0.391f, 0.391f, 1.000f);
colors[(int) ImGuiCol.SeparatorActive] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.ResizeGrip] = new Num.Vector4(1.000f, 1.000f, 1.000f, 0.250f);
colors[(int) ImGuiCol.ResizeGripHovered] = new Num.Vector4(1.000f, 1.000f, 1.000f, 0.670f);
colors[(int) ImGuiCol.ResizeGripActive] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.Tab] = new Num.Vector4(0.098f, 0.098f, 0.098f, 1.000f);
colors[(int) ImGuiCol.TabHovered] = new Num.Vector4(0.352f, 0.352f, 0.352f, 1.000f);
colors[(int) ImGuiCol.TabActive] = new Num.Vector4(0.195f, 0.195f, 0.195f, 1.000f);
colors[(int) ImGuiCol.TabUnfocused] = new Num.Vector4(0.098f, 0.098f, 0.098f, 1.000f);
colors[(int) ImGuiCol.TabUnfocusedActive] = new Num.Vector4(0.195f, 0.195f, 0.195f, 1.000f);
colors[(int) ImGuiCol.PlotLines] = new Num.Vector4(0.469f, 0.469f, 0.469f, 1.000f);
colors[(int) ImGuiCol.PlotLinesHovered] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.PlotHistogram] = new Num.Vector4(0.586f, 0.586f, 0.586f, 1.000f);
colors[(int) ImGuiCol.PlotHistogramHovered] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.TextSelectedBg] = new Num.Vector4(1.000f, 1.000f, 1.000f, 0.156f);
colors[(int) ImGuiCol.DragDropTarget] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.NavHighlight] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.NavWindowingHighlight] = new Num.Vector4(1.000f, 0.391f, 0.000f, 1.000f);
colors[(int) ImGuiCol.NavWindowingDimBg] = new Num.Vector4(0.000f, 0.000f, 0.000f, 0.586f);
colors[(int) ImGuiCol.ModalWindowDimBg] = new Num.Vector4(0.000f, 0.000f, 0.000f, 0.586f);
style.ChildRounding = 4.0f;
style.FrameBorderSize = 1.0f;
style.FrameRounding = 2.0f;
style.GrabMinSize = 7.0f;
style.PopupRounding = 2.0f;
style.ScrollbarRounding = 12.0f;
style.ScrollbarSize = 13.0f;
style.TabBorderSize = 1.0f;
style.TabRounding = 0.0f;
style.WindowRounding = 4.0f;
}
public static void LightGreenMiniDart()
{
var style = ImGui.GetStyle();
var colors = style.Colors;
style.WindowRounding = 2.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
style.ScrollbarRounding = 3.0f; // Radius of grab corners rounding for scrollbar
style.GrabRounding =
2.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
style.AntiAliasedLines = true;
style.AntiAliasedFill = true;
style.WindowRounding = 2;
style.ChildRounding = 2;
style.ScrollbarSize = 16;
style.ScrollbarRounding = 3;
style.GrabRounding = 2;
style.ItemSpacing.X = 10;
style.ItemSpacing.Y = 4;
style.FramePadding.X = 6;
style.FramePadding.Y = 4;
style.Alpha = 1.0f;
style.FrameRounding = 3.0f;
colors[(int) ImGuiCol.Text] = new Num.Vector4(0.00f, 0.00f, 0.00f, 1.00f);
colors[(int) ImGuiCol.TextDisabled] = new Num.Vector4(0.60f, 0.60f, 0.60f, 1.00f);
colors[(int) ImGuiCol.WindowBg] = new Num.Vector4(0.86f, 0.86f, 0.86f, 1.00f);
//colors[(int)ImGuiCol.ChildWindowBg] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
colors[(int) ImGuiCol.ChildBg] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
colors[(int) ImGuiCol.PopupBg] = new Num.Vector4(0.93f, 0.93f, 0.93f, 0.98f);
colors[(int) ImGuiCol.Border] = new Num.Vector4(0.71f, 0.71f, 0.71f, 0.08f);
colors[(int) ImGuiCol.BorderShadow] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.04f);
colors[(int) ImGuiCol.FrameBg] = new Num.Vector4(0.71f, 0.71f, 0.71f, 0.55f);
colors[(int) ImGuiCol.FrameBgHovered] = new Num.Vector4(0.94f, 0.94f, 0.94f, 0.55f);
colors[(int) ImGuiCol.FrameBgActive] = new Num.Vector4(0.71f, 0.78f, 0.69f, 0.98f);
colors[(int) ImGuiCol.TitleBg] = new Num.Vector4(0.85f, 0.85f, 0.85f, 1.00f);
colors[(int) ImGuiCol.TitleBgCollapsed] = new Num.Vector4(0.82f, 0.78f, 0.78f, 0.51f);
colors[(int) ImGuiCol.TitleBgActive] = new Num.Vector4(0.78f, 0.78f, 0.78f, 1.00f);
colors[(int) ImGuiCol.MenuBarBg] = new Num.Vector4(0.86f, 0.86f, 0.86f, 1.00f);
colors[(int) ImGuiCol.ScrollbarBg] = new Num.Vector4(0.20f, 0.25f, 0.30f, 0.61f);
colors[(int) ImGuiCol.ScrollbarGrab] = new Num.Vector4(0.90f, 0.90f, 0.90f, 0.30f);
colors[(int) ImGuiCol.ScrollbarGrabHovered] = new Num.Vector4(0.92f, 0.92f, 0.92f, 0.78f);
colors[(int) ImGuiCol.ScrollbarGrabActive] = new Num.Vector4(1.00f, 1.00f, 1.00f, 1.00f);
colors[(int) ImGuiCol.CheckMark] = new Num.Vector4(0.184f, 0.407f, 0.193f, 1.00f);
colors[(int) ImGuiCol.SliderGrab] = new Num.Vector4(0.26f, 0.59f, 0.98f, 0.78f);
colors[(int) ImGuiCol.SliderGrabActive] = new Num.Vector4(0.26f, 0.59f, 0.98f, 1.00f);
colors[(int) ImGuiCol.Button] = new Num.Vector4(0.71f, 0.78f, 0.69f, 0.40f);
colors[(int) ImGuiCol.ButtonHovered] = new Num.Vector4(0.725f, 0.805f, 0.702f, 1.00f);
colors[(int) ImGuiCol.ButtonActive] = new Num.Vector4(0.793f, 0.900f, 0.836f, 1.00f);
colors[(int) ImGuiCol.Header] = new Num.Vector4(0.71f, 0.78f, 0.69f, 0.31f);
colors[(int) ImGuiCol.HeaderHovered] = new Num.Vector4(0.71f, 0.78f, 0.69f, 0.80f);
colors[(int) ImGuiCol.HeaderActive] = new Num.Vector4(0.71f, 0.78f, 0.69f, 1.00f);
colors[(int) ImGuiCol.Separator] = new Num.Vector4(0.39f, 0.39f, 0.39f, 1.00f);
colors[(int) ImGuiCol.SeparatorHovered] = new Num.Vector4(0.14f, 0.44f, 0.80f, 0.78f);
colors[(int) ImGuiCol.SeparatorActive] = new Num.Vector4(0.14f, 0.44f, 0.80f, 1.00f);
colors[(int) ImGuiCol.ResizeGrip] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.00f);
colors[(int) ImGuiCol.ResizeGripHovered] = new Num.Vector4(0.26f, 0.59f, 0.98f, 0.45f);
colors[(int) ImGuiCol.ResizeGripActive] = new Num.Vector4(0.26f, 0.59f, 0.98f, 0.78f);
colors[(int) ImGuiCol.PlotLines] = new Num.Vector4(0.39f, 0.39f, 0.39f, 1.00f);
colors[(int) ImGuiCol.PlotLinesHovered] = new Num.Vector4(1.00f, 0.43f, 0.35f, 1.00f);
colors[(int) ImGuiCol.PlotHistogram] = new Num.Vector4(0.90f, 0.70f, 0.00f, 1.00f);
colors[(int) ImGuiCol.PlotHistogramHovered] = new Num.Vector4(1.00f, 0.60f, 0.00f, 1.00f);
colors[(int) ImGuiCol.TextSelectedBg] = new Num.Vector4(0.26f, 0.59f, 0.98f, 0.35f);
colors[(int) ImGuiCol.ModalWindowDimBg] = new Num.Vector4(0.20f, 0.20f, 0.20f, 0.35f);
colors[(int) ImGuiCol.DragDropTarget] = new Num.Vector4(0.26f, 0.59f, 0.98f, 0.95f);
colors[(int) ImGuiCol.NavHighlight] = colors[(int) ImGuiCol.HeaderHovered];
colors[(int) ImGuiCol.NavWindowingHighlight] = new Num.Vector4(0.70f, 0.70f, 0.70f, 0.70f);
}
public static void HighContrast()
{
var style = ImGui.GetStyle();
style.WindowRounding = 5.3f;
style.FrameRounding = 2.3f;
style.ScrollbarRounding = 0;
style.Colors[(int) ImGuiCol.Text] = new Num.Vector4(0.90f, 0.90f, 0.90f, 0.90f);
style.Colors[(int) ImGuiCol.TextDisabled] = new Num.Vector4(0.60f, 0.60f, 0.60f, 1.00f);
style.Colors[(int) ImGuiCol.WindowBg] = new Num.Vector4(0.09f, 0.09f, 0.15f, 1.00f);
style.Colors[(int) ImGuiCol.ChildBg] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
style.Colors[(int) ImGuiCol.PopupBg] = new Num.Vector4(0.05f, 0.05f, 0.10f, 0.85f);
style.Colors[(int) ImGuiCol.Border] = new Num.Vector4(0.70f, 0.70f, 0.70f, 0.65f);
style.Colors[(int) ImGuiCol.BorderShadow] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.00f);
style.Colors[(int) ImGuiCol.FrameBg] = new Num.Vector4(0.00f, 0.00f, 0.01f, 1.00f);
style.Colors[(int) ImGuiCol.FrameBgHovered] = new Num.Vector4(0.90f, 0.80f, 0.80f, 0.40f);
style.Colors[(int) ImGuiCol.FrameBgActive] = new Num.Vector4(0.90f, 0.65f, 0.65f, 0.45f);
style.Colors[(int) ImGuiCol.TitleBg] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.83f);
style.Colors[(int) ImGuiCol.TitleBgCollapsed] = new Num.Vector4(0.40f, 0.40f, 0.80f, 0.20f);
style.Colors[(int) ImGuiCol.TitleBgActive] = new Num.Vector4(0.00f, 0.00f, 0.00f, 0.87f);
style.Colors[(int) ImGuiCol.MenuBarBg] = new Num.Vector4(0.01f, 0.01f, 0.02f, 0.80f);
style.Colors[(int) ImGuiCol.ScrollbarBg] = new Num.Vector4(0.20f, 0.25f, 0.30f, 0.60f);
style.Colors[(int) ImGuiCol.ScrollbarGrab] = new Num.Vector4(0.55f, 0.53f, 0.55f, 0.51f);
style.Colors[(int) ImGuiCol.ScrollbarGrabHovered] = new Num.Vector4(0.56f, 0.56f, 0.56f, 1.00f);
style.Colors[(int) ImGuiCol.ScrollbarGrabActive] = new Num.Vector4(0.56f, 0.56f, 0.56f, 0.91f);
style.Colors[(int) ImGuiCol.CheckMark] = new Num.Vector4(0.90f, 0.90f, 0.90f, 0.83f);
style.Colors[(int) ImGuiCol.SliderGrab] = new Num.Vector4(0.70f, 0.70f, 0.70f, 0.62f);
style.Colors[(int) ImGuiCol.SliderGrabActive] = new Num.Vector4(0.30f, 0.30f, 0.30f, 0.84f);
style.Colors[(int) ImGuiCol.Button] = new Num.Vector4(0.48f, 0.72f, 0.89f, 0.49f);
style.Colors[(int) ImGuiCol.ButtonHovered] = new Num.Vector4(0.50f, 0.69f, 0.99f, 0.68f);
style.Colors[(int) ImGuiCol.ButtonActive] = new Num.Vector4(0.80f, 0.50f, 0.50f, 1.00f);
style.Colors[(int) ImGuiCol.Header] = new Num.Vector4(0.30f, 0.69f, 1.00f, 0.53f);
style.Colors[(int) ImGuiCol.HeaderHovered] = new Num.Vector4(0.44f, 0.61f, 0.86f, 1.00f);
style.Colors[(int) ImGuiCol.HeaderActive] = new Num.Vector4(0.38f, 0.62f, 0.83f, 1.00f);
style.Colors[(int) ImGuiCol.ResizeGrip] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.85f);
style.Colors[(int) ImGuiCol.ResizeGripHovered] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.60f);
style.Colors[(int) ImGuiCol.ResizeGripActive] = new Num.Vector4(1.00f, 1.00f, 1.00f, 0.90f);
style.Colors[(int) ImGuiCol.PlotLines] = new Num.Vector4(1.00f, 1.00f, 1.00f, 1.00f);
style.Colors[(int) ImGuiCol.PlotLinesHovered] = new Num.Vector4(0.90f, 0.70f, 0.00f, 1.00f);
style.Colors[(int) ImGuiCol.PlotHistogram] = new Num.Vector4(0.90f, 0.70f, 0.00f, 1.00f);
style.Colors[(int) ImGuiCol.PlotHistogramHovered] = new Num.Vector4(1.00f, 0.60f, 0.00f, 1.00f);
style.Colors[(int) ImGuiCol.TextSelectedBg] = new Num.Vector4(0.00f, 0.00f, 1.00f, 0.35f);
style.Colors[(int) ImGuiCol.ModalWindowDimBg] = new Num.Vector4(0.20f, 0.20f, 0.20f, 0.35f);
}
}
}
| |
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| BigInteger.cs |
| |
| Release 3.0.2 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* Big Integer implementation
*
* Authors:
* Ben Maurer
* Chew Keong TAN
* Sebastien Pouliot <sebastien@ximian.com>
* Pieter Philippaerts <Pieter@mentalis.org>
* Ma Bingyao <andot@ujn.edu.cn>
*
* Copyright (c) 2003 Ben Maurer
* All rights reserved
*
* Copyright (c) 2002 Chew Keong TAN
* All rights reserved.
*
* Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com)
* Copyright (C) 2008 Ma Bingyao <andot@ujn.edu.cn>
*
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*/
namespace org.phprpc.util {
using System;
#if !(PocketPC || Smartphone)
using System.Security.Cryptography;
#endif
public class BigInteger {
#region Data Storage
UInt32 length = 1;
UInt32[] data;
#endregion
#region Constants
const UInt32 DEFAULT_LEN = 20;
public enum Sign : int {
Negative = -1,
Zero = 0,
Positive = 1
};
#region Exception Messages
const String WouldReturnNegVal = "Operation would return a negative value";
#endregion
#endregion
#region Constructors
public BigInteger() {
data = new UInt32[DEFAULT_LEN];
this.length = DEFAULT_LEN;
}
public BigInteger(Sign sign, UInt32 len) {
this.data = new UInt32[len];
this.length = len;
}
public BigInteger(BigInteger bi) {
this.data = (UInt32[])bi.data.Clone();
this.length = bi.length;
}
public BigInteger(BigInteger bi, UInt32 len) {
this.data = new UInt32[len];
for (UInt32 i = 0; i < bi.length; i++) {
this.data[i] = bi.data[i];
}
this.length = bi.length;
}
#endregion
#region Conversions
public BigInteger(byte[] inData) {
length = (UInt32)inData.Length >> 2;
Int32 leftOver = inData.Length & 0x3;
// length not multiples of 4
if (leftOver != 0) {
length++;
}
data = new UInt32[length];
for (Int32 i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++) {
data[j] = (UInt32)(((UInt32)inData[i - 3] << 24) | ((UInt32)inData[i - 2] << 16) | ((UInt32)inData[i - 1] << 8) | (UInt32)inData[i]);
}
switch (leftOver) {
case 1:
data[length - 1] = (UInt32)inData[0];
break;
case 2:
data[length - 1] = (((UInt32)inData[0] << 8) | (UInt32)inData[1]);
break;
case 3:
data[length - 1] = (((UInt32)inData[0] << 16) | ((UInt32)inData[1] << 8) | (UInt32)inData[2]);
break;
}
this.Normalize();
}
public BigInteger(UInt32[] inData) {
length = (UInt32)inData.Length;
data = new UInt32[length];
for (Int32 i = (Int32)length - 1, j = 0; i >= 0; i--, j++) {
data[j] = inData[i];
}
this.Normalize();
}
public BigInteger(UInt32 ui) {
data = new UInt32[] { ui };
}
public BigInteger(UInt64 ul) {
data = new UInt32[2] { (UInt32)ul, (UInt32)(ul >> 32) };
length = 2;
this.Normalize();
}
public static implicit operator BigInteger(UInt32 value) {
return (new BigInteger(value));
}
public static implicit operator BigInteger(Int32 value) {
if (value < 0) {
throw new ArgumentOutOfRangeException("value");
}
return (new BigInteger((UInt32)value));
}
public static implicit operator BigInteger(UInt64 value) {
return (new BigInteger(value));
}
/* This is the BigInteger.Parse method I use. This method works
because BigInteger.ToString returns the input I gave to Parse. */
public static BigInteger Parse(String number) {
if (number == null) {
throw new ArgumentNullException("number");
}
Int32 i = 0, len = number.Length;
Char c;
Boolean digits_seen = false;
BigInteger val = new BigInteger(0);
if (number[i] == '+') {
i++;
}
else if (number[i] == '-') {
throw new FormatException(WouldReturnNegVal);
}
for (; i < len; i++) {
c = number[i];
if (c == '\0') {
i = len;
continue;
}
if (c >= '0' && c <= '9') {
val = val * 10 + (c - '0');
digits_seen = true;
}
else {
if (Char.IsWhiteSpace(c)) {
for (i++; i < len; i++) {
if (!Char.IsWhiteSpace(number[i])) {
throw new FormatException();
}
}
break;
}
else {
throw new FormatException();
}
}
}
if (!digits_seen) {
throw new FormatException();
}
return val;
}
#endregion
#region Operators
public static BigInteger operator +(BigInteger bi1, BigInteger bi2) {
if (bi1 == 0) {
return new BigInteger(bi2);
}
else if (bi2 == 0) {
return new BigInteger(bi1);
}
else {
return Kernel.AddSameSign(bi1, bi2);
}
}
public static BigInteger operator -(BigInteger bi1, BigInteger bi2) {
if (bi2 == 0) {
return new BigInteger(bi1);
}
if (bi1 == 0) {
throw new ArithmeticException(WouldReturnNegVal);
}
switch (Kernel.Compare(bi1, bi2)) {
case Sign.Zero:
return 0;
case Sign.Positive:
return Kernel.Subtract(bi1, bi2);
case Sign.Negative:
throw new ArithmeticException(WouldReturnNegVal);
default:
throw new Exception();
}
}
public static Int32 operator %(BigInteger bi, Int32 i) {
if (i > 0) {
return (Int32)Kernel.DwordMod(bi, (UInt32)i);
}
else {
return -(Int32)Kernel.DwordMod(bi, (UInt32)(-i));
}
}
public static UInt32 operator %(BigInteger bi, UInt32 ui) {
return Kernel.DwordMod(bi, (UInt32)ui);
}
public static BigInteger operator %(BigInteger bi1, BigInteger bi2) {
return Kernel.multiByteDivide(bi1, bi2)[1];
}
public static BigInteger operator /(BigInteger bi, Int32 i) {
if (i > 0) {
return Kernel.DwordDiv(bi, (UInt32)i);
}
throw new ArithmeticException(WouldReturnNegVal);
}
public static BigInteger operator /(BigInteger bi1, BigInteger bi2) {
return Kernel.multiByteDivide(bi1, bi2)[0];
}
public static BigInteger operator *(BigInteger bi1, BigInteger bi2) {
if (bi1 == 0 || bi2 == 0) {
return 0;
}
//
// Validate pointers
//
if (bi1.data.Length < bi1.length) {
throw new IndexOutOfRangeException("bi1 out of range");
}
if (bi2.data.Length < bi2.length) {
throw new IndexOutOfRangeException("bi2 out of range");
}
BigInteger ret = new BigInteger(Sign.Positive, bi1.length + bi2.length);
Kernel.Multiply(bi1.data, 0, bi1.length, bi2.data, 0, bi2.length, ret.data, 0);
ret.Normalize();
return ret;
}
public static BigInteger operator *(BigInteger bi, Int32 i) {
if (i < 0) {
throw new ArithmeticException(WouldReturnNegVal);
}
if (i == 0) {
return 0;
}
if (i == 1) {
return new BigInteger(bi);
}
return Kernel.MultiplyByDword(bi, (UInt32)i);
}
public static BigInteger operator <<(BigInteger bi1, Int32 shiftVal) {
return Kernel.LeftShift(bi1, shiftVal);
}
public static BigInteger operator >>(BigInteger bi1, Int32 shiftVal) {
return Kernel.RightShift(bi1, shiftVal);
}
#endregion
#region Friendly names for operators
// with names suggested by FxCop 1.30
public static BigInteger Add(BigInteger bi1, BigInteger bi2) {
return (bi1 + bi2);
}
public static BigInteger Subtract(BigInteger bi1, BigInteger bi2) {
return (bi1 - bi2);
}
public static Int32 Modulus(BigInteger bi, Int32 i) {
return (bi % i);
}
public static UInt32 Modulus(BigInteger bi, UInt32 ui) {
return (bi % ui);
}
public static BigInteger Modulus(BigInteger bi1, BigInteger bi2) {
return (bi1 % bi2);
}
public static BigInteger Divid(BigInteger bi, Int32 i) {
return (bi / i);
}
public static BigInteger Divid(BigInteger bi1, BigInteger bi2) {
return (bi1 / bi2);
}
public static BigInteger Multiply(BigInteger bi1, BigInteger bi2) {
return (bi1 * bi2);
}
public static BigInteger Multiply(BigInteger bi, Int32 i) {
return (bi * i);
}
#endregion
#region Random
#if PocketPC || Smartphone || SILVERLIGHT
private static Random rng;
private static Random Rng {
get {
if (rng == null) {
rng = new Random((int)DateTime.Now.Ticks);
}
return rng;
}
}
#else
private static RandomNumberGenerator rng;
private static RandomNumberGenerator Rng {
get {
if (rng == null) {
rng = RandomNumberGenerator.Create();
}
return rng;
}
}
#endif
#if PocketPC || Smartphone || SILVERLIGHT
public static BigInteger GenerateRandom(Int32 bits, Random rng) {
#else
public static BigInteger GenerateRandom(Int32 bits, RandomNumberGenerator rng) {
#endif
Int32 dwords = bits >> 5;
Int32 remBits = bits & 0x1F;
if (remBits != 0) {
dwords++;
}
BigInteger ret = new BigInteger(Sign.Positive, (UInt32)dwords + 1);
byte[] random = new byte[dwords << 2];
#if PocketPC || Smartphone || SILVERLIGHT
rng.NextBytes(random);
#else
rng.GetBytes(random);
#endif
Buffer.BlockCopy(random, 0, ret.data, 0, (Int32)dwords << 2);
if (remBits != 0) {
UInt32 mask = (UInt32)(0x01 << (remBits - 1));
ret.data[dwords - 1] |= mask;
mask = (UInt32)(0xFFFFFFFF >> (32 - remBits));
ret.data[dwords - 1] &= mask;
}
else {
ret.data[dwords - 1] |= 0x80000000;
}
ret.Normalize();
return ret;
}
public static BigInteger GenerateRandom(Int32 bits) {
return GenerateRandom(bits, Rng);
}
#if PocketPC || Smartphone || SILVERLIGHT
public void Randomize(Random rng) {
#else
public void Randomize(RandomNumberGenerator rng) {
#endif
if (this == 0) {
return;
}
Int32 bits = this.BitCount();
Int32 dwords = bits >> 5;
Int32 remBits = bits & 0x1F;
if (remBits != 0) {
dwords++;
}
byte[] random = new byte[dwords << 2];
#if PocketPC || Smartphone || SILVERLIGHT
rng.NextBytes(random);
#else
rng.GetBytes(random);
#endif
Buffer.BlockCopy(random, 0, data, 0, (Int32)dwords << 2);
if (remBits != 0) {
UInt32 mask = (UInt32)(0x01 << (remBits - 1));
data[dwords - 1] |= mask;
mask = (UInt32)(0xFFFFFFFF >> (32 - remBits));
data[dwords - 1] &= mask;
}
else {
data[dwords - 1] |= 0x80000000;
}
Normalize();
}
public void Randomize() {
Randomize(Rng);
}
#endregion
#region Bitwise
public Int32 BitCount() {
this.Normalize();
UInt32 value = data[length - 1];
UInt32 mask = 0x80000000;
UInt32 bits = 32;
while (bits > 0 && (value & mask) == 0) {
bits--;
mask >>= 1;
}
bits += ((length - 1) << 5);
return (Int32)bits;
}
public Boolean TestBit(UInt32 bitNum) {
UInt32 bytePos = bitNum >> 5; // divide by 32
byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
UInt32 mask = (UInt32)1 << bitPos;
return ((this.data[bytePos] & mask) != 0);
}
public Boolean TestBit(Int32 bitNum) {
if (bitNum < 0) {
throw new IndexOutOfRangeException("bitNum out of range");
}
UInt32 bytePos = (UInt32)bitNum >> 5; // divide by 32
byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
UInt32 mask = (UInt32)1 << bitPos;
return ((this.data[bytePos] | mask) == this.data[bytePos]);
}
public void SetBit(UInt32 bitNum) {
SetBit(bitNum, true);
}
public void ClearBit(UInt32 bitNum) {
SetBit(bitNum, false);
}
public void SetBit(UInt32 bitNum, Boolean value) {
UInt32 bytePos = bitNum >> 5; // divide by 32
if (bytePos < this.length) {
UInt32 mask = (UInt32)1 << (Int32)(bitNum & 0x1F);
if (value) {
this.data[bytePos] |= mask;
}
else {
this.data[bytePos] &= ~mask;
}
}
}
public Int32 LowestSetBit() {
if (this == 0) {
return -1;
}
Int32 i = 0;
while (!TestBit(i)) {
i++;
}
return i;
}
public byte[] GetBytes() {
if (this == 0) {
return new byte[1];
}
Int32 numBits = BitCount();
Int32 numBytes = numBits >> 3;
if ((numBits & 0x7) != 0) {
numBytes++;
}
byte[] result = new byte[numBytes];
Int32 numBytesInWord = numBytes & 0x3;
if (numBytesInWord == 0) {
numBytesInWord = 4;
}
Int32 pos = 0;
for (Int32 i = (Int32)length - 1; i >= 0; i--) {
UInt32 val = data[i];
for (Int32 j = numBytesInWord - 1; j >= 0; j--) {
result[pos + j] = (byte)(val & 0xFF);
val >>= 8;
}
pos += numBytesInWord;
numBytesInWord = 4;
}
return result;
}
#endregion
#region Compare
public static Boolean operator ==(BigInteger bi1, UInt32 ui) {
if (bi1.length != 1) {
bi1.Normalize();
}
return bi1.length == 1 && bi1.data[0] == ui;
}
public static Boolean operator !=(BigInteger bi1, UInt32 ui) {
if (bi1.length != 1) {
bi1.Normalize();
}
return !(bi1.length == 1 && bi1.data[0] == ui);
}
public static Boolean operator ==(BigInteger bi1, BigInteger bi2) {
// we need to compare with null
if ((bi1 as Object) == (bi2 as Object)) {
return true;
}
if (null == bi1 || null == bi2) {
return false;
}
return Kernel.Compare(bi1, bi2) == 0;
}
public static Boolean operator !=(BigInteger bi1, BigInteger bi2) {
// we need to compare with null
if ((bi1 as Object) == (bi2 as Object)) {
return false;
}
if (null == bi1 || null == bi2) {
return true;
}
return Kernel.Compare(bi1, bi2) != 0;
}
public static Boolean operator >(BigInteger bi1, BigInteger bi2) {
return Kernel.Compare(bi1, bi2) > 0;
}
public static Boolean operator <(BigInteger bi1, BigInteger bi2) {
return Kernel.Compare(bi1, bi2) < 0;
}
public static Boolean operator >=(BigInteger bi1, BigInteger bi2) {
return Kernel.Compare(bi1, bi2) >= 0;
}
public static Boolean operator <=(BigInteger bi1, BigInteger bi2) {
return Kernel.Compare(bi1, bi2) <= 0;
}
public Sign Compare(BigInteger bi) {
return Kernel.Compare(this, bi);
}
#endregion
#region Formatting
public String ToString(UInt32 radix) {
return ToString(radix, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public String ToString(UInt32 radix, String characterSet) {
if (characterSet.Length < radix)
throw new ArgumentException("charSet length less than radix", "characterSet");
if (radix == 1)
throw new ArgumentException("There is no such thing as radix one notation", "radix");
if (this == 0)
return "0";
if (this == 1)
return "1";
String result = "";
BigInteger a = new BigInteger(this);
while (a != 0) {
UInt32 rem = Kernel.SingleByteDivideInPlace(a, radix);
result = characterSet[(Int32)rem] + result;
}
return result;
}
#endregion
#region Misc
private void Normalize() {
// Normalize length
while (length > 0 && data[length - 1] == 0) {
length--;
}
// Check for zero
if (length == 0) {
length++;
}
}
public void Clear() {
for (Int32 i = 0; i < length; i++) {
data[i] = 0x00;
}
}
#endregion
#region Object Impl
public override Int32 GetHashCode() {
UInt32 val = 0;
for (UInt32 i = 0; i < this.length; i++)
val ^= this.data[i];
return (Int32)val;
}
public override String ToString() {
return ToString(10);
}
public override Boolean Equals(Object o) {
if (o == null)
return false;
if (o is Int32)
return (Int32)o >= 0 && this == (UInt32)o;
BigInteger bi = o as BigInteger;
if (bi == null)
return false;
return Kernel.Compare(this, bi) == 0;
}
#endregion
#region Number Theory
public BigInteger ModPow(BigInteger exp, BigInteger n) {
ModulusRing mr = new ModulusRing(n);
return mr.Pow(this, exp);
}
#endregion
public sealed class ModulusRing {
BigInteger mod, constant;
public ModulusRing(BigInteger modulus) {
this.mod = modulus;
// calculate constant = b^ (2k) / m
UInt32 i = mod.length << 1;
constant = new BigInteger(Sign.Positive, i + 1);
constant.data[i] = 0x00000001;
constant = constant / mod;
}
public void BarrettReduction(BigInteger x) {
BigInteger n = mod;
UInt32 k = n.length,
kPlusOne = k + 1,
kMinusOne = k - 1;
// x < mod, so nothing to do.
if (x.length < k) {
return;
}
BigInteger q3;
//
// Validate pointers
//
if (x.data.Length < x.length) {
throw new IndexOutOfRangeException("x out of range");
}
// q1 = x / b^ (k-1)
// q2 = q1 * constant
// q3 = q2 / b^ (k+1), Needs to be accessed with an offset of kPlusOne
// TODO: We should the method in HAC p 604 to do this (14.45)
q3 = new BigInteger(Sign.Positive, x.length - kMinusOne + constant.length);
Kernel.Multiply(x.data, kMinusOne, x.length - kMinusOne, constant.data, 0, constant.length, q3.data, 0);
// r1 = x mod b^ (k+1)
// i.e. keep the lowest (k+1) words
UInt32 lengthToCopy = (x.length > kPlusOne) ? kPlusOne : x.length;
x.length = lengthToCopy;
x.Normalize();
// r2 = (q3 * n) mod b^ (k+1)
// partial multiplication of q3 and n
BigInteger r2 = new BigInteger(Sign.Positive, kPlusOne);
Kernel.MultiplyMod2p32pmod(q3.data, (Int32)kPlusOne, (Int32)q3.length - (Int32)kPlusOne, n.data, 0, (Int32)n.length, r2.data, 0, (Int32)kPlusOne);
r2.Normalize();
if (r2 <= x) {
Kernel.MinusEq(x, r2);
}
else {
BigInteger val = new BigInteger(Sign.Positive, kPlusOne + 1);
val.data[kPlusOne] = 0x00000001;
Kernel.MinusEq(val, r2);
Kernel.PlusEq(x, val);
}
while (x >= n) {
Kernel.MinusEq(x, n);
}
}
public BigInteger Multiply(BigInteger a, BigInteger b) {
if (a == 0 || b == 0) {
return 0;
}
if (a > mod) {
a %= mod;
}
if (b > mod) {
b %= mod;
}
BigInteger ret = new BigInteger(a * b);
BarrettReduction(ret);
return ret;
}
public BigInteger Difference(BigInteger a, BigInteger b) {
Sign cmp = Kernel.Compare(a, b);
BigInteger diff;
switch (cmp) {
case Sign.Zero:
return 0;
case Sign.Positive:
diff = a - b;
break;
case Sign.Negative:
diff = b - a;
break;
default:
throw new Exception();
}
if (diff >= mod) {
if (diff.length >= mod.length << 1) {
diff %= mod;
}
else {
BarrettReduction(diff);
}
}
if (cmp == Sign.Negative) {
diff = mod - diff;
}
return diff;
}
public BigInteger Pow(BigInteger a, BigInteger k) {
BigInteger b = new BigInteger(1);
if (k == 0) {
return b;
}
BigInteger A = a;
if (k.TestBit(0)) {
b = a;
}
for (Int32 i = 1; i < k.BitCount(); i++) {
A = Multiply(A, A);
if (k.TestBit(i)) {
b = Multiply(A, b);
}
}
return b;
}
#region Pow Small Base
// TODO: Make tests for this, not really needed b/c prime stuff
// checks it, but still would be nice
public BigInteger Pow(UInt32 b, BigInteger exp) {
return Pow(new BigInteger(b), exp);
}
#endregion
}
private sealed class Kernel {
#region Addition/Subtraction
public static BigInteger AddSameSign(BigInteger bi1, BigInteger bi2) {
UInt32[] x, y;
UInt32 yMax, xMax, i = 0;
// x should be bigger
if (bi1.length < bi2.length) {
x = bi2.data;
xMax = bi2.length;
y = bi1.data;
yMax = bi1.length;
}
else {
x = bi1.data;
xMax = bi1.length;
y = bi2.data;
yMax = bi2.length;
}
BigInteger result = new BigInteger(Sign.Positive, xMax + 1);
UInt32[] r = result.data;
UInt64 sum = 0;
// Add common parts of both numbers
do {
sum = ((UInt64)x[i]) + ((UInt64)y[i]) + sum;
r[i] = (UInt32)sum;
sum >>= 32;
} while (++i < yMax);
// Copy remainder of longer number while carry propagation is required
Boolean carry = (sum != 0);
if (carry) {
if (i < xMax) {
do {
carry = ((r[i] = x[i] + 1) == 0);
} while (++i < xMax && carry);
}
if (carry) {
r[i] = 1;
result.length = ++i;
return result;
}
}
// Copy the rest
if (i < xMax) {
do {
r[i] = x[i];
} while (++i < xMax);
}
result.Normalize();
return result;
}
public static BigInteger Subtract(BigInteger big, BigInteger small) {
BigInteger result = new BigInteger(Sign.Positive, big.length);
UInt32[] r = result.data, b = big.data, s = small.data;
UInt32 i = 0, c = 0;
do {
UInt32 x = s[i];
if (((x += c) < c) | ((r[i] = b[i] - x) > ~x)) {
c = 1;
}
else {
c = 0;
}
} while (++i < small.length);
if (i == big.length) {
result.Normalize();
return result;
}
if (c == 1) {
do {
r[i] = b[i] - 1;
} while (b[i++] == 0 && i < big.length);
if (i == big.length) {
result.Normalize();
return result;
}
}
do {
r[i] = b[i];
} while (++i < big.length);
result.Normalize();
return result;
}
public static void MinusEq(BigInteger big, BigInteger small) {
UInt32[] b = big.data, s = small.data;
UInt32 i = 0, c = 0;
do {
UInt32 x = s[i];
if (((x += c) < c) | ((b[i] -= x) > ~x)) {
c = 1;
}
else {
c = 0;
}
} while (++i < small.length);
if (i != big.length && c == 1) {
do {
b[i]--;
} while (b[i++] == 0 && i < big.length);
}
// Normalize length
while (big.length > 0 && big.data[big.length - 1] == 0) {
big.length--;
}
// Check for zero
if (big.length == 0) {
big.length++;
}
}
public static void PlusEq(BigInteger bi1, BigInteger bi2) {
UInt32[] x, y;
UInt32 yMax, xMax, i = 0;
Boolean flag = false;
// x should be bigger
if (bi1.length < bi2.length) {
flag = true;
x = bi2.data;
xMax = bi2.length;
y = bi1.data;
yMax = bi1.length;
}
else {
x = bi1.data;
xMax = bi1.length;
y = bi2.data;
yMax = bi2.length;
}
UInt32[] r = bi1.data;
UInt64 sum = 0;
// Add common parts of both numbers
do {
sum += ((UInt64)x[i]) + ((UInt64)y[i]);
r[i] = (UInt32)sum;
sum >>= 32;
} while (++i < yMax);
// Copy remainder of longer number while carry propagation is required
Boolean carry = (sum != 0);
if (carry) {
if (i < xMax) {
do {
carry = ((r[i] = x[i] + 1) == 0);
} while (++i < xMax && carry);
}
if (carry) {
r[i] = 1;
bi1.length = ++i;
return;
}
}
// Copy the rest
if (flag && i < xMax - 1) {
do {
r[i] = x[i];
} while (++i < xMax);
}
bi1.length = xMax + 1;
bi1.Normalize();
}
#endregion
#region Compare
public static Sign Compare(BigInteger bi1, BigInteger bi2) {
//
// Step 1. Compare the lengths
//
UInt32 l1 = bi1.length, l2 = bi2.length;
while (l1 > 0 && bi1.data[l1 - 1] == 0) {
l1--;
}
while (l2 > 0 && bi2.data[l2 - 1] == 0) {
l2--;
}
if (l1 == 0 && l2 == 0) {
return Sign.Zero;
}
// bi1 len < bi2 len
if (l1 < l2) {
return Sign.Negative;
}
// bi1 len > bi2 len
else if (l1 > l2) {
return Sign.Positive;
}
//
// Step 2. Compare the bits
//
UInt32 pos = l1 - 1;
while (pos != 0 && bi1.data[pos] == bi2.data[pos]) {
pos--;
}
if (bi1.data[pos] < bi2.data[pos]) {
return Sign.Negative;
}
else if (bi1.data[pos] > bi2.data[pos]) {
return Sign.Positive;
}
else {
return Sign.Zero;
}
}
#endregion
#region Division
#region Dword
public static UInt32 SingleByteDivideInPlace(BigInteger n, UInt32 d) {
UInt64 r = 0;
UInt32 i = n.length;
while (i-- > 0) {
r <<= 32;
r |= n.data[i];
n.data[i] = (UInt32)(r / d);
r %= d;
}
n.Normalize();
return (UInt32)r;
}
public static UInt32 DwordMod(BigInteger n, UInt32 d) {
UInt64 r = 0;
UInt32 i = n.length;
while (i-- > 0) {
r <<= 32;
r |= n.data[i];
r %= d;
}
return (UInt32)r;
}
public static BigInteger DwordDiv(BigInteger n, UInt32 d) {
BigInteger ret = new BigInteger(Sign.Positive, n.length);
UInt64 r = 0;
UInt32 i = n.length;
while (i-- > 0) {
r <<= 32;
r |= n.data[i];
ret.data[i] = (UInt32)(r / d);
r %= d;
}
ret.Normalize();
return ret;
}
public static BigInteger[] DwordDivMod(BigInteger n, UInt32 d) {
BigInteger ret = new BigInteger(Sign.Positive, n.length);
UInt64 r = 0;
UInt32 i = n.length;
while (i-- > 0) {
r <<= 32;
r |= n.data[i];
ret.data[i] = (UInt32)(r / d);
r %= d;
}
ret.Normalize();
BigInteger rem = (UInt32)r;
return new BigInteger[] { ret, rem };
}
#endregion
#region BigNum
public static BigInteger[] multiByteDivide(BigInteger bi1, BigInteger bi2) {
if (Kernel.Compare(bi1, bi2) == Sign.Negative) {
return new BigInteger[2] { 0, new BigInteger(bi1) };
}
bi1.Normalize();
bi2.Normalize();
if (bi2.length == 1) {
return DwordDivMod(bi1, bi2.data[0]);
}
UInt32 remainderLen = bi1.length + 1;
Int32 divisorLen = (Int32)bi2.length + 1;
UInt32 mask = 0x80000000;
UInt32 val = bi2.data[bi2.length - 1];
Int32 shift = 0;
Int32 resultPos = (Int32)bi1.length - (Int32)bi2.length;
while (mask != 0 && (val & mask) == 0) {
shift++;
mask >>= 1;
}
BigInteger quot = new BigInteger(Sign.Positive, bi1.length - bi2.length + 1);
BigInteger rem = (bi1 << shift);
UInt32[] remainder = rem.data;
bi2 = bi2 << shift;
Int32 j = (Int32)(remainderLen - bi2.length);
Int32 pos = (Int32)remainderLen - 1;
UInt32 firstDivisorByte = bi2.data[bi2.length - 1];
UInt64 secondDivisorByte = bi2.data[bi2.length - 2];
while (j > 0) {
UInt64 dividend = ((UInt64)remainder[pos] << 32) + (UInt64)remainder[pos - 1];
UInt64 q_hat = dividend / (UInt64)firstDivisorByte;
UInt64 r_hat = dividend % (UInt64)firstDivisorByte;
do {
if (q_hat == 0x100000000 ||
(q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos - 2])) {
q_hat--;
r_hat += (UInt64)firstDivisorByte;
if (r_hat < 0x100000000) {
continue;
}
}
break;
} while (true);
//
// At this point, q_hat is either exact, or one too large
// (more likely to be exact) so, we attempt to multiply the
// divisor by q_hat, if we get a borrow, we just subtract
// one from q_hat and add the divisor back.
//
UInt32 t;
UInt32 dPos = 0;
Int32 nPos = pos - divisorLen + 1;
UInt64 mc = 0;
UInt32 uint_q_hat = (UInt32)q_hat;
do {
mc += (UInt64)bi2.data[dPos] * (UInt64)uint_q_hat;
t = remainder[nPos];
remainder[nPos] -= (UInt32)mc;
mc >>= 32;
if (remainder[nPos] > t) {
mc++;
}
dPos++;
nPos++;
} while (dPos < divisorLen);
nPos = pos - divisorLen + 1;
dPos = 0;
// Overestimate
if (mc != 0) {
uint_q_hat--;
UInt64 sum = 0;
do {
sum = ((UInt64)remainder[nPos]) + ((UInt64)bi2.data[dPos]) + sum;
remainder[nPos] = (UInt32)sum;
sum >>= 32;
dPos++;
nPos++;
} while (dPos < divisorLen);
}
quot.data[resultPos--] = (UInt32)uint_q_hat;
pos--;
j--;
}
quot.Normalize();
rem.Normalize();
BigInteger[] ret = new BigInteger[2] { quot, rem };
if (shift != 0) {
ret[1] >>= shift;
}
return ret;
}
#endregion
#endregion
#region Shift
public static BigInteger LeftShift(BigInteger bi, Int32 n) {
if (n == 0) {
return new BigInteger(bi, bi.length + 1);
}
Int32 w = n >> 5;
n &= ((1 << 5) - 1);
BigInteger ret = new BigInteger(Sign.Positive, bi.length + 1 + (UInt32)w);
UInt32 i = 0, l = bi.length;
if (n != 0) {
UInt32 x, carry = 0;
while (i < l) {
x = bi.data[i];
ret.data[i + w] = (x << n) | carry;
carry = x >> (32 - n);
i++;
}
ret.data[i + w] = carry;
}
else {
while (i < l) {
ret.data[i + w] = bi.data[i];
i++;
}
}
ret.Normalize();
return ret;
}
public static BigInteger RightShift(BigInteger bi, Int32 n) {
if (n == 0) {
return new BigInteger(bi);
}
Int32 w = n >> 5;
n &= ((1 << 5) - 1);
BigInteger ret = new BigInteger(Sign.Positive, bi.length - (UInt32)w + 1);
UInt32 l = (UInt32)ret.data.Length - 1;
if (n != 0) {
UInt32 x, carry = 0;
while (l-- > 0) {
x = bi.data[l + w];
ret.data[l] = (x >> n) | carry;
carry = x << (32 - n);
}
}
else {
while (l-- > 0) {
ret.data[l] = bi.data[l + w];
}
}
ret.Normalize();
return ret;
}
#endregion
#region Multiply
public static BigInteger MultiplyByDword(BigInteger n, UInt32 f) {
BigInteger ret = new BigInteger(Sign.Positive, n.length + 1);
UInt32 i = 0;
UInt64 c = 0;
do {
c += (UInt64)n.data[i] * (UInt64)f;
ret.data[i] = (UInt32)c;
c >>= 32;
} while (++i < n.length);
ret.data[i] = (UInt32)c;
ret.Normalize();
return ret;
}
/// <summary>
/// Multiplies the data in x [xOffset:xOffset+xLen] by
/// y [yOffset:yOffset+yLen] and puts it into
/// d [dOffset:dOffset+xLen+yLen].
/// </summary>
/// <remarks>
/// This code is unsafe! It is the caller's responsibility to make
/// sure that it is safe to access x [xOffset:xOffset+xLen],
/// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+xLen+yLen].
/// </remarks>
public static void Multiply(UInt32[] x, UInt32 xOffset, UInt32 xLen, UInt32[] y, UInt32 yOffset, UInt32 yLen, UInt32[] d, UInt32 dOffset) {
UInt32 yE = yOffset + yLen;
for (UInt32 xE = xOffset + xLen; xOffset < xE; xOffset++, dOffset++) {
if (x[xOffset] == 0) {
continue;
}
UInt64 mcarry = 0;
UInt32 dP = dOffset;
for (UInt32 yP = yOffset; yP < yE; yP++, dP++) {
mcarry += ((UInt64)x[xOffset] * (UInt64)y[yP]) + (UInt64)d[dP];
d[dP] = (UInt32)mcarry;
mcarry >>= 32;
}
if (mcarry != 0) {
d[dP] = (UInt32)mcarry;
}
}
}
/// <summary>
/// Multiplies the data in x [xOffset:xOffset+xLen] by
/// y [yOffset:yOffset+yLen] and puts the low mod words into
/// d [dOffset:dOffset+mod].
/// </summary>
/// <remarks>
/// This code is unsafe! It is the caller's responsibility to make
/// sure that it is safe to access x [xOffset:xOffset+xLen],
/// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+mod].
/// </remarks>
public static void MultiplyMod2p32pmod(UInt32[] x, Int32 xOffset, Int32 xLen, UInt32[] y, Int32 yOffest, Int32 yLen, UInt32[] d, Int32 dOffset, Int32 mod) {
UInt32 xP = (UInt32)xOffset, xE = xP + (UInt32)xLen, yB = (UInt32)yOffest, yE = yB + (UInt32)yLen, dB = (UInt32)dOffset, dE = dB + (UInt32)mod;
for (; xP < xE; xP++, dB++) {
if (x[xP] == 0) {
continue;
}
UInt64 mcarry = 0;
UInt32 dP = dB;
for (UInt32 yP = yB; yP < yE && dP < dE; yP++, dP++) {
mcarry += ((UInt64)x[xP] * (UInt64)y[yP]) + (UInt64)d[dP];
d[dP] = (UInt32)mcarry;
mcarry >>= 32;
}
if (mcarry != 0 && dP < dE) {
d[dP] = (UInt32)mcarry;
}
}
}
public static void SquarePositive(BigInteger bi, ref UInt32[] wkSpace) {
UInt32[] t = wkSpace;
wkSpace = bi.data;
UInt32[] d = bi.data;
UInt32 dl = bi.length;
bi.data = t;
UInt32 ttE = (UInt32)t.Length;
// Clear the dest
for (UInt32 ttt = 0; ttt < ttE; ttt++) {
t[ttt] = 0;
}
UInt32 dP = 0, tP = 0;
for (UInt32 i = 0; i < dl; i++, dP++) {
if (d[dP] == 0) {
continue;
}
UInt64 mcarry = 0;
UInt32 bi1val = d[dP];
UInt32 dP2 = dP + 1, tP2 = tP + 2 * i + 1;
for (UInt32 j = i + 1; j < dl; j++, tP2++, dP2++) {
// k = i + j
mcarry += ((UInt64)bi1val * (UInt64)d[dP2]) + t[tP2];
t[tP2] = (UInt32)mcarry;
mcarry >>= 32;
}
if (mcarry != 0) {
t[tP2] = (UInt32)mcarry;
}
}
// Double t. Inlined for speed.
tP = 0;
UInt32 x, carry = 0;
while (tP < ttE) {
x = t[tP];
t[tP] = (x << 1) | carry;
carry = x >> (32 - 1);
tP++;
}
if (carry != 0) {
t[tP] = carry;
}
// Add in the diagnals
dP = 0;
tP = 0;
for (UInt32 dE = dP + dl; (dP < dE); dP++, tP++) {
UInt64 val = (UInt64)d[dP] * (UInt64)d[dP] + t[tP];
t[tP] = (UInt32)val;
val >>= 32;
t[(++tP)] += (UInt32)val;
if (t[tP] < (UInt32)val) {
UInt32 tP3 = tP;
// Account for the first carry
(t[++tP3])++;
// Keep adding until no carry
while ((t[tP3++]) == 0) {
(t[tP3])++;
}
}
}
bi.length <<= 1;
// Normalize length
while (t[bi.length - 1] == 0 && bi.length > 1) {
bi.length--;
}
}
#endregion
}
}
}
| |
// 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.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics.Models
{
using Analytics;
using Azure;
using DataLake;
using Management;
using Azure;
using Management;
using DataLake;
using Analytics;
using Newtonsoft.Json;
using Rest;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The common Data Lake Analytics job information properties.
/// </summary>
public partial class JobInformation
{
/// <summary>
/// Initializes a new instance of the JobInformation class.
/// </summary>
public JobInformation() { }
/// <summary>
/// Initializes a new instance of the JobInformation class.
/// </summary>
/// <param name="name">the friendly name of the job.</param>
/// <param name="type">the job type of the current job (Hive or USql).
/// Possible values include: 'USql', 'Hive'</param>
/// <param name="properties">the job specific properties.</param>
/// <param name="jobId">the job's unique identifier (a GUID).</param>
/// <param name="submitter">the user or account that submitted the
/// job.</param>
/// <param name="errorMessage">the error message details for the job,
/// if the job failed.</param>
/// <param name="degreeOfParallelism">the degree of parallelism used
/// for this job. This must be greater than 0, if set to less than 0 it
/// will default to 1.</param>
/// <param name="priority">the priority value for the current job.
/// Lower numbers have a higher priority. By default, a job has a
/// priority of 1000. This must be greater than 0.</param>
/// <param name="submitTime">the time the job was submitted to the
/// service.</param>
/// <param name="startTime">the start time of the job.</param>
/// <param name="endTime">the completion time of the job.</param>
/// <param name="state">the job state. When the job is in the Ended
/// state, refer to Result and ErrorMessage for details. Possible
/// values include: 'Accepted', 'Compiling', 'Ended', 'New', 'Queued',
/// 'Running', 'Scheduling', 'Starting', 'Paused',
/// 'WaitingForCapacity'</param>
/// <param name="result">the result of job execution or the current
/// result of the running job. Possible values include: 'None',
/// 'Succeeded', 'Cancelled', 'Failed'</param>
/// <param name="logFolder">the log folder path to use in the following
/// format:
/// adl://<accountName>.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/.</param>
/// <param name="logFilePatterns">the list of log file name patterns to
/// find in the logFolder. '*' is the only matching character allowed.
/// Example format: jobExecution*.log or *mylog*.txt</param>
/// <param name="stateAuditRecords">the job state audit records,
/// indicating when various operations have been performed on this
/// job.</param>
public JobInformation(string name, JobType type, JobProperties properties, System.Guid? jobId = default(System.Guid?), string submitter = default(string), IList<JobErrorDetails> errorMessage = default(IList<JobErrorDetails>), int? degreeOfParallelism = default(int?), int? priority = default(int?), System.DateTimeOffset? submitTime = default(System.DateTimeOffset?), System.DateTimeOffset? startTime = default(System.DateTimeOffset?), System.DateTimeOffset? endTime = default(System.DateTimeOffset?), JobState? state = default(JobState?), JobResult? result = default(JobResult?), string logFolder = default(string), IList<string> logFilePatterns = default(IList<string>), IList<JobStateAuditRecord> stateAuditRecords = default(IList<JobStateAuditRecord>))
{
JobId = jobId;
Name = name;
Type = type;
Submitter = submitter;
ErrorMessage = errorMessage;
DegreeOfParallelism = degreeOfParallelism;
Priority = priority;
SubmitTime = submitTime;
StartTime = startTime;
EndTime = endTime;
State = state;
Result = result;
LogFolder = logFolder;
LogFilePatterns = logFilePatterns;
StateAuditRecords = stateAuditRecords;
Properties = properties;
}
/// <summary>
/// Gets the job's unique identifier (a GUID).
/// </summary>
[JsonProperty(PropertyName = "jobId")]
public System.Guid? JobId { get; protected set; }
/// <summary>
/// Gets or sets the friendly name of the job.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the job type of the current job (Hive or USql).
/// Possible values include: 'USql', 'Hive'
/// </summary>
[JsonProperty(PropertyName = "type")]
public JobType Type { get; set; }
/// <summary>
/// Gets the user or account that submitted the job.
/// </summary>
[JsonProperty(PropertyName = "submitter")]
public string Submitter { get; protected set; }
/// <summary>
/// Gets the error message details for the job, if the job failed.
/// </summary>
[JsonProperty(PropertyName = "errorMessage")]
public IList<JobErrorDetails> ErrorMessage { get; protected set; }
/// <summary>
/// Gets or sets the degree of parallelism used for this job. This must
/// be greater than 0, if set to less than 0 it will default to 1.
/// </summary>
[JsonProperty(PropertyName = "degreeOfParallelism")]
public int? DegreeOfParallelism { get; set; }
/// <summary>
/// Gets or sets the priority value for the current job. Lower numbers
/// have a higher priority. By default, a job has a priority of 1000.
/// This must be greater than 0.
/// </summary>
[JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets the time the job was submitted to the service.
/// </summary>
[JsonProperty(PropertyName = "submitTime")]
public System.DateTimeOffset? SubmitTime { get; protected set; }
/// <summary>
/// Gets the start time of the job.
/// </summary>
[JsonProperty(PropertyName = "startTime")]
public System.DateTimeOffset? StartTime { get; protected set; }
/// <summary>
/// Gets the completion time of the job.
/// </summary>
[JsonProperty(PropertyName = "endTime")]
public System.DateTimeOffset? EndTime { get; protected set; }
/// <summary>
/// Gets the job state. When the job is in the Ended state, refer to
/// Result and ErrorMessage for details. Possible values include:
/// 'Accepted', 'Compiling', 'Ended', 'New', 'Queued', 'Running',
/// 'Scheduling', 'Starting', 'Paused', 'WaitingForCapacity'
/// </summary>
[JsonProperty(PropertyName = "state")]
public JobState? State { get; protected set; }
/// <summary>
/// Gets the result of job execution or the current result of the
/// running job. Possible values include: 'None', 'Succeeded',
/// 'Cancelled', 'Failed'
/// </summary>
[JsonProperty(PropertyName = "result")]
public JobResult? Result { get; protected set; }
/// <summary>
/// Gets the log folder path to use in the following format:
/// adl://&lt;accountName&gt;.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/.
/// </summary>
[JsonProperty(PropertyName = "logFolder")]
public string LogFolder { get; protected set; }
/// <summary>
/// Gets or sets the list of log file name patterns to find in the
/// logFolder. '*' is the only matching character allowed. Example
/// format: jobExecution*.log or *mylog*.txt
/// </summary>
[JsonProperty(PropertyName = "logFilePatterns")]
public IList<string> LogFilePatterns { get; set; }
/// <summary>
/// Gets the job state audit records, indicating when various
/// operations have been performed on this job.
/// </summary>
[JsonProperty(PropertyName = "stateAuditRecords")]
public IList<JobStateAuditRecord> StateAuditRecords { get; protected set; }
/// <summary>
/// Gets or sets the job specific properties.
/// </summary>
[JsonProperty(PropertyName = "properties")]
public JobProperties Properties { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Name");
}
if (Properties == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Properties");
}
if (Properties != null)
{
Properties.Validate();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.