context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) 2018 Algolia
* http://www.algolia.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.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Algolia.Search.Http;
using Algolia.Search.Models.Enums;
using Algolia.Search.Models.Insights;
using Algolia.Search.Utils;
namespace Algolia.Search.Clients
{
/// <summary>
/// Describe a user identifier class.
/// </summary>
public class UserInsightsClient
{
private readonly string _userToken;
private readonly InsightsClient _insightsClient;
/// <summary>
/// Create an instance for a user identifier
/// </summary>
/// <param name="userToken">A user identifier, format [a-zA-Z0-9_-]{1,64}.</param>
/// <param name="insightsClient">The insights client</param>
public UserInsightsClient(string userToken, InsightsClient insightsClient)
{
_userToken = userToken;
_insightsClient = insightsClient;
}
// Click
/// <summary>
/// Send events when filters are clicked
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="filters">A filter is defined by the ${attr}${op}${value} string e.g. brand:apple. Limited to 10 filters.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ClickedFilters(string eventName, string indexName, IEnumerable<string> filters,
RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() => ClickedFiltersAsync(eventName, indexName, filters, requestOptions));
/// <summary>
/// Send events when filters are clicked
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="filters">A filter is defined by the ${attr}${op}${value} string e.g. brand:apple. Limited to 10 filters.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ClickedFiltersAsync(string eventName, string indexName,
IEnumerable<string> filters, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.Click,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
Filters = filters
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
/// <summary>
/// Send events when objectIDs are clicked
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ClickedObjectIDs(string eventName, string indexName, IEnumerable<string> objectIDs,
RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() => ClickedObjectIDsAsync(eventName, indexName, objectIDs, requestOptions));
/// <summary>
/// Send events when objectIDs are clicked
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ClickedObjectIDsAsync(string eventName, string indexName,
IEnumerable<string> objectIDs, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.Click,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
ObjectIDs = objectIDs
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
/// <summary>
/// Send events after a search when objectIDs are clicked
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="positions">Position of the click in the list of Algolia search results</param>
/// <param name="queryID">Algolia queryID, format: [a-z1-9]{32}.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ClickedObjectIDsAfterSearch(string eventName, string indexName,
IEnumerable<string> objectIDs, IEnumerable<uint> positions, string queryID,
RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() =>
ClickedObjectIDsAfterSearchAsync(eventName, indexName, objectIDs, positions, queryID, requestOptions));
/// <summary>
/// Send events after a search when objectIDs are clicked
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="positions">Position of the click in the list of Algolia search results</param>
/// <param name="queryID">Algolia queryID, format: [a-z1-9]{32}.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ClickedObjectIDsAfterSearchAsync(string eventName, string indexName,
IEnumerable<string> objectIDs, IEnumerable<uint> positions, string queryID,
RequestOptions requestOptions = null, CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.Click,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
ObjectIDs = objectIDs,
Positions = positions,
QueryID = queryID
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
// Conversion
/// <summary>
/// Send events of converted objectIDs
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ConvertedObjectIDs(string eventName, string indexName, IEnumerable<string> objectIDs,
RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() => ConvertedObjectIDsAsync(eventName, indexName, objectIDs, requestOptions));
/// <summary>
/// Send events of converted objectIDs
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ConvertedObjectIDsAsync(string eventName, string indexName,
IEnumerable<string> objectIDs, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.Conversion,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
ObjectIDs = objectIDs
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
/// <summary>
/// Send events of converted objectIDs after a search
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="queryID">Algolia queryID, format: [a-z1-9]{32}.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ConvertedObjectIDsAfterSearch(string eventName, string indexName,
IEnumerable<string> objectIDs, string queryID, RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() =>
ConvertedObjectIDsAfterSearchAsync(eventName, indexName, objectIDs, queryID, requestOptions));
/// <summary>
/// Send events of converted objectIDs after a search
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="queryID">Algolia queryID, format: [a-z1-9]{32}.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ConvertedObjectIDsAfterSearchAsync(string eventName, string indexName,
IEnumerable<string> objectIDs, string queryID, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.Conversion,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
ObjectIDs = objectIDs,
QueryID = queryID
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
/// <summary>
/// Send events of filters conversion
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="filters">A filter is defined by the ${attr}${op}${value} string e.g. brand:apple. Limited to 10 filters.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public InsightsResponse ConvertedFilters(string eventName, string indexName, IEnumerable<string> filters,
RequestOptions requestOptions = null, CancellationToken ct = default) =>
AsyncHelper.RunSync(() => ConvertedFiltersAsync(eventName, indexName, filters, requestOptions, ct));
/// <summary>
/// Send events of filters conversion
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="filters">A filter is defined by the ${attr}${op}${value} string e.g. brand:apple. Limited to 10 filters.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ConvertedFiltersAsync(string eventName, string indexName,
IEnumerable<string> filters, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.Conversion,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
Filters = filters,
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
// View
/// <summary>
/// Send events when filters are viewed
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="filters">A filter is defined by the ${attr}${op}${value} string e.g. brand:apple. Limited to 10 filters.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ViewedFilters(string eventName, string indexName, IEnumerable<string> filters,
RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() => ViewedFiltersAsync(eventName, indexName, filters, requestOptions));
/// <summary>
/// Send events when filters are viewed
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="filters">A filter is defined by the ${attr}${op}${value} string e.g. brand:apple. Limited to 10 filters.</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ViewedFiltersAsync(string eventName, string indexName,
IEnumerable<string> filters, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.View,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
Filters = filters
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
/// <summary>
/// Send events when objectIDs are viewed
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <returns></returns>
public InsightsResponse ViewedObjectIDs(string eventName, string indexName, IEnumerable<string> objectIDs,
RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() => ViewedObjectIDsAsync(eventName, indexName, objectIDs, requestOptions));
/// <summary>
/// Send events when objectIDs are viewed
/// </summary>
/// <param name="eventName">User defined string, format: any ascii char except control points with length between 1 and 64.</param>
/// <param name="indexName">Index name, format, same as the engine.</param>
/// <param name="objectIDs">Array of index objectIDs. Limited to 20 objects</param>
/// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
/// <param name="ct">The cancellation token</param>
/// <returns></returns>
public async Task<InsightsResponse> ViewedObjectIDsAsync(string eventName, string indexName,
IEnumerable<string> objectIDs, RequestOptions requestOptions = null,
CancellationToken ct = default)
{
var insightEvent = new InsightsEvent
{
EventType = EventType.View,
UserToken = _userToken,
EventName = eventName,
Index = indexName,
ObjectIDs = objectIDs
};
return await _insightsClient.SendEventAsync(insightEvent, requestOptions, ct).ConfigureAwait(false);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlBoundElement.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
#pragma warning disable 618 // ignore obsolete warning about XmlDataDocument
namespace System.Xml {
using System.Data;
using System.Diagnostics;
internal enum ElementState {
None,
Defoliated,
WeakFoliation,
StrongFoliation,
Foliating,
Defoliating,
}
internal sealed class XmlBoundElement: XmlElement {
private DataRow row;
private ElementState state;
internal XmlBoundElement( string prefix, string localName, string namespaceURI, XmlDocument doc )
: base( prefix, localName, namespaceURI, doc ) {
state = ElementState.None;
}
public override XmlAttributeCollection Attributes {
get {
AutoFoliate();
return base.Attributes;
}
}
public override bool HasAttributes {
get { return Attributes.Count > 0; }
}
public override XmlNode FirstChild {
get {
AutoFoliate();
return base.FirstChild;
}
}
internal XmlNode SafeFirstChild { get { return base.FirstChild; } }
public override XmlNode LastChild {
get {
AutoFoliate();
return base.LastChild;
}
}
public override XmlNode PreviousSibling {
get {
XmlNode prev = base.PreviousSibling;
if ( prev == null ) {
XmlBoundElement parent = ParentNode as XmlBoundElement;
if ( parent != null ) {
parent.AutoFoliate();
return base.PreviousSibling;
}
}
return prev;
}
}
internal XmlNode SafePreviousSibling { get { return base.PreviousSibling; } }
public override XmlNode NextSibling {
get {
XmlNode next = base.NextSibling;
if ( next == null ) {
XmlBoundElement parent = ParentNode as XmlBoundElement;
if ( parent != null ) {
parent.AutoFoliate();
return base.NextSibling;
}
}
return next;
}
}
internal XmlNode SafeNextSibling { get { return base.NextSibling; } }
public override bool HasChildNodes {
get {
AutoFoliate();
return base.HasChildNodes;
}
}
public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) {
AutoFoliate();
return base.InsertBefore( newChild, refChild );
}
public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) {
AutoFoliate();
return base.InsertAfter( newChild, refChild );
}
public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) {
AutoFoliate();
return base.ReplaceChild( newChild, oldChild );
}
public override XmlNode AppendChild(XmlNode newChild) {
AutoFoliate();
return base.AppendChild( newChild );
}
internal void RemoveAllChildren() {
XmlNode child = FirstChild;
XmlNode sibling = null;
while ( child != null ) {
sibling = child.NextSibling;
RemoveChild( child );
child = sibling;
}
}
public override string InnerXml {
get {
return base.InnerXml;
}
set {
RemoveAllChildren();
XmlDataDocument doc = (XmlDataDocument) OwnerDocument;
bool bOrigIgnoreXmlEvents = doc.IgnoreXmlEvents;
bool bOrigIgnoreDataSetEvents = doc.IgnoreDataSetEvents;
doc.IgnoreXmlEvents = true;
doc.IgnoreDataSetEvents = true;
base.InnerXml = value;
doc.SyncTree( this );
doc.IgnoreDataSetEvents = bOrigIgnoreDataSetEvents;
doc.IgnoreXmlEvents = bOrigIgnoreXmlEvents;
}
}
internal DataRow Row {
get { return row;}
set { row = value;}
}
internal bool IsFoliated {
get {
while ( state == ElementState.Foliating || state == ElementState.Defoliating )
System.Threading.Thread.Sleep(0);
//has to be sure that we are either foliated or defoliated when ask for IsFoliated.
return state != ElementState.Defoliated;
}
}
internal ElementState ElementState {
get { return state;}
set { state = value;}
}
internal void Foliate( ElementState newState ) {
XmlDataDocument doc = (XmlDataDocument) OwnerDocument;
if ( doc != null )
doc.Foliate( this, newState );
}
// Foliate the node as a side effect of user calling functions on this node (like NextSibling) OR as a side effect of DataDocNav using nodes to do editing
private void AutoFoliate() {
XmlDataDocument doc = (XmlDataDocument) OwnerDocument;
if ( doc != null )
doc.Foliate( this, doc.AutoFoliationState );
}
public override XmlNode CloneNode(bool deep) {
XmlDataDocument doc = (XmlDataDocument)(this.OwnerDocument);
ElementState oldAutoFoliationState = doc.AutoFoliationState;
doc.AutoFoliationState = ElementState.WeakFoliation;
XmlElement element;
try {
Foliate( ElementState.WeakFoliation );
element = (XmlElement)(base.CloneNode( deep ));
// Clone should create a XmlBoundElement node
Debug.Assert( element is XmlBoundElement );
}
finally {
doc.AutoFoliationState = oldAutoFoliationState;
}
return element;
}
public override void WriteContentTo( XmlWriter w ) {
DataPointer dp = new DataPointer( (XmlDataDocument)OwnerDocument, this );
try {
dp.AddPointer();
WriteBoundElementContentTo( dp, w );
}
finally {
dp.SetNoLongerUse();
}
}
public override void WriteTo( XmlWriter w ) {
DataPointer dp = new DataPointer( (XmlDataDocument)OwnerDocument, this );
try {
dp.AddPointer();
WriteRootBoundElementTo( dp, w );
}
finally {
dp.SetNoLongerUse();
}
}
private void WriteRootBoundElementTo(DataPointer dp, XmlWriter w) {
Debug.Assert( dp.NodeType == XmlNodeType.Element );
XmlDataDocument doc = (XmlDataDocument)OwnerDocument;
w.WriteStartElement( dp.Prefix, dp.LocalName, dp.NamespaceURI );
int cAttr = dp.AttributeCount;
bool bHasXSI = false;
if ( cAttr > 0 ) {
for ( int iAttr = 0; iAttr < cAttr; iAttr++ ) {
dp.MoveToAttribute( iAttr );
if ( dp.Prefix == "xmlns" && dp.LocalName == XmlDataDocument.XSI )
bHasXSI = true;
WriteTo( dp, w );
dp.MoveToOwnerElement();
}
}
if ( !bHasXSI && doc.bLoadFromDataSet && doc.bHasXSINIL )
w.WriteAttributeString( "xmlns", "xsi", "http://www.w3.org/2000/xmlns/", Keywords.XSINS );
WriteBoundElementContentTo( dp, w );
// Force long end tag when the elem is not empty, even if there are no children.
if ( dp.IsEmptyElement )
w.WriteEndElement();
else
w.WriteFullEndElement();
}
private static void WriteBoundElementTo( DataPointer dp, XmlWriter w ) {
Debug.Assert( dp.NodeType == XmlNodeType.Element );
w.WriteStartElement( dp.Prefix, dp.LocalName, dp.NamespaceURI );
int cAttr = dp.AttributeCount;
if ( cAttr > 0 ) {
for ( int iAttr = 0; iAttr < cAttr; iAttr++ ) {
dp.MoveToAttribute( iAttr );
WriteTo( dp, w );
dp.MoveToOwnerElement();
}
}
WriteBoundElementContentTo( dp, w );
// Force long end tag when the elem is not empty, even if there are no children.
if ( dp.IsEmptyElement )
w.WriteEndElement();
else
w.WriteFullEndElement();
}
private static void WriteBoundElementContentTo( DataPointer dp, XmlWriter w ) {
if ( !dp.IsEmptyElement && dp.MoveToFirstChild() ) {
do {
WriteTo( dp, w );
}
while ( dp.MoveToNextSibling() );
dp.MoveToParent();
}
}
private static void WriteTo( DataPointer dp, XmlWriter w ) {
switch ( dp.NodeType ) {
case XmlNodeType.Attribute:
if ( !dp.IsDefault ) {
w.WriteStartAttribute( dp.Prefix, dp.LocalName, dp.NamespaceURI );
if ( dp.MoveToFirstChild() ) {
do {
WriteTo( dp, w );
}
while ( dp.MoveToNextSibling() );
dp.MoveToParent();
}
w.WriteEndAttribute();
}
break;
case XmlNodeType.Element:
WriteBoundElementTo( dp, w );
break;
case XmlNodeType.Text:
w.WriteString(dp.Value);
break;
default:
Debug.Assert( ((IXmlDataVirtualNode)dp).IsOnColumn( null ) );
if ( dp.GetNode() != null )
dp.GetNode().WriteTo( w );
break;
}
}
public override XmlNodeList GetElementsByTagName(string name) {
// Retrieving nodes from the returned nodelist may cause foliation which causes new nodes to be created,
// so the System.Xml iterator will throw if this happens during iteration. To avoid this, foliate everything
// before iteration, so iteration will not cause foliation (and as a result of this, creation of new nodes).
XmlNodeList tempNodeList = base.GetElementsByTagName(name);
int tempint = tempNodeList.Count;
return tempNodeList;
}
}
}
| |
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.BulletX.Dynamics
{
public delegate float ContactSolverFunc (RigidBody bodyA, RigidBody bodyB, ManifoldPoint contactPoint, ContactSolverInfo info);
public enum ContactSolverType
{
Default = 0,
TypeA,
TypeB,
User,
MaxContactSolverType,
}
public class ConstraintPersistentData
{
// total applied impulse during most recent frame
private float _appliedImpulse;
private float _previousAppliedImpulse;
private float _accumulatedTangentImpulse0;
private float _accumulatedTangentImpulse1;
private float _jacDiagABInv;
private float _jacDiagABInvTangentA;
private float _jacDiagABInvTangentB;
private int _persistentLifeTime;
private float _restitution;
private float _friction;
private float _penetration;
private Vector3 _frictionWorldTangentialA;
private Vector3 _frictionWorldTangentialB;
private Vector3 _frictionAngularComponent0A;
private Vector3 _frictionAngularComponent0B;
private Vector3 _frictionAngularComponent1A;
private Vector3 _frictionAngularComponent1B;
//some data doesn't need to be persistent over frames: todo: clean/reuse this
private Vector3 _angularComponentA;
private Vector3 _angularComponentB;
private ContactSolverFunc _contactSolverFunc;
private ContactSolverFunc _frictionSolverFunc;
public float AppliedImpulse { get { return _appliedImpulse; } set { _appliedImpulse = value; } }
public float PreviousAppliedImpulse { get { return _previousAppliedImpulse; } set { _previousAppliedImpulse = value; } }
public float AccumulatedTangentImpulseA { get { return _accumulatedTangentImpulse0; } set { _accumulatedTangentImpulse0 = value; } }
public float AccumulatedTangentImpulseB { get { return _accumulatedTangentImpulse1; } set { _accumulatedTangentImpulse1 = value; } }
public float JacDiagABInv { get { return _jacDiagABInv; } set { _jacDiagABInv = value; } }
public float JacDiagABInvTangentA { get { return _jacDiagABInvTangentA; } set { _jacDiagABInvTangentA = value; } }
public float JacDiagABInvTangentB { get { return _jacDiagABInvTangentB; } set { _jacDiagABInvTangentB = value; } }
public int PersistentLifeTime { get { return _persistentLifeTime; } set { _persistentLifeTime = value; } }
public float Restitution { get { return _restitution; } set { _restitution = value; } }
public float Friction { get { return _friction; } set { _friction = value; } }
public float Penetration { get { return _penetration; } set { _penetration = value; } }
public Vector3 FrictionWorldTangentialA { get { return _frictionWorldTangentialA; } set { _frictionWorldTangentialA = value; } }
public Vector3 FrictionWorldTangentialB { get { return _frictionWorldTangentialB; } set { _frictionWorldTangentialB = value; } }
public Vector3 FrictionAngularComponent0A { get { return _frictionAngularComponent0A; } set { _frictionAngularComponent0A = value; } }
public Vector3 FrictionAngularComponent0B { get { return _frictionAngularComponent0B; } set { _frictionAngularComponent0B = value; } }
public Vector3 FrictionAngularComponent1A { get { return _frictionAngularComponent1A; } set { _frictionAngularComponent1A = value; } }
public Vector3 FrictionAngularComponent1B { get { return _frictionAngularComponent1B; } set { _frictionAngularComponent1B = value; } }
public Vector3 AngularComponentA { get { return _angularComponentA; } set { _angularComponentA = value; } }
public Vector3 AngularComponentB { get { return _angularComponentB; } set { _angularComponentB = value; } }
public ContactSolverFunc ContactSolverFunc { get { return _contactSolverFunc; } set { _contactSolverFunc = value; } }
public ContactSolverFunc FrictionSolverFunc { get { return _frictionSolverFunc; } set { _frictionSolverFunc = value; } }
}
public static class ContactConstraint
{
private const int UseInternalApplyImpulse = 1;
/// <summary>
/// bilateral constraint between two dynamic objects
/// positive distance = separation, negative distance = penetration
/// </summary>
/// <param name="body1"></param>
/// <param name="pos1"></param>
/// <param name="body2"></param>
/// <param name="pos2"></param>
/// <param name="distance"></param>
/// <param name="normal"></param>
/// <param name="impulse"></param>
/// <param name="timeStep"></param>
public static void ResolveSingleBilateral(RigidBody bodyA, Vector3 posA,
RigidBody bodyB, Vector3 posB,
float distance, Vector3 normal, out float impulse, float timeStep)
{
float normalLenSqr = normal.LengthSquared();
if (Math.Abs(normalLenSqr) >= 1.1f)
throw new BulletException();
/*if (normalLenSqr > 1.1f)
{
impulse = 0f;
return;
}*/
Vector3 rel_pos1 = posA - bodyA.CenterOfMassPosition;
Vector3 rel_pos2 = posB - bodyB.CenterOfMassPosition;
//this jacobian entry could be re-used for all iterations
Vector3 vel1 = bodyA.GetVelocityInLocalPoint(rel_pos1);
Vector3 vel2 = bodyB.GetVelocityInLocalPoint(rel_pos2);
Vector3 vel = vel1 - vel2;
JacobianEntry jac = new JacobianEntry(Matrix.Transpose(bodyA.CenterOfMassTransform),
Matrix.Transpose(bodyB.CenterOfMassTransform),
rel_pos1, rel_pos2, normal, bodyA.InvInertiaDiagLocal, bodyA.InverseMass,
bodyB.InvInertiaDiagLocal, bodyB.InverseMass);
float jacDiagAB = jac.Diagonal;
float jacDiagABInv = 1f / jacDiagAB;
float rel_vel = jac.GetRelativeVelocity(
bodyA.LinearVelocity,
Vector3.TransformNormal(bodyA.AngularVelocity, Matrix.Transpose(bodyA.CenterOfMassTransform)),
bodyB.LinearVelocity,
Vector3.TransformNormal(bodyB.AngularVelocity, Matrix.Transpose(bodyB.CenterOfMassTransform)));
float a;
a = jacDiagABInv;
rel_vel = Vector3.Dot(normal, vel);
float contactDamping = 0.2f;
float velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
impulse = velocityImpulse;
}
/// <summary>
/// contact constraint resolution:
/// calculate and apply impulse to satisfy non-penetration and non-negative relative velocity constraint
/// positive distance = separation, negative distance = penetration
/// </summary>
/// <param name="body1"></param>
/// <param name="body2"></param>
/// <param name="contactPoint"></param>
/// <param name="info"></param>
/// <returns></returns>
public static float ResolveSingleCollision(RigidBody bodyA, RigidBody bodyB,
ManifoldPoint contactPoint, ContactSolverInfo solverInfo)
{
Vector3 pos1 = contactPoint.PositionWorldOnA;
Vector3 pos2 = contactPoint.PositionWorldOnB;
// printf("distance=%f\n",distance);
Vector3 normal = contactPoint.NormalWorldOnB;
Vector3 rel_pos1 = pos1 - bodyA.CenterOfMassPosition;
Vector3 rel_pos2 = pos2 - bodyB.CenterOfMassPosition;
Vector3 vel1 = bodyA.GetVelocityInLocalPoint(rel_pos1);
Vector3 vel2 = bodyB.GetVelocityInLocalPoint(rel_pos2);
Vector3 vel = vel1 - vel2;
float rel_vel;
rel_vel = Vector3.Dot(normal, vel);
float Kfps = 1f / solverInfo.TimeStep;
//float damping = solverInfo.m_damping;
float Kerp = solverInfo.Erp;
float Kcor = Kerp * Kfps;
//printf("dist=%f\n",distance);
ConstraintPersistentData cpd = contactPoint.UserPersistentData as ConstraintPersistentData;
if (cpd == null)
throw new BulletException();
float distance = cpd.Penetration;//contactPoint.getDistance();
//distance = 0.f;
float positionalError = Kcor * -distance;
//jacDiagABInv;
float velocityError = cpd.Restitution - rel_vel;// * damping;
float penetrationImpulse = positionalError * cpd.JacDiagABInv;
float velocityImpulse = velocityError * cpd.JacDiagABInv;
float normalImpulse = penetrationImpulse + velocityImpulse;
// See Erin Catto's GDC 2006 paper: Clamp the accumulated impulse
float oldNormalImpulse = cpd.AppliedImpulse;
float sum = oldNormalImpulse + normalImpulse;
cpd.AppliedImpulse = 0f > sum ? 0f : sum;
normalImpulse = cpd.AppliedImpulse - oldNormalImpulse;
if (bodyA.InverseMass != 0)
{
bodyA.InternalApplyImpulse(contactPoint.NormalWorldOnB * bodyA.InverseMass, cpd.AngularComponentA, normalImpulse);
}
if (bodyB.InverseMass != 0)
{
bodyB.InternalApplyImpulse(contactPoint.NormalWorldOnB * bodyB.InverseMass, cpd.AngularComponentB, -normalImpulse);
}
/*body1.applyImpulse(normal * (normalImpulse), rel_pos1);
body2.applyImpulse(-normal * (normalImpulse), rel_pos2);*/
return normalImpulse;
}
public static float ResolveSingleFriction(RigidBody bodyA, RigidBody bodyB,
ManifoldPoint contactPoint, ContactSolverInfo solverInfo)
{
Vector3 pos1 = contactPoint.PositionWorldOnA;
Vector3 pos2 = contactPoint.PositionWorldOnB;
Vector3 rel_pos1 = pos1 - bodyA.CenterOfMassPosition;
Vector3 rel_pos2 = pos2 - bodyB.CenterOfMassPosition;
ConstraintPersistentData cpd = contactPoint.UserPersistentData as ConstraintPersistentData;
if (cpd == null)
throw new BulletException();
float combinedFriction = cpd.Friction;
float limit = cpd.AppliedImpulse * combinedFriction;
//friction
if (cpd.AppliedImpulse > 0)
{
//apply friction in the 2 tangential directions
// 1st tangent
Vector3 vel1 = bodyA.GetVelocityInLocalPoint(rel_pos1);
Vector3 vel2 = bodyB.GetVelocityInLocalPoint(rel_pos2);
Vector3 vel = vel1 - vel2;
float j1, j2;
{
float vrel = Vector3.Dot(cpd.FrictionWorldTangentialA, vel);
// calculate j that moves us to zero relative velocity
j1 = -vrel * cpd.JacDiagABInvTangentA;
float oldTangentImpulse = cpd.AccumulatedTangentImpulseA;
cpd.AccumulatedTangentImpulseA = oldTangentImpulse + j1;
float atia = cpd.AccumulatedTangentImpulseA;
MathHelper.SetMin(ref atia, limit);
MathHelper.SetMax(ref atia, -limit);
cpd.AccumulatedTangentImpulseA = atia;
j1 = cpd.AccumulatedTangentImpulseA - oldTangentImpulse;
}
{
// 2nd tangent
float vrel = Vector3.Dot(cpd.FrictionWorldTangentialB, vel);
// calculate j that moves us to zero relative velocity
j2 = -vrel * cpd.JacDiagABInvTangentB;
float oldTangentImpulse = cpd.AccumulatedTangentImpulseB;
cpd.AccumulatedTangentImpulseB = oldTangentImpulse + j2;
float atib = cpd.AccumulatedTangentImpulseB;
MathHelper.SetMin(ref atib, limit);
MathHelper.SetMax(ref atib, -limit);
cpd.AccumulatedTangentImpulseB = atib;
j2 = cpd.AccumulatedTangentImpulseB - oldTangentImpulse;
}
if (bodyA.InverseMass != 0)
{
bodyA.InternalApplyImpulse(cpd.FrictionWorldTangentialA * bodyA.InverseMass, cpd.FrictionAngularComponent0A, j1);
bodyA.InternalApplyImpulse(cpd.FrictionWorldTangentialB * bodyA.InverseMass, cpd.FrictionAngularComponent1A, j2);
}
if (bodyB.InverseMass != 0)
{
bodyB.InternalApplyImpulse(cpd.FrictionWorldTangentialA * bodyB.InverseMass, cpd.FrictionAngularComponent0B, -j1);
bodyB.InternalApplyImpulse(cpd.FrictionWorldTangentialB * bodyB.InverseMass, cpd.FrictionAngularComponent1B, -j2);
}
}
return cpd.AppliedImpulse;
}
public static float ResolveSingleFrictionOriginal(
RigidBody bodyA,
RigidBody bodyB,
ManifoldPoint contactPoint,
ContactSolverInfo solverInfo)
{
Vector3 posA = contactPoint.PositionWorldOnA;
Vector3 posB = contactPoint.PositionWorldOnB;
Vector3 relPosA = posA - bodyA.CenterOfMassPosition;
Vector3 relPosB = posB - bodyB.CenterOfMassPosition;
ConstraintPersistentData cpd = contactPoint.UserPersistentData as ConstraintPersistentData;
if (cpd == null)
throw new BulletException();
float combinedFriction = cpd.Friction;
float limit = cpd.AppliedImpulse * combinedFriction;
//if (contactPoint.m_appliedImpulse>0.f)
//friction
{
//apply friction in the 2 tangential directions
{
// 1st tangent
Vector3 velA = bodyA.GetVelocityInLocalPoint(relPosA);
Vector3 velB = bodyB.GetVelocityInLocalPoint(relPosB);
Vector3 vel = velA - velB;
float vrel = Vector3.Dot(cpd.FrictionWorldTangentialA, vel);
// calculate j that moves us to zero relative velocity
float j = -vrel * cpd.JacDiagABInvTangentA;
float total = cpd.AccumulatedTangentImpulseA + j;
if (limit < total)
total = limit;
if (total < -limit)
total = -limit;
j = total - cpd.AccumulatedTangentImpulseA;
cpd.AccumulatedTangentImpulseA = total;
bodyA.ApplyImpulse(j * cpd.FrictionWorldTangentialA, relPosA);
bodyB.ApplyImpulse(j * -cpd.FrictionWorldTangentialA, relPosB);
}
{
// 2nd tangent
Vector3 velA = bodyA.GetVelocityInLocalPoint(relPosA);
Vector3 velB = bodyB.GetVelocityInLocalPoint(relPosB);
Vector3 vel = velA - velB;
float vrel = Vector3.Dot(cpd.FrictionWorldTangentialB, vel);
// calculate j that moves us to zero relative velocity
float j = -vrel * cpd.JacDiagABInvTangentB;
float total = cpd.AccumulatedTangentImpulseB + j;
if (limit < total)
total = limit;
if (total < -limit)
total = -limit;
j = total - cpd.AccumulatedTangentImpulseB;
cpd.AccumulatedTangentImpulseB = total;
bodyA.ApplyImpulse(j * cpd.FrictionWorldTangentialB, relPosA);
bodyB.ApplyImpulse(j * -cpd.FrictionWorldTangentialB, relPosB);
}
}
return cpd.AppliedImpulse;
}
//velocity + friction
//response between two dynamic objects with friction
public static float ResolveSingleCollisionCombined(
RigidBody bodyA,
RigidBody bodyB,
ManifoldPoint contactPoint,
ContactSolverInfo solverInfo)
{
Vector3 posA = contactPoint.PositionWorldOnA;
Vector3 posB = contactPoint.PositionWorldOnB;
Vector3 normal = contactPoint.NormalWorldOnB;
Vector3 relPosA = posA - bodyA.CenterOfMassPosition;
Vector3 relPosB = posB - bodyB.CenterOfMassPosition;
Vector3 velA = bodyA.GetVelocityInLocalPoint(relPosA);
Vector3 velB = bodyB.GetVelocityInLocalPoint(relPosB);
Vector3 vel = velA - velB;
float relVel;
relVel = Vector3.Dot(normal, vel);
float Kfps = 1f / solverInfo.TimeStep;
//float damping = solverInfo.m_damping;
float Kerp = solverInfo.Erp;
float Kcor = Kerp * Kfps;
ConstraintPersistentData cpd = contactPoint.UserPersistentData as ConstraintPersistentData;
if (cpd == null)
throw new BulletException();
float distance = cpd.Penetration;
float positionalError = Kcor * -distance;
float velocityError = cpd.Restitution - relVel;// * damping;
float penetrationImpulse = positionalError * cpd.JacDiagABInv;
float velocityImpulse = velocityError * cpd.JacDiagABInv;
float normalImpulse = penetrationImpulse + velocityImpulse;
// See Erin Catto's GDC 2006 paper: Clamp the accumulated impulse
float oldNormalImpulse = cpd.AppliedImpulse;
float sum = oldNormalImpulse + normalImpulse;
cpd.AppliedImpulse = 0 > sum ? 0 : sum;
normalImpulse = cpd.AppliedImpulse - oldNormalImpulse;
if (bodyA.InverseMass != 0)
{
bodyA.InternalApplyImpulse(contactPoint.NormalWorldOnB * bodyA.InverseMass, cpd.AngularComponentA, normalImpulse);
}
if (bodyB.InverseMass != 0)
{
bodyB.InternalApplyImpulse(contactPoint.NormalWorldOnB * bodyB.InverseMass, cpd.AngularComponentB, -normalImpulse);
}
{
//friction
Vector3 vel12 = bodyA.GetVelocityInLocalPoint(relPosA);
Vector3 vel22 = bodyB.GetVelocityInLocalPoint(relPosB);
Vector3 vel3 = vel12 - vel22;
relVel = Vector3.Dot(normal, vel3);
Vector3 latVel = vel3 - normal * relVel;
float lat_rel_vel = latVel.Length();
float combinedFriction = cpd.Friction;
if (cpd.AppliedImpulse > 0)
if (lat_rel_vel > float.Epsilon)
{
latVel /= lat_rel_vel;
Vector3 temp1 = Vector3.TransformNormal(Vector3.Cross(relPosA, latVel), bodyA.InvInertiaTensorWorld);
Vector3 temp2 = Vector3.TransformNormal(Vector3.Cross(relPosB, latVel), bodyB.InvInertiaTensorWorld);
float friction_impulse = lat_rel_vel /
(bodyA.InverseMass + bodyB.InverseMass + Vector3.Dot(latVel, Vector3.Cross(temp1, relPosA) + Vector3.Cross(temp2, relPosB)));
float normal_impulse = cpd.AppliedImpulse * combinedFriction;
MathHelper.SetMin(ref friction_impulse, normal_impulse);
MathHelper.SetMin(ref friction_impulse, -normal_impulse);
bodyA.ApplyImpulse(latVel * -friction_impulse, relPosA);
bodyB.ApplyImpulse(latVel * friction_impulse, relPosB);
}
}
return normalImpulse;
}
public static float ResolveSingleFrictionEmpty(
RigidBody bodyA,
RigidBody bodyB,
ManifoldPoint contactPoint,
ContactSolverInfo solverInfo)
{
return 0;
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
public sealed partial class DriveInfo
{
private static string NormalizeDriveName(string driveName)
{
Debug.Assert(driveName != null);
string name;
if (driveName.Length == 1)
name = driveName + ":\\";
else
{
// GetPathRoot does not check all invalid characters
if (PathInternal.HasIllegalCharacters(driveName))
throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), nameof(driveName));
name = Path.GetPathRoot(driveName);
// Disallow null or empty drive letters and UNC paths
if (name == null || name.Length == 0 || name.StartsWith("\\\\", StringComparison.Ordinal))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
}
// We want to normalize to have a trailing backslash so we don't have two equivalent forms and
// because some Win32 API don't work without it.
if (name.Length == 2 && name[1] == ':')
{
name = name + "\\";
}
// Now verify that the drive letter could be a real drive name.
// On Windows this means it's between A and Z, ignoring case.
char letter = driveName[0];
if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z')))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
return name;
}
public DriveType DriveType
{
[System.Security.SecuritySafeCritical]
get
{
// GetDriveType can't fail
return (DriveType)Interop.Kernel32.GetDriveType(Name);
}
}
public String DriveFormat
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.Kernel32.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
throw Error.GetExceptionForLastWin32DriveError(Name);
}
}
finally
{
Interop.Kernel32.SetErrorMode(oldMode);
}
return fileSystemName.ToString();
}
}
public long AvailableFreeSpace
{
[System.Security.SecuritySafeCritical]
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.Kernel32.SetErrorMode(oldMode);
}
return userBytes;
}
}
public long TotalFreeSpace
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.Kernel32.SetErrorMode(oldMode);
}
return freeBytes;
}
}
public long TotalSize
{
[System.Security.SecuritySafeCritical]
get
{
// Don't cache this, to handle variable sized floppy drives
// or other various removable media drives.
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.Kernel32.SetErrorMode(oldMode);
}
return totalBytes;
}
}
public static DriveInfo[] GetDrives()
{
string[] drives = DriveInfoInternal.GetLogicalDrives();
DriveInfo[] result = new DriveInfo[drives.Length];
for (int i = 0; i < drives.Length; i++)
{
result[i] = new DriveInfo(drives[i]);
}
return result;
}
// Null is a valid volume label.
public String VolumeLabel
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// NTFS uses a limit of 32 characters for the volume label,
// as of Windows Server 2003.
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.Kernel32.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Win9x appears to return ERROR_INVALID_DATA when a
// drive doesn't exist.
if (errorCode == Interop.Errors.ERROR_INVALID_DATA)
errorCode = Interop.Errors.ERROR_INVALID_DRIVE;
throw Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
Interop.Kernel32.SetErrorMode(oldMode);
}
return volumeName.ToString();
}
[System.Security.SecuritySafeCritical] // auto-generated
set
{
uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.Kernel32.SetVolumeLabel(Name, value);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Provide better message
if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException(SR.InvalidOperation_SetVolumeLabelFailed);
throw Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
Interop.Kernel32.SetErrorMode(oldMode);
}
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Helper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
/// <summary>
/// Helper Class for EDM Metadata - this class contains all the helper methods
/// which only accesses public methods/properties. The other partial class contains all
/// helper methods which just uses internal methods/properties. The reason why we
/// did this for allowing view gen to happen at compile time - all the helper
/// methods that view gen or mapping uses are in this class. Rest of the
/// methods are in this class
/// </summary>
internal static partial class Helper
{
#region Fields
internal static readonly EdmMember[] EmptyArrayEdmProperty = new EdmMember[0];
#endregion
#region Methods
/// <summary>
/// The method wraps the GetAttribute method on XPathNavigator.
/// The problem with using the method directly is that the
/// Get Attribute method does not differentiate the absence of an attribute and
/// having an attribute with Empty string value. In both cases the value returned is an empty string.
/// So in case of optional attributes, it becomes hard to distinguish the case whether the
/// xml contains the attribute with empty string or doesn't contain the attribute
/// This method will return null if the attribute is not present and otherwise will return the
/// attribute value.
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName">name of the attribute</param>
/// <returns></returns>
static internal string GetAttributeValue(XPathNavigator nav,
string attributeName)
{
//Clone the navigator so that there wont be any sideeffects on the passed in Navigator
nav = nav.Clone();
string attributeValue = null;
if (nav.MoveToAttribute(attributeName, string.Empty))
{
attributeValue = nav.Value;
}
return attributeValue;
}
/// <summary>
/// The method returns typed attribute value of the specified xml attribute.
/// The method does not do any specific casting but uses the methods on XPathNavigator.
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName"></param>
/// <param name="clrType"></param>
/// <returns></returns>
internal static object GetTypedAttributeValue(XPathNavigator nav,
string attributeName,
Type clrType)
{
//Clone the navigator so that there wont be any sideeffects on the passed in Navigator
nav = nav.Clone();
object attributeValue = null;
if (nav.MoveToAttribute(attributeName, string.Empty))
{
attributeValue = nav.ValueAs(clrType);
}
return attributeValue;
}
/// <summary>
/// Searches for Facet Description with the name specified.
/// </summary>
/// <param name="facetCollection">Collection of facet description</param>
/// <param name="facetName">name of the facet</param>
/// <returns></returns>
internal static FacetDescription GetFacet(IEnumerable<FacetDescription> facetCollection, string facetName)
{
foreach (FacetDescription facetDescription in facetCollection)
{
if (facetDescription.FacetName == facetName)
{
return facetDescription;
}
}
return null;
}
// requires: firstType is not null
// effects: Returns true iff firstType is assignable from secondType
internal static bool IsAssignableFrom(EdmType firstType, EdmType secondType)
{
Debug.Assert(firstType != null, "firstType should not be not null");
if (secondType == null)
{
return false;
}
return firstType.Equals(secondType) || IsSubtypeOf(secondType, firstType);
}
// requires: firstType is not null
// effects: if otherType is among the base types, return true,
// otherwise returns false.
// when othertype is same as the current type, return false.
internal static bool IsSubtypeOf(EdmType firstType, EdmType secondType)
{
Debug.Assert(firstType != null, "firstType should not be not null");
if (secondType == null)
{
return false;
}
// walk up my type hierarchy list
for (EdmType t = firstType.BaseType; t != null; t = t.BaseType)
{
if (t == secondType)
return true;
}
return false;
}
internal static IList GetAllStructuralMembers(EdmType edmType)
{
switch (edmType.BuiltInTypeKind)
{
case BuiltInTypeKind.AssociationType:
return ((AssociationType)edmType).AssociationEndMembers;
case BuiltInTypeKind.ComplexType:
return ((ComplexType)edmType).Properties;
case BuiltInTypeKind.EntityType:
return ((EntityType)edmType).Properties;
case BuiltInTypeKind.RowType:
return ((RowType)edmType).Properties;
default:
return EmptyArrayEdmProperty;
}
}
internal static AssociationEndMember GetEndThatShouldBeMappedToKey(AssociationType associationType)
{
//For 1:* and 1:0..1 associations, the end other than 1 i.e. either * or 0..1 ends need to be
//mapped to key columns
if (associationType.AssociationEndMembers.Any( it =>
it.RelationshipMultiplicity.Equals(RelationshipMultiplicity.One)))
{
{
return associationType.AssociationEndMembers.SingleOrDefault(it =>
((it.RelationshipMultiplicity.Equals(RelationshipMultiplicity.Many))
|| (it.RelationshipMultiplicity.Equals(RelationshipMultiplicity.ZeroOrOne))));
}
}
//For 0..1:* associations, * end must be mapped to key.
else if (associationType.AssociationEndMembers.Any(it =>
(it.RelationshipMultiplicity.Equals(RelationshipMultiplicity.ZeroOrOne))))
{
{
return associationType.AssociationEndMembers.SingleOrDefault(it =>
((it.RelationshipMultiplicity.Equals(RelationshipMultiplicity.Many))));
}
}
return null;
}
/// <summary>
/// Creates a single comma delimited string given a list of strings
/// </summary>
/// <param name="stringList"></param>
/// <returns></returns>
internal static String GetCommaDelimitedString(IEnumerable<string> stringList)
{
Debug.Assert(stringList != null , "Expecting a non null list");
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (string part in stringList)
{
if (!first)
{
sb.Append(", ");
}
else
{
first = false;
}
sb.Append(part);
}
return sb.ToString();
}
// effects: concatenates all given enumerations
internal static IEnumerable<T> Concat<T>(params IEnumerable<T>[] sources)
{
foreach (IEnumerable<T> source in sources)
{
if (null != source)
{
foreach (T element in source)
{
yield return element;
}
}
}
}
internal static void DisposeXmlReaders(IEnumerable<XmlReader> xmlReaders)
{
Debug.Assert(xmlReaders != null);
foreach (XmlReader xmlReader in xmlReaders)
{
((IDisposable)xmlReader).Dispose();
}
}
#region IsXXXType Methods
internal static bool IsStructuralType(EdmType type)
{
return (IsComplexType(type) || IsEntityType(type) || IsRelationshipType(type) || IsRowType(type));
}
internal static bool IsCollectionType(GlobalItem item)
{
return (BuiltInTypeKind.CollectionType == item.BuiltInTypeKind);
}
internal static bool IsEntityType(EdmType type)
{
return (BuiltInTypeKind.EntityType == type.BuiltInTypeKind);
}
internal static bool IsComplexType(EdmType type)
{
return (BuiltInTypeKind.ComplexType == type.BuiltInTypeKind);
}
internal static bool IsPrimitiveType(EdmType type)
{
return (BuiltInTypeKind.PrimitiveType == type.BuiltInTypeKind);
}
internal static bool IsRefType(GlobalItem item)
{
return (BuiltInTypeKind.RefType == item.BuiltInTypeKind);
}
internal static bool IsRowType(GlobalItem item)
{
return (BuiltInTypeKind.RowType == item.BuiltInTypeKind);
}
internal static bool IsAssociationType(EdmType type)
{
return (BuiltInTypeKind.AssociationType == type.BuiltInTypeKind);
}
internal static bool IsRelationshipType(EdmType type)
{
return (BuiltInTypeKind.AssociationType == type.BuiltInTypeKind);
}
internal static bool IsEdmProperty(EdmMember member)
{
return (BuiltInTypeKind.EdmProperty == member.BuiltInTypeKind);
}
internal static bool IsRelationshipEndMember(EdmMember member)
{
return (BuiltInTypeKind.AssociationEndMember == member.BuiltInTypeKind);
}
internal static bool IsAssociationEndMember(EdmMember member)
{
return (BuiltInTypeKind.AssociationEndMember == member.BuiltInTypeKind);
}
internal static bool IsNavigationProperty(EdmMember member)
{
return (BuiltInTypeKind.NavigationProperty == member.BuiltInTypeKind);
}
internal static bool IsEntityTypeBase(EdmType edmType)
{
return Helper.IsEntityType(edmType) ||
Helper.IsRelationshipType(edmType);
}
internal static bool IsTransientType(EdmType edmType)
{
return Helper.IsCollectionType(edmType) ||
Helper.IsRefType(edmType) ||
Helper.IsRowType(edmType);
}
internal static bool IsEntitySet(EntitySetBase entitySetBase)
{
return BuiltInTypeKind.EntitySet == entitySetBase.BuiltInTypeKind;
}
internal static bool IsRelationshipSet(EntitySetBase entitySetBase)
{
return BuiltInTypeKind.AssociationSet == entitySetBase.BuiltInTypeKind;
}
internal static bool IsEntityContainer(GlobalItem item)
{
return BuiltInTypeKind.EntityContainer == item.BuiltInTypeKind;
}
internal static bool IsEdmFunction(GlobalItem item)
{
return BuiltInTypeKind.EdmFunction == item.BuiltInTypeKind;
}
internal static string GetFileNameFromUri(Uri uri)
{
if ( uri == null )
throw new ArgumentNullException("uri");
if ( uri.IsFile )
return uri.LocalPath;
if ( uri.IsAbsoluteUri )
return uri.AbsolutePath;
throw new ArgumentException(System.Data.Entity.Strings.UnacceptableUri(uri),"uri");
}
internal static bool IsEnumType(EdmType edmType)
{
Debug.Assert(edmType != null, "edmType != null");
return BuiltInTypeKind.EnumType == edmType.BuiltInTypeKind;
}
internal static bool IsUnboundedFacetValue(Facet facet)
{
return object.ReferenceEquals(facet.Value, EdmConstants.UnboundedValue);
}
internal static bool IsVariableFacetValue(Facet facet)
{
return object.ReferenceEquals(facet.Value, EdmConstants.VariableValue);
}
internal static bool IsScalarType(EdmType edmType)
{
return IsEnumType(edmType) || IsPrimitiveType(edmType);
}
internal static bool IsSpatialType(PrimitiveType type)
{
return IsGeographicType(type) || IsGeometricType(type);
}
internal static bool IsSpatialType(EdmType type, out bool isGeographic)
{
PrimitiveType pt = type as PrimitiveType;
if (pt == null)
{
isGeographic = false;
return false;
}
else
{
isGeographic = IsGeographicType(pt);
return isGeographic || IsGeometricType(pt);
}
}
internal static bool IsGeographicType(PrimitiveType type)
{
return IsGeographicTypeKind(type.PrimitiveTypeKind);
}
internal static bool AreSameSpatialUnionType(PrimitiveType firstType, PrimitiveType secondType)
{
// for the purposes of type checking all geographic types should be treated as if they were the Geography union type.
if (Helper.IsGeographicTypeKind(firstType.PrimitiveTypeKind) && Helper.IsGeographicTypeKind(secondType.PrimitiveTypeKind))
{
return true;
}
// for the purposes of type checking all geometric types should be treated as if they were the Geometry union type.
if (Helper.IsGeometricTypeKind(firstType.PrimitiveTypeKind) && Helper.IsGeometricTypeKind(secondType.PrimitiveTypeKind))
{
return true;
}
return false;
}
internal static bool IsGeographicTypeKind(PrimitiveTypeKind kind)
{
return kind == PrimitiveTypeKind.Geography || IsStrongGeographicTypeKind(kind);
}
internal static bool IsGeometricType(PrimitiveType type)
{
return IsGeometricTypeKind(type.PrimitiveTypeKind);
}
internal static bool IsGeometricTypeKind(PrimitiveTypeKind kind)
{
return kind == PrimitiveTypeKind.Geometry || IsStrongGeometricTypeKind(kind);
}
internal static bool IsStrongSpatialTypeKind(PrimitiveTypeKind kind)
{
return IsStrongGeometricTypeKind(kind) || IsStrongGeographicTypeKind(kind);
}
static bool IsStrongGeometricTypeKind(PrimitiveTypeKind kind)
{
return kind >= PrimitiveTypeKind.GeometryPoint && kind <= PrimitiveTypeKind.GeometryCollection;
}
static bool IsStrongGeographicTypeKind(PrimitiveTypeKind kind)
{
return kind >= PrimitiveTypeKind.GeographyPoint && kind <= PrimitiveTypeKind.GeographyCollection;
}
internal static bool IsSpatialType(TypeUsage type)
{
return (type.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType && IsSpatialType((PrimitiveType)type.EdmType));
}
internal static bool IsSpatialType(TypeUsage type, out PrimitiveTypeKind spatialType)
{
if (type.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
{
PrimitiveType primitiveType = (PrimitiveType)type.EdmType;
if (IsGeographicTypeKind(primitiveType.PrimitiveTypeKind) || IsGeometricTypeKind(primitiveType.PrimitiveTypeKind))
{
spatialType = primitiveType.PrimitiveTypeKind;
return true;
}
}
spatialType = default(PrimitiveTypeKind);
return false;
}
#endregion /// IsXXXType region
/// <remarks>Performance of Enum.ToString() is slow and we use this value in building Identity</remarks>
internal static string ToString(System.Data.ParameterDirection value)
{
switch (value)
{
case ParameterDirection.Input:
return "Input";
case ParameterDirection.Output:
return "Output";
case ParameterDirection.InputOutput:
return "InputOutput";
case ParameterDirection.ReturnValue:
return "ReturnValue";
default:
Debug.Assert(false, "which ParameterDirection.ToString() is missing?");
return value.ToString();
}
}
/// <remarks>Performance of Enum.ToString() is slow and we use this value in building Identity</remarks>
internal static string ToString(System.Data.Metadata.Edm.ParameterMode value)
{
switch (value)
{
case ParameterMode.In:
return EdmConstants.In;
case ParameterMode.Out:
return EdmConstants.Out;
case ParameterMode.InOut:
return EdmConstants.InOut;
case ParameterMode.ReturnValue:
return "ReturnValue";
default:
Debug.Assert(false, "which ParameterMode.ToString() is missing?");
return value.ToString();
}
}
/// <summary>
/// Verifies whether the given <paramref name="typeKind"/> is a valid underlying type for an enumeration type.
/// </summary>
/// <param name="typeKind">
/// <see cref="PrimitiveTypeKind"/> to verifiy.
/// </param>
/// <returns>
/// <c>true</c> if the <paramref name="typeKind"/> is a valid underlying type for an enumeration type. Otherwise <c>false</c>.
/// </returns>
internal static bool IsSupportedEnumUnderlyingType(PrimitiveTypeKind typeKind)
{
return typeKind == PrimitiveTypeKind.Byte ||
typeKind == PrimitiveTypeKind.SByte ||
typeKind == PrimitiveTypeKind.Int16 ||
typeKind == PrimitiveTypeKind.Int32 ||
typeKind == PrimitiveTypeKind.Int64;
}
private static readonly Dictionary<PrimitiveTypeKind, long[]> _enumUnderlyingTypeRanges =
new Dictionary<PrimitiveTypeKind, long[]>
{
{ PrimitiveTypeKind.Byte, new long[] { Byte.MinValue, Byte.MaxValue } },
{ PrimitiveTypeKind.SByte, new long[] { SByte.MinValue, SByte.MaxValue } },
{ PrimitiveTypeKind.Int16, new long[] { Int16.MinValue, Int16.MaxValue } },
{ PrimitiveTypeKind.Int32, new long[] { Int32.MinValue, Int32.MaxValue } },
{ PrimitiveTypeKind.Int64, new long[] { Int64.MinValue, Int64.MaxValue } },
};
/// <summary>
/// Verifies whether a value of a member of an enumeration type is in range according to underlying type of the enumeration type.
/// </summary>
/// <param name="underlyingTypeKind">Underlying type of the enumeration type.</param>
/// <param name="value">Value to check.</param>
/// <returns>
/// <c>true</c> if the <paramref name="value"/> is in range of the <paramref name="underlyingTypeKind"/>. <c>false</c> otherwise.
/// </returns>
internal static bool IsEnumMemberValueInRange(PrimitiveTypeKind underlyingTypeKind, long value)
{
Debug.Assert(IsSupportedEnumUnderlyingType(underlyingTypeKind), "Unsupported underlying type.");
return value >= _enumUnderlyingTypeRanges[underlyingTypeKind][0] && value <= _enumUnderlyingTypeRanges[underlyingTypeKind][1];
}
/// <summary>
/// Checks whether the <paramref name="type"/> is enum type and if this is the case returns its underlying type. Otherwise
/// returns <paramref name="type"/> after casting it to PrimitiveType.
/// </summary>
/// <param name="type">Type to convert to primitive type.</param>
/// <returns>Underlying type if <paramref name="type"/> is enumeration type. Otherwise <paramref name="type"/> itself.</returns>
/// <remarks>This method should be called only for primitive or enumeration types.</remarks>
internal static PrimitiveType AsPrimitive(EdmType type)
{
Debug.Assert(type != null, "type != null");
Debug.Assert(IsScalarType(type), "This method must not be called for types that are neither primitive nor enums.");
return Helper.IsEnumType(type) ?
GetUnderlyingEdmTypeForEnumType(type) :
(PrimitiveType)type;
}
/// <summary>
/// Returns underlying EDM type of a given enum <paramref name="type"/>.
/// </summary>
/// <param name="type">Enum type whose underlying EDM type needs to be returned. Must not be null.</param>
/// <returns>The underlying EDM type of a given enum <paramref name="type"/>.</returns>
internal static PrimitiveType GetUnderlyingEdmTypeForEnumType(EdmType type)
{
Debug.Assert(type != null, "type != null");
Debug.Assert(IsEnumType(type), "This method can be called only for enums.");
return ((EnumType)type).UnderlyingType;
}
internal static PrimitiveType GetSpatialNormalizedPrimitiveType(EdmType type)
{
Debug.Assert(type != null, "type != null");
Debug.Assert(IsPrimitiveType(type), "This method can be called only for enums.");
PrimitiveType primitiveType = (PrimitiveType)type;
if (IsGeographicType(primitiveType) && primitiveType.PrimitiveTypeKind != PrimitiveTypeKind.Geography)
{
return PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Geography);
}
else if (IsGeometricType(primitiveType) && primitiveType.PrimitiveTypeKind != PrimitiveTypeKind.Geometry)
{
return PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Geometry);
}
else
{
return primitiveType;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
*
*/
/// <summary>
/// Stream over a memory pointer or over a SafeBuffer
/// </summary>
public class UnmanagedMemoryStream : Stream
{
private SafeBuffer _buffer;
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
private bool _isOpen;
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
/// <summary>
/// Creates a closed stream.
/// </summary>
// Needed for subclasses that need to map a file, etc.
protected UnmanagedMemoryStream()
{
unsafe
{
_mem = null;
}
_isOpen = false;
}
/// <summary>
/// Creates a stream over a SafeBuffer.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
{
Initialize(buffer, offset, length, FileAccess.Read);
}
/// <summary>
/// Creates a stream over a SafeBuffer.
/// </summary>
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
{
Initialize(buffer, offset, length, access);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="access"></param>
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.ByteLength < (ulong)(offset + length))
{
throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen);
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
if (_isOpen)
{
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
// check for wraparound
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
buffer.AcquirePointer(ref pointer);
if ((pointer + offset + length) < pointer)
{
throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
/// <summary>
/// Creates a stream over a byte*.
/// </summary>
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read);
}
/// <summary>
/// Creates a stream over a byte*.
/// </summary>
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (length > capacity)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*)((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
if (_isOpen)
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
/// <summary>
/// Returns true if the stream can be read; otherwise returns false.
/// </summary>
public override bool CanRead
{
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
/// <summary>
/// Returns true if the stream can seek; otherwise returns false.
/// </summary>
public override bool CanSeek
{
[Pure]
get { return _isOpen; }
}
/// <summary>
/// Returns true if the stream can be written to; otherwise returns false.
/// </summary>
public override bool CanWrite
{
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
/// <summary>
/// Closes the stream. The stream's memory needs to be dealt with separately.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
/// <summary>
/// Since it's a memory stream, this method does nothing.
/// </summary>
public override void Flush()
{
if (!_isOpen) throw Error.GetStreamIsClosed();
}
/// <summary>
/// Since it's a memory stream, this method does nothing specific.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
/// <summary>
/// Number of bytes in the stream.
/// </summary>
public override long Length
{
get
{
if (!_isOpen) throw Error.GetStreamIsClosed();
return Interlocked.Read(ref _length);
}
}
/// <summary>
/// Number of bytes that can be written to the stream.
/// </summary>
public long Capacity
{
get
{
if (!_isOpen) throw Error.GetStreamIsClosed();
return _capacity;
}
}
/// <summary>
/// ReadByte will read byte at the Position in the stream
/// </summary>
public override long Position
{
get
{
if (!CanSeek) throw Error.GetStreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
set
{
if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!CanSeek) throw Error.GetStreamIsClosed();
Contract.EndContractBlock();
Interlocked.Exchange(ref _position, value);
}
}
/// <summary>
/// Pointer to memory at the current Position in the stream.
/// </summary>
[CLSCompliant(false)]
public unsafe byte* PositionPointer
{
get
{
if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition);
byte* ptr = _mem + pos;
return ptr;
}
set
{
if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
if (value < _mem)
throw new IOException(SR.IO_SeekBeforeBegin);
long newPosition = (long)value - (long)_mem;
if (newPosition < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
Interlocked.Exchange(ref _position, newPosition);
}
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="buffer">Buffer to read the bytes to.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
/// <returns>Number of bytes actually read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return ReadCore(new Span<byte>(buffer, offset, count));
}
public override int Read(Span<byte> destination)
{
if (GetType() == typeof(UnmanagedMemoryStream))
{
return ReadCore(destination);
}
else
{
// UnmanagedMemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(destination);
}
}
internal int ReadCore(Span<byte> destination)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = Math.Min(len - pos, destination.Length);
if (n <= 0)
{
return 0;
}
int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
{
return 0; // _position could be beyond EOF
}
Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
fixed (byte* pBuffer = &destination.DangerousGetPinnableReference())
{
if (_buffer != null)
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pBuffer, pointer + pos + _offset, nInt);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memcpy(pBuffer, _mem + pos, nInt);
}
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="buffer">Buffer to read the bytes to.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
/// <param name="cancellationToken">Token that can be used to cancel this operation.</param>
/// <returns>Task that can be used to access the number of bytes actually read.</returns>
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<Int32>(cancellationToken);
try
{
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="destination">Buffer to read the bytes to.</param>
/// <param name="cancellationToken">Token that can be used to cancel this operation.</param>
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
try
{
return new ValueTask<int>(Read(destination.Span));
}
catch (Exception ex)
{
return new ValueTask<int>(Task.FromException<int>(ex));
}
}
/// <summary>
/// Returns the byte at the stream current Position and advances the Position.
/// </summary>
/// <returns></returns>
public override int ReadByte()
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
result = _mem[pos];
}
}
return result;
}
/// <summary>
/// Advanced the Position to specific location in the stream.
/// </summary>
/// <param name="offset">Offset from the loc parameter.</param>
/// <param name="loc">Origin for the offset parameter.</param>
/// <returns></returns>
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
switch (loc)
{
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
long finalPos = Interlocked.Read(ref _position);
Debug.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
/// <summary>
/// Sets the Length of the stream.
/// </summary>
/// <param name="value"></param>
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
if (value > _capacity)
throw new IOException(SR.IO_FixedCapacity);
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, value - len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value)
{
Interlocked.Exchange(ref _position, value);
}
}
/// <summary>
/// Writes buffer into the stream
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
WriteCore(new Span<byte>(buffer, offset, count));
}
public override void Write(ReadOnlySpan<byte> source)
{
if (GetType() == typeof(UnmanagedMemoryStream))
{
WriteCore(source);
}
else
{
// UnmanagedMemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(source);
}
}
internal unsafe void WriteCore(ReadOnlySpan<byte> source)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + source.Length;
// Check for overflow
if (n < 0)
{
throw new IOException(SR.IO_StreamTooLong);
}
if (n > _capacity)
{
throw new NotSupportedException(SR.IO_FixedCapacity);
}
if (_buffer == null)
{
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len)
{
Buffer.ZeroMemory(_mem + len, pos - len);
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len)
{
Interlocked.Exchange(ref _length, n);
}
}
fixed (byte* pBuffer = &source.DangerousGetPinnableReference())
{
if (_buffer != null)
{
long bytesLeft = _capacity - pos;
if (bytesLeft < source.Length)
{
throw new ArgumentException(SR.Arg_BufferTooSmall);
}
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pointer + pos + _offset, pBuffer, source.Length);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memcpy(_mem + pos, pBuffer, source.Length);
}
}
Interlocked.Exchange(ref _position, n);
return;
}
/// <summary>
/// Writes buffer into the stream. The operation completes synchronously.
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Number of bytes to write.</param>
/// <param name="cancellationToken">Token that can be used to cancel the operation.</param>
/// <returns>Task that can be awaited </returns>
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException(ex);
}
}
/// <summary>
/// Writes buffer into the stream. The operation completes synchronously.
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="cancellationToken">Token that can be used to cancel the operation.</param>
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
try
{
Write(source.Span);
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
/// <summary>
/// Writes a byte to the stream and advances the current Position.
/// </summary>
/// <param name="value"></param>
public override void WriteByte(byte value)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len)
{
// Check for overflow
if (n < 0)
throw new IOException(SR.IO_StreamTooLong);
if (n > _capacity)
throw new NotSupportedException(SR.IO_FixedCapacity);
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null)
{
if (pos > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, 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.Net.Test.Common;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class DnsEndPointTest : DualModeBase
{
private void OnConnectAsyncCompleted(object sender, SocketAsyncEventArgs args)
{
ManualResetEvent complete = (ManualResetEvent)args.UserToken;
complete.Set();
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_ConnectDnsEndPoint_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new DnsEndPoint("localhost", port));
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_ConnectDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.LingerState = new LingerOption(false, 0);
sock.NoDelay = true;
sock.ReceiveBufferSize = 1024;
sock.ReceiveTimeout = 100;
sock.SendBufferSize = 1024;
sock.SendTimeout = 100;
sock.Connect(new DnsEndPoint("localhost", port));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_ConnectDnsEndPoint_Failure()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketException ex = Assert.ThrowsAny<SocketException>(() =>
{
sock.Connect(new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort));
});
SocketError errorCode = ex.SocketErrorCode;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
$"SocketErrorCode: {errorCode}");
ex = Assert.ThrowsAny<SocketException>(() =>
{
sock.Connect(new DnsEndPoint("localhost", UnusedPort));
});
Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_SendToDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
AssertExtensions.Throws<ArgumentException>("remoteEP", () =>
{
sock.SendTo(new byte[10], new DnsEndPoint("localhost", UnusedPort));
});
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_ReceiveFromDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
int port = sock.BindToAnonymousPort(IPAddress.Loopback);
EndPoint endpoint = new DnsEndPoint("localhost", port);
AssertExtensions.Throws<ArgumentException>("remoteEP", () =>
{
sock.ReceiveFrom(new byte[10], ref endpoint);
});
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_BeginConnectDnsEndPoint_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null);
sock.EndConnect(result);
Assert.Throws<InvalidOperationException>(() => sock.EndConnect(result)); // validate can't call end twice
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_BeginConnectDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.LingerState = new LingerOption(false, 0);
sock.NoDelay = true;
sock.ReceiveBufferSize = 1024;
sock.ReceiveTimeout = 100;
sock.SendBufferSize = 1024;
sock.SendTimeout = 100;
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null);
sock.EndConnect(result);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_BeginConnectDnsEndPoint_Failure()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketException ex = Assert.ThrowsAny<SocketException>(() =>
{
IAsyncResult result = sock.BeginConnect(new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort), null, null);
sock.EndConnect(result);
});
SocketError errorCode = ex.SocketErrorCode;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
"SocketErrorCode: {0}" + errorCode);
ex = Assert.ThrowsAny<SocketException>(() =>
{
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", UnusedPort), null, null);
sock.EndConnect(result);
});
Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_BeginSendToDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
AssertExtensions.Throws<ArgumentException>("remoteEP", () =>
{
sock.BeginSendTo(new byte[10], 0, 0, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null);
});
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_Success(SocketImplementationType type)
{
Assert.True(Capability.IPv4Support());
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", port);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type)
{
Assert.True(Capability.IPv4Support());
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.LingerState = new LingerOption(false, 0);
sock.NoDelay = true;
sock.ReceiveBufferSize = 1024;
sock.ReceiveTimeout = 100;
sock.SendBufferSize = 1024;
sock.SendTimeout = 100;
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", port);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_HostNotFound()
{
Assert.True(Capability.IPv4Support());
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort);
args.Completed += OnConnectAsyncCompleted;
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
}
AssertHostNotFoundOrNoData(args);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_ConnectionRefused()
{
Assert.True(Capability.IPv4Support());
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort);
args.Completed += OnConnectAsyncCompleted;
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
}
Assert.Equal(SocketError.ConnectionRefused, args.SocketError);
Assert.True(args.ConnectByNameError is SocketException);
Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(LocalhostIsBothIPv4AndIPv6))]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public void Socket_StaticConnectAsync_Success(SocketImplementationType type)
{
Assert.True(Capability.IPv4Support() && Capability.IPv6Support());
int port4, port6;
using (SocketTestServer server4 = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port4))
using (SocketTestServer server6 = SocketTestServer.SocketTestServerFactory(type, IPAddress.IPv6Loopback, out port6))
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", port4);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
Assert.NotNull(args.ConnectSocket);
Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetwork);
Assert.True(args.ConnectSocket.Connected);
args.ConnectSocket.Dispose();
args.RemoteEndPoint = new DnsEndPoint("localhost", port6);
complete.Reset();
Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
Assert.NotNull(args.ConnectSocket);
Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetworkV6);
Assert.True(args.ConnectSocket.Connected);
args.ConnectSocket.Dispose();
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_StaticConnectAsync_HostNotFound()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);
if (!willRaiseEvent)
{
OnConnectAsyncCompleted(null, args);
}
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
AssertHostNotFoundOrNoData(args);
Assert.Null(args.ConnectSocket);
complete.Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_StaticConnectAsync_ConnectionRefused()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);
if (!willRaiseEvent)
{
OnConnectAsyncCompleted(null, args);
}
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
complete.Dispose(); // only dispose on success as we know we're done with the instance
Assert.Equal(SocketError.ConnectionRefused, args.SocketError);
Assert.True(args.ConnectByNameError is SocketException);
Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode);
Assert.Null(args.ConnectSocket);
complete.Dispose();
}
private static void CallbackThatShouldNotBeCalled(object sender, SocketAsyncEventArgs args)
{
throw new ShouldNotBeInvokedException();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv6", "true")]
public void Socket_StaticConnectAsync_SyncFailure()
{
Assert.True(Capability.IPv6Support()); // IPv6 required because we use AF.InterNetworkV6
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("127.0.0.1", UnusedPort, AddressFamily.InterNetworkV6);
args.Completed += CallbackThatShouldNotBeCalled;
Assert.False(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
Assert.Equal(SocketError.NoData, args.SocketError);
Assert.Null(args.ConnectSocket);
}
private static void AssertHostNotFoundOrNoData(SocketAsyncEventArgs args)
{
SocketError errorCode = args.SocketError;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
"SocketError: " + errorCode);
Assert.True(args.ConnectByNameError is SocketException);
errorCode = ((SocketException)args.ConnectByNameError).SocketErrorCode;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
"SocketError: " + errorCode);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D05Level111Child (editable child object).<br/>
/// This is a generated base class of <see cref="D05Level111Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D04Level11"/> collection.
/// </remarks>
[Serializable]
public partial class D05Level111Child : BusinessBase<D05Level111Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1 Child Name.</value>
public string Level_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D05Level111Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D05Level111Child"/> object.</returns>
internal static D05Level111Child NewD05Level111Child()
{
return DataPortal.CreateChild<D05Level111Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="D05Level111Child"/> object, based on given parameters.
/// </summary>
/// <param name="cMarentID1">The CMarentID1 parameter of the D05Level111Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="D05Level111Child"/> object.</returns>
internal static D05Level111Child GetD05Level111Child(int cMarentID1)
{
return DataPortal.FetchChild<D05Level111Child>(cMarentID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D05Level111Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private D05Level111Child()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D05Level111Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D05Level111Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cMarentID1">The CMarent ID1.</param>
protected void Child_Fetch(int cMarentID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CMarentID1", cMarentID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cMarentID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="D05Level111Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D05Level111Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D05Level111Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="D05Level111Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteD05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.FTP.Server
{
#region usings
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
#endregion
#region Event delegates
/// <summary>
/// Represents the method that will handle the AuthUser event for FTP_Server.
/// </summary>
/// <param name="sender">The source of the event. </param>
/// <param name="e">A AuthUser_EventArgs that contains the event data.</param>
public delegate void AuthUserEventHandler(object sender, AuthUser_EventArgs e);
/// <summary>
/// Represents the method that will handle the filsystem rerlated events for FTP_Server.
/// </summary>
public delegate void FileSysEntryEventHandler(object sender, FileSysEntry_EventArgs e);
#endregion
/// <summary>
/// FTP Server component.
/// </summary>
public class FTP_Server : SocketServer
{
#region Events
/// <summary>
/// Occurs when connected user tryes to authenticate.
/// </summary>
public event AuthUserEventHandler AuthUser = null;
/// <summary>
/// Occurs when server needs needs to create directory.
/// </summary>
public event FileSysEntryEventHandler CreateDir = null;
/// <summary>
/// Occurs when server needs needs to delete directory.
/// </summary>
public event FileSysEntryEventHandler DeleteDir = null;
/// <summary>
/// Occurs when server needs needs to delete file.
/// </summary>
public event FileSysEntryEventHandler DeleteFile = null;
/// <summary>
/// Occurs when server needs to validatee directory.
/// </summary>
public event FileSysEntryEventHandler DirExists = null;
/// <summary>
/// Occurs when server needs needs validate file.
/// </summary>
public event FileSysEntryEventHandler FileExists = null;
/// <summary>
/// Occurs when server needs directory info (directories,files in deirectory).
/// </summary>
public event FileSysEntryEventHandler GetDirInfo = null;
/// <summary>
/// Occurs when server needs needs to get file.
/// </summary>
public event FileSysEntryEventHandler GetFile = null;
/// <summary>
/// Occurs when server needs needs to rname directory or file.
/// </summary>
public event FileSysEntryEventHandler RenameDirFile = null;
/// <summary>
/// Occurs when POP3 session has finished and session log is available.
/// </summary>
public event LogEventHandler SessionLog = null;
/// <summary>
/// Occurs when server needs needs to store file.
/// </summary>
public event FileSysEntryEventHandler StoreFile = null;
/// <summary>
/// Occurs when new computer connected to FTP server.
/// </summary>
public event ValidateIPHandler ValidateIPAddress = null;
#endregion
#region Members
private int m_PassiveStartPort = 20000;
#endregion
#region Properties
/// <summary>
/// Gets active sessions.
/// </summary>
public new FTP_Session[] Sessions
{
get
{
SocketServerSession[] sessions = base.Sessions;
FTP_Session[] ftpSessions = new FTP_Session[sessions.Length];
sessions.CopyTo(ftpSessions, 0);
return ftpSessions;
}
}
/// <summary>
/// Gets or sets passive mode public IP address what is reported to clients.
/// This property is manly needed if FTP server is running behind NAT.
/// Value null means not spcified.
/// </summary>
public IPAddress PassivePublicIP { get; set; }
/// <summary>
/// Gets or sets passive mode start port form which server starts using ports.
/// </summary>
/// <exception cref="ArgumentException">Is raised when ivalid value is passed.</exception>
public int PassiveStartPort
{
get { return m_PassiveStartPort; }
set
{
if (value < 1)
{
throw new ArgumentException("Valu must be > 0 !");
}
m_PassiveStartPort = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Defalut constructor.
/// </summary>
public FTP_Server()
{
BindInfo = new[] {new IPBindInfo("", IPAddress.Any, 21, SslMode.None, null)};
}
#endregion
#region Overrides
/// <summary>
/// Initialize and start new session here. Session isn't added to session list automatically,
/// session must add itself to server session list by calling AddSession().
/// </summary>
/// <param name="socket">Connected client socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
protected override void InitNewSession(Socket socket, IPBindInfo bindInfo)
{
string sessionID = Guid.NewGuid().ToString();
SocketEx socketEx = new SocketEx(socket);
if (LogCommands)
{
socketEx.Logger = new SocketLogger(socket, SessionLog);
socketEx.Logger.SessionID = sessionID;
}
FTP_Session session = new FTP_Session(sessionID, socketEx, bindInfo, this);
}
#endregion
#region Virtual methods
/// <summary>
/// Raises event ValidateIP event.
/// </summary>
/// <param name="localEndPoint">Server IP.</param>
/// <param name="remoteEndPoint">Connected client IP.</param>
/// <returns>Returns true if connection allowed.</returns>
internal virtual bool OnValidate_IpAddress(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint)
{
ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(localEndPoint, remoteEndPoint);
if (ValidateIPAddress != null)
{
ValidateIPAddress(this, oArg);
}
return oArg.Validated;
}
/// <summary>
/// Authenticates user.
/// </summary>
/// <param name="session">Reference to current pop3 session.</param>
/// <param name="userName">User name.</param>
/// <param name="passwData"></param>
/// <param name="data"></param>
/// <param name="authType"></param>
/// <returns></returns>
internal virtual bool OnAuthUser(FTP_Session session,
string userName,
string passwData,
string data,
AuthType authType)
{
AuthUser_EventArgs oArg = new AuthUser_EventArgs(session, userName, passwData, data, authType);
if (AuthUser != null)
{
AuthUser(this, oArg);
}
return oArg.Validated;
}
#endregion
#region Internal methods
internal FileSysEntry_EventArgs OnGetDirInfo(FTP_Session session, string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, "");
if (GetDirInfo != null)
{
GetDirInfo(this, oArg);
}
return oArg;
}
internal bool OnDirExists(FTP_Session session, string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, "");
if (DirExists != null)
{
DirExists(this, oArg);
}
return oArg.Validated;
}
internal bool OnCreateDir(FTP_Session session, string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, "");
if (CreateDir != null)
{
CreateDir(this, oArg);
}
return oArg.Validated;
}
internal bool OnDeleteDir(FTP_Session session, string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, "");
if (DeleteDir != null)
{
DeleteDir(this, oArg);
}
return oArg.Validated;
}
internal bool OnRenameDirFile(FTP_Session session, string from, string to)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, from, to);
if (RenameDirFile != null)
{
RenameDirFile(this, oArg);
}
return oArg.Validated;
}
internal bool OnFileExists(FTP_Session session, string file)
{
// Remove last /
file = file.Substring(0, file.Length - 1);
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, "");
if (FileExists != null)
{
FileExists(this, oArg);
}
return oArg.Validated;
}
internal Stream OnGetFile(FTP_Session session, string file)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, "");
if (GetFile != null)
{
GetFile(this, oArg);
}
return oArg.FileStream;
}
internal Stream OnStoreFile(FTP_Session session, string file)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, "");
if (StoreFile != null)
{
StoreFile(this, oArg);
}
return oArg.FileStream;
}
internal bool OnDeleteFile(FTP_Session session, string file)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, "");
if (DeleteFile != null)
{
DeleteFile(this, oArg);
}
return oArg.Validated;
}
#endregion
}
}
| |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// 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 Copyright
using System;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using WatiN.Core.Constraints;
using WatiN.Core.Exceptions;
using WatiN.Core.UnitTests.TestUtils;
using TimeoutException=WatiN.Core.Exceptions.TimeoutException;
namespace WatiN.Core.UnitTests
{
[TestFixture]
public class HTMLDialogTests : BaseWithBrowserTests
{
[TearDown]
public void TearDown()
{
Ie.HtmlDialogs.CloseAll();
}
[Test]
public void Should_find_modal_HTMLDialog_by_title_then_typetext_and_handle_alert_popup()
{
Ie.Button("modalid").ClickNoWait();
using (var htmlDialog = Ie.HtmlDialog(Find.ByTitle("PopUpTest")))
{
Assert.IsInstanceOfType(typeof (DomContainer), htmlDialog);
Assert.IsNotNull(htmlDialog, "Dialog niet aangetroffen");
Assert.AreEqual("PopUpTest", htmlDialog.Title, "Unexpected title");
htmlDialog.TextField("name").TypeText("Textfield in HTMLDialog");
htmlDialog.Button("hello").Click();
}
}
[Test]
public void HTMLDialogModalByUrl()
{
Ie.Button("modalid").ClickNoWait();
using (var htmlDialog = Ie.HtmlDialog(Find.ByUrl(PopUpURI)))
{
Assert.IsNotNull(htmlDialog, "Dialog not found");
Assert.AreEqual("PopUpTest", htmlDialog.Title, "Unexpected title");
}
}
[Test]
public void HTMLDialogShouldBeClosedWhenDisposed()
{
// Given no HtmlDialog is shown
Assert.That(Ie.HtmlDialogs.Length, Is.EqualTo(0));
// When I open an HtmlDialog
// and verify it exists
// and the HtmlDialog instance gets disposed
Ie.Button("modalid").ClickNoWait();
using (var htmlDialog = Ie.HtmlDialog(Find.ByUrl(PopUpURI)))
{
Assert.IsNotNull(htmlDialog, "Dialog not found");
}
// Then again there should be no HtmlDialog open
Assert.That(Ie.HtmlDialogs.Length, Is.EqualTo(0));
}
[Test]
public void HTMLDialogsExists()
{
Constraint findBy = Find.ByUrl(PopUpURI);
Assert.IsFalse(Ie.HtmlDialogs.Exists(findBy));
Ie.Button("modalid").ClickNoWait();
Thread.Sleep(1000);
Assert.IsTrue(Ie.HtmlDialogs.Exists(findBy));
}
[Test]
public void HTMLDialogNotFoundException()
{
const int timeoutTime = 2;
const string expectedMessage = "Could not find a HTMLDialog matching criteria: Attribute 'title' contains 'PopUpTest' ignoring case. (Search expired after '2' seconds). Is there a popup blocker active?";
var startTime = DateTime.Now;
try
{
// Time out after timeoutTime seconds
startTime = DateTime.Now;
Ie.HtmlDialog(Find.ByTitle("PopUpTest"), timeoutTime);
Assert.Fail("PopUpTest should not be found");
}
catch (Exception e)
{
Assert.IsInstanceOfType(typeof (HtmlDialogNotFoundException), e, "Unexpected exception");
// add 1 second to give it some slack.
Assert.Greater(timeoutTime + 1, DateTime.Now.Subtract(startTime).TotalSeconds);
Assert.AreEqual(expectedMessage, e.Message, "Unexpected exception message");
}
}
[Test]
public void HTMLDialogModeless()
{
Ie.Button("popupid").Click();
Thread.Sleep(100);
using (Document dialog = Ie.HtmlDialogs[0])
{
var value = dialog.TextField("dims").Value;
Assert.AreEqual("47", value);
}
}
[Test]
public void HtmlDialog_should_exist()
{
// GIVEN
bool exists;
Ie.Button("popupid").Click();
Thread.Sleep(100);
using (var dialog = Ie.HtmlDialogs[0])
{
// WHEN
exists = dialog.Exists;
}
// THEN
Assert.That(exists, Is.True, "Expect HtmlDialog would exist");
}
[Test]
public void HtmlDialog_should_not_exist()
{
// GIVEN
bool exists;
Ie.Button("popupid").Click();
Thread.Sleep(100);
var dialog = Ie.HtmlDialogs[0];
dialog.Close();
// WHEN
exists = dialog.Exists;
// THEN
Assert.That(exists, Is.False, "Expect HtmlDialog should no longer exist");
}
[Test]
public void Should_wait_until_html_dialog_is_closed()
{
// GIVEN
Ie.Button("popupid").Click();
Thread.Sleep(100);
var dialog = Ie.HtmlDialogs[0];
dialog.Button("closebutton").ClickNoWait();
// WHEN
dialog.WaitUntilClosed();
// THEN
Assert.That(dialog.Exists, Is.False, "Expect HtmlDialog was closed");
}
[Test]
public void WaitUntilClosed_should_throw_trimeout_exception_when_timed_out()
{
// GIVEN
Ie.Button("popupid").Click();
Thread.Sleep(100);
var dialog = Ie.HtmlDialogs[0];
try
{
// WHEN
dialog.WaitUntilClosed(1);
Assert.Fail("Should have thrown TimeoutException");
}
catch (TimeoutException)
{
// THEN: this is OK
}
}
public override Uri TestPageUri
{
get { return MainURI; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using WebDumpLib.Core;
using WebDumpUtils.Tracking;
using WebDumpUtils.XML;
namespace WebDumpLib.Content
{
public class Target
{
public TargetXml Configuration { get; }
public string FolderName { get; }
private string LogFileName { get; }
public string ShortName { get; }
private bool Cancelled { get; set; }
private ProgressInts Progress { get; set; }
public event ProgressChangedEventHandler ProgressChanged;
public Target(TargetXml config)
{
Configuration = config;
Cancelled = false;
var trimmedUrl = Configuration.Url.TrimEnd('/');
ShortName = trimmedUrl.Substring(trimmedUrl.LastIndexOf('/') + 1);
LogWriter.WriteLine("Target Constructor for Target " + ShortName, "master");
FolderName = ".\\output\\" + Configuration.Name;
LogFileName = "logs\\" + Configuration.Name;
LogWriter.OpenLog(ShortName, LogFileName, Configuration.LogHistoryDepth);
CreateFolders();
switch (Configuration.Type)
{
case TargetType.Chan:
//Configuration.Url = "https://a.4cdn.org/" + ShortName + "/threads.json";
Configuration.Url = "https://a.4cdn.org/" + ShortName + "/catalog.json";
break;
case TargetType.Reddit:
Configuration.Url = "https://oauth.reddit.com/r/" + ShortName;
break;
}
}
~Target()
{
LogWriter.Close(ShortName);
}
public void WriteLog(string entry)
{
LogWriter.WriteLine(entry, ShortName);
}
public void WriteError(string entry)
{
LogWriter.WriteError(entry, ShortName);
}
public void WriteException(Exception ex, string message)
{
LogWriter.WriteException(ex, message, ShortName);
}
private void CreateFolders()
{
if (!Directory.Exists(FolderName))
{
Directory.CreateDirectory(FolderName);
}
if (!Directory.Exists(".//logs"))
{
Directory.CreateDirectory(".//logs");
}
WriteLog("Start of Run: " + DateTime.Now + "\n");
}
public List<Site> FindTrackedSites(ProgressInts progress)
{
WriteLog("Target: " + ShortName + " Finding Tracked Sites");
Cancelled = false;
Progress = progress;
var sites = FindRedownloadSites();
Progress.OverallTotal = 3;
Progress.OverallDone = 1;
ReportProgress();
switch (Configuration.Type)
{
case TargetType.Chan:
foreach (var site in FindChanTrackedSites())
{
if (!sites.ContainsKey(site.Key)) sites.Add(site.Key, site.Value);
}
break;
case TargetType.Reddit:
foreach (var site in FindRedditTrackedSites())
{
if (!sites.ContainsKey(site.Key)) sites.Add(site.Key, site.Value);
}
break;
case TargetType.Generic:
Progress.OverallDone = 2;
var urls = new List<string>();
foreach (var site in FindGenericTrackedSites(0, Configuration.Url, ref urls))
{
if (!sites.ContainsKey(site.Key)) sites.Add(site.Key, site.Value);
}
break;
}
var output = new List<Site>();
foreach (var site in sites)
{
output.Add(site.Value);
}
Progress.OverallDone = Progress.OverallTotal;
ReportProgress();
WriteLog("FNT Complete! Target: " + ShortName + " Cancelled: " + Cancelled + ", Site Count: " + output.Count);
if (Cancelled) return new List<Site>();
return output;
}
private Dictionary<string, Site> FindRedownloadSites()
{
WriteLog("Target: " + ShortName + " Finding Redownload Sites");
var output = new Dictionary<string, Site>();
var sites = WebDumpCore.UrlTables.GetRedownloadSites(Configuration.Url, FolderName);
Progress.ItemDone = 0;
Progress.ItemMessage = "Finding Redownload Sites";
Progress.ItemTotal = sites.Count;
var imageUrls = new List<string>();
var siteUrls = new List<string>();
foreach (var site in sites)
{
if (Cancelled) break;
Progress.ItemDone++;
ReportProgress();
if (WebDumpCore.UrlTables.HasTrackedSite(site.Url, site.Value, true)) continue;
if (output.ContainsKey(site.Url)) continue;
var thissite = new Site(site.Url, site.Name, site.FolderName, this, site.Value, null, false, -1, 0, "");
imageUrls.AddRange(thissite.SiteInfo.ImageUrls);
siteUrls.AddRange(thissite.SiteInfo.SiteUrls);
output.Add(site.Url, thissite);
WriteLog("Thread " + site.Name + " is Redownload");
}
WebDumpCore.UrlTables.RemoveImageUrls(imageUrls, WebDumpCore.Configuration.FuzzyImageMatches);
WebDumpCore.UrlTables.RemoveSiteUrls(siteUrls);
Progress.ItemTotal = 0;
Progress.ItemDone = 0;
Progress.ItemMessage = "";
return output;
}
private Dictionary<string, Site> FindRedditTrackedSites()
{
WriteLog("Target " + ShortName + " is a Reddit Subreddit. Using JSON to determine TrackedSites");
var output = new Dictionary<string, Site>();
var counter = 0;
var totalScanned = 0;
var first = true;
Progress.OverallTotal = Progress.OverallDone + Configuration.RedditConfig.SearchQueries.Count +
(Configuration.RedditConfig.New ? 1 : 0) + (Configuration.RedditConfig.Top ? 1 : 0) +
(Configuration.RedditConfig.Best ? 1 : 0) + (Configuration.RedditConfig.Rising ? 1 : 0) +
(Configuration.RedditConfig.Controversial ? 1 : 0) + (Configuration.RedditConfig.HotRegion != "" ? 1 : 0);
Progress.Message = "Finding Reddit Threads: " + output.Count + " new";
ReportProgress();
using (var d = new Downloader())
{
d.OnDownloadProgress += ReportProgressHandler;
var after = "";
const int limit = 100;
foreach (var query in Configuration.RedditConfig.SearchQueries)
{
Progress.ItemTotal = 1000;
Progress.ItemDone = 0;
Progress.ItemMessage = "";
Progress.Message = "Finding New Reddit Threads: " + output.Count + " new";
ReportProgress();
counter = 0;
after = "";
while (first || after != "")
{
if (Cancelled)
{
WriteError("FNT Cancelled in Date search");
return new Dictionary<string, Site>();
}
var queryUri = Uri.EscapeUriString(query);
after = ProcessRedditSearchPage(Configuration.Url, queryUri, after, limit, counter, d, ref output, out int postCount);
totalScanned += postCount;
counter += limit;
Progress.ItemMessage = "Searching subreddit for " + query;
Progress.Message = "Finding Reddit Threads: " + output.Count + " new";
Progress.ItemDone = counter;
ReportProgress();
first = false;
}
Progress.OverallDone++;
}
Progress.ItemTotal = 0;
Progress.ItemDone = 0;
Progress.ItemMessage = "";
Progress.Message = "Finding New Reddit Threads: " + output.Count + " new";
ReportProgress();
if (Cancelled) return new Dictionary<string, Site>();
if (Configuration.RedditConfig.New &&
(output.Count < Configuration.RedditConfig.MaxThreads ||
Configuration.RedditConfig.MaxThreads == 0))
{
SearchRedditPages("new", "", ref output, ref totalScanned, d);
}
if (Cancelled) return new Dictionary<string, Site>();
if (Configuration.RedditConfig.Best &&
(output.Count < Configuration.RedditConfig.MaxThreads ||
Configuration.RedditConfig.MaxThreads == 0))
{
SearchRedditPages("best", "", ref output, ref totalScanned, d);
}
if (Cancelled) return new Dictionary<string, Site>();
if (Configuration.RedditConfig.Controversial &&
(output.Count < Configuration.RedditConfig.MaxThreads ||
Configuration.RedditConfig.MaxThreads == 0))
{
SearchRedditPages("controversial", "", ref output, ref totalScanned, d);
}
if (Cancelled) return new Dictionary<string, Site>();
if (Configuration.RedditConfig.Rising &&
(output.Count < Configuration.RedditConfig.MaxThreads ||
Configuration.RedditConfig.MaxThreads == 0))
{
SearchRedditPages("rising", "", ref output, ref totalScanned, d);
}
if (Cancelled) return new Dictionary<string, Site>();
if (Configuration.RedditConfig.Top &&
(output.Count < Configuration.RedditConfig.MaxThreads ||
Configuration.RedditConfig.MaxThreads == 0))
{
SearchRedditPages("top", "", ref output, ref totalScanned, d);
}
if (Cancelled) return new Dictionary<string, Site>();
if (Configuration.RedditConfig.HotRegion != "" &&
(output.Count < Configuration.RedditConfig.MaxThreads ||
Configuration.RedditConfig.MaxThreads == 0))
{
SearchRedditPages("hot", $"&g={Configuration.RedditConfig.HotRegion}", ref output, ref totalScanned, d);
}
}
WriteLog($"FNT: Reddit Search Complete. Found {output.Count} new threads in {totalScanned} posts");
return output;
}
private void SearchRedditPages(string listingType, string extraParam, ref Dictionary<string, Site> output, ref int totalScanned, Downloader d)
{
Progress.ItemTotal = 1000;
Progress.ItemDone = 0;
var counter = 0;
var first = true;
var after = "";
while (first || after != "")
{
if (Cancelled)
{
output = new Dictionary<string, Site>();
return;
}
WriteLog($"Finding {listingType} Threads: after=" + after + ", count=" + counter);
after = ProcessRedditPage(Configuration.Url, listingType, after, extraParam,
100, counter, d, ref output, Configuration.RedditConfig.EndSearch, out int postCount);
totalScanned += postCount;
counter += 100;
Progress.ItemDone += 100;
Progress.Message = $"Finding {listingType} Reddit Threads: " + output.Count + " new";
ReportProgress();
first = false;
}
Progress.ItemTotal = 0;
Progress.ItemDone = 0;
Progress.ItemMessage = "";
Progress.OverallDone++;
Progress.Message = $"Finding {listingType} Reddit Threads: " + output.Count + " new";
ReportProgress();
}
private string ProcessRedditPage(string subredditUrl, string listing, string after, string extraParam, int limit, int count, Downloader d, ref Dictionary<string, Site> threads, bool abortIfNone, out int postCount)
{
//Parent.Board.Log.Add("Finding New Threads: " + url);
//Progress.Message = "Finding New Threads";
var url = subredditUrl + '/' + listing + ".json?limit=" + limit + "&count=" + count + "&t=all&show=all" + extraParam;
if (after.Length > 0)
{
url = url + "&after=" + after;
}
return ProcessRedditPage(url, d, ref threads, abortIfNone, out postCount);
}
public string GetOauthToken()
{
var done = false;
var tries = 0;
var token = "";
while (!done && tries < 5)
{
try
{
token = WebDumpCore.OauthLogin.GetToken();
done = true;
}
catch (WebDumpJSON.RedditJSON.OauthException ex)
{
WriteException(ex, $"OauthException occurred in ProcessRedditPage, response was {ex.Response}");
System.Threading.Thread.Sleep(5000);
}
catch (AggregateException ee)
{
foreach (var ex in ee.InnerExceptions)
{
if (ex is WebDumpJSON.RedditJSON.OauthException oe)
{
WriteException(oe, $"OauthException occurred in ProcessRedditPage, response was {oe.Response}");
}
else
{
WriteException(ex, "Exception occurred in ProcessRedditPage: " + ex.Message);
}
}
System.Threading.Thread.Sleep(5000);
}
tries++;
}
return token;
}
private string ProcessRedditPage(string url, Downloader d, ref Dictionary<string, Site> threads, bool abortIfNone, out int postsCount)
{
// variables
var initialCount = threads.Count;
postsCount = 0;
string content;
var token = GetOauthToken();
if (token == "") return "";
// download index
try
{
content = d.DownloadText(this, url, Progress, 1010, GetOauthToken());
}
catch (WebException ex)
{
WriteException(ex, $"WebException occurred in ProcessRedditPage, url is {url}");
// just pass the exception through
return "";
}
if (content == "")
{
return "";
}
var thisReddit = new WebDumpJSON.RedditJSON.Reddit();
var posts = thisReddit.GetPosts(content);
postsCount = posts.Length;
const string afterRegex = "\"after\": \"(t3_[0-9a-z]+)\"";
var afterUrl = Regex.Match(content, afterRegex).Groups[1].Value;
foreach (var p in posts)
{
var permlink = p.Permalink.TrimEnd('/');
var threadurl = "https://oauth.reddit.com" + permlink.Substring(0, permlink.LastIndexOf('/')) + ".json?limit=500&depth=10";
var threadname = p.Id;
var comments = p.CommentCount;
if (WebDumpCore.UrlTables.HasTrackedSite(threadurl, comments, true)) continue;
if (threads.ContainsKey(threadurl)) continue;
threads.Add(threadurl, new Site(threadurl, p.Title, FolderName + "\\" + threadname, this, comments, null, false, -1, 0, ""));
WriteLog("Thread " + p.Title + " is New");
if (threads.Count < Configuration.RedditConfig.MaxThreads || Configuration.RedditConfig.MaxThreads <= 0)
continue;
return "";
}
if (threads.Count != initialCount || !abortIfNone) return afterUrl;
return "";
}
private string ProcessRedditSearchPage(string subredditUrl, string query, string after, int limit, int count, Downloader d, ref Dictionary<string, Site> threads, out int postCount)
{
//Parent.Board.Log.Add("Finding New Threads: " + url);
//Progress.Message = "Finding New Threads";
var url = subredditUrl + "/search.json?limit=" + limit + "&count=" + count + "&restrict_sr=on&t=all&show=all&sort=new";
if (query.Length > 0)
{
url = url + "&q=" + query;
}
if (after.Length > 0)
{
url = url + "&after=" + after;
}
return ProcessRedditPage(url, d, ref threads, true, out postCount);
}
private Dictionary<string, Site> FindChanTrackedSites()
{
WriteLog("Target " + ShortName + " is a 4chan Board. Using JSON to determine Tracked Sites");
var threadOutput = new Dictionary<string, Site>();
// variables
var content = "";
var tries = 0;
// download index
using (var d = new Downloader())
{
d.OnDownloadProgress += ReportProgressHandler;
try
{
var done = false;
while (!done && tries < 5)
{
content = d.DownloadText(this, Configuration.Url, Progress, 1100, null);
done = d.Success;
tries++;
}
}
catch (WebException ex)
{
WriteException(ex, "WebException occurred in FindChanTrackedSites");
// just pass the exception through
}
}
Progress.OverallDone = 2;
ReportProgress();
var thisBoard = new WebDumpJSON.ChanJSON.Catalog();
var threads = new List<WebDumpJSON.ChanJSON.CatalogListing>(WebDumpJSON.ChanJSON.Catalog.GetThreads(content));
var counter = 0;
Progress.ItemTotal = threads.Count;
Progress.ItemDone = 0;
Progress.ItemMessage = "Parsing Thread Catalog";
ReportProgress();
foreach (var t in threads)
{
if (Cancelled) return new Dictionary<string, Site>();
counter++;
var threadurl = "https://a.4cdn.org/" + ShortName + "/thread/" + t.ThreadNumber + ".json";
var replies = t.Replies;
var number = t.ThreadNumber.ToString();
var name = t.Subject ?? t.Comment ?? number;
name = WebUtility.HtmlDecode(name);
Progress.ItemDone++;
ReportProgress();
if (WebDumpCore.UrlTables.HasTrackedSite(threadurl, replies, true)) continue;
if (threadOutput.ContainsKey(threadurl)) continue;
threadOutput.Add(threadurl, new Site(threadurl, name, FolderName + "\\" + number, this, replies, null, false, -1, 0, ""));
WriteLog("Thread " + name + " is New");
}
Progress.ItemTotal = 0;
Progress.ItemDone = 0;
Progress.ItemMessage = "";
ReportProgress();
return threadOutput;
}
private Dictionary<string, Site> FindGenericTrackedSites(int level, string url, ref List<string> checkedUrls)
{
WriteLog("Target " + ShortName + " is a Generic Site. This is level " + level + " of " + Configuration.GenericConfig.Depth);
var threadOutput = new Dictionary<string, Site>();
// variables
var content = "";
var tries = 0;
// download index
using (var d = new Downloader())
{
d.OnDownloadProgress += ReportProgressHandler;
try
{
var done = false;
while (!done && tries < 5)
{
content = d.DownloadText(this, url, ProgressInts.Decay(Progress), 0, null);
done = d.Success;
tries++;
}
}
catch (WebException ex)
{
WriteException(ex, "WebException occurred in FindGenericTrackedSites");
// just pass the exception through
}
}
ReportProgress();
var baseUri = new Uri(Configuration.Url);
var contentTemp = content.Replace("\n", "");
const string imageRegex = @"(?:<a[^>]*href|<frame[^>]*src)=""([^"">]*)""[^>]*>";
var mc = Regex.Matches(contentTemp, imageRegex, RegexOptions.IgnoreCase);
Progress.ItemTotal = mc.Count;
Progress.ItemDone = 0;
Progress.ItemMessage = $"Parsing Regex Matches: Level {level + 1}/{Configuration.GenericConfig.Depth + 1}";
ReportProgress();
var nextLevelSites = new List<string>();
foreach (Match m in mc)
{
Progress.ItemDone++;
ReportProgress();
if (Cancelled) return new Dictionary<string, Site>();
var threadUrl = m.Groups[1].Value;
threadUrl = UrlTables.NormalizeUrl(threadUrl, true);
if (threadUrl.Length > 2 && threadUrl[0] == '/' && threadUrl[1] == '/')
{
threadUrl = baseUri.Scheme + ":" + threadUrl;
}
threadUrl = threadUrl.TrimEnd('/');
if (threadUrl.Length < 2) continue;
if (threadUrl.Contains("mailto:")) continue;
Uri threadUri = null;
try
{
threadUri = new Uri(threadUrl, UriKind.RelativeOrAbsolute);
if (!threadUri.IsAbsoluteUri)
{
threadUri = new Uri(baseUri, threadUri);
}
}
catch (UriFormatException)
{
continue;
}
if (threadUri == null) continue;
if (checkedUrls.Contains(threadUri.AbsoluteUri)) continue;
checkedUrls.Add(threadUri.AbsoluteUri);
if (threadUri.Host != baseUri.Host) continue;
if (Configuration.GenericConfig.DirectoryFilter.Length > 0 && !threadUri.AbsoluteUri.Contains(Configuration.GenericConfig.DirectoryFilter)) continue;
var fileTypes = new HashSet<string>(WebDumpCore.Configuration.FileTypes);
var fileTypesString = fileTypes.Aggregate("(?:", (current, s) => current + s + "|");
fileTypesString = "\\." + fileTypesString.Remove(fileTypesString.Length - 1) + ")$";
if (Regex.IsMatch(threadUri.AbsoluteUri, fileTypesString)) continue; // Skip files
var number = threadUri.LocalPath;
if (number.IndexOf('/') >= 0)
{
number = number.Substring(number.LastIndexOf('/') + 1);
}
long modifiedTicks = 0;
long size = 0;
var modified = new DateTime();
Downloader.DownloadHeader(this, threadUri.AbsoluteUri, ref size, ref modified);
modifiedTicks = modified.Ticks;
if (WebDumpCore.UrlTables.HasTrackedSite(threadUri.AbsoluteUri, modifiedTicks, true)) continue;
if (threadOutput.ContainsKey(threadUri.AbsoluteUri)) continue;
threadOutput.Add(threadUri.AbsoluteUri, new Site(threadUri.AbsoluteUri, number, FolderName + "\\" + number, this, modifiedTicks, null, false, -1, 0, ""));
if (Configuration.GenericConfig.Depth == -1 || level < Configuration.GenericConfig.Depth)
{
nextLevelSites.Add(threadUri.AbsoluteUri);
}
WriteLog("Thread " + number + " is New");
}
Progress.ItemTotal = nextLevelSites.Count;
Progress.ItemDone = 0;
Progress.ItemMessage = $"Checking Next Level Sites: Level {level + 1}/{Configuration.GenericConfig.Depth + 1}";
ReportProgress();
foreach (var site in nextLevelSites)
{
var progressTemp = new ProgressInts(Progress);
Progress = ProgressInts.Decay(Progress);
foreach (var foundSite in FindGenericTrackedSites(level + 1, site, ref checkedUrls))
{
if (threadOutput.ContainsKey(foundSite.Key)) continue;
threadOutput.Add(foundSite.Key, foundSite.Value);
}
Progress = new ProgressInts(progressTemp);
Progress.ItemDone++;
ReportProgress();
}
Progress.ItemDone = Progress.ItemTotal;
ReportProgress();
return threadOutput;
}
private void ReportProgress()
{
ReportProgressHandler(this, new ProgressChangedEventArgs(Progress.ItemPercentage(), Progress));
}
private void ReportProgressHandler(object sender, ProgressChangedEventArgs e)
{
//WebDumpLib.Tracking.Log.WriteLine("Translating Downloader ReportProgress Event to Target ReportProgress Event");
var handler = ProgressChanged;
handler?.Invoke(this, new ProgressChangedEventArgs(Progress.ItemPercentage(), Progress));
}
public void CancelEventHandler(object o, CancelEventArgs e)
{
WriteError("Cancel called (Target)!");
Cancelled = true;
}
}
}
| |
namespace Sitecore.Feature.Demo.Tests.Services
{
using System;
using System.Linq;
using FluentAssertions;
using NSubstitute;
using Sitecore.Analytics;
using Sitecore.Analytics.Data.Items;
using Sitecore.Analytics.Tracking;
using Sitecore.Collections;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.FakeDb.AutoFixture;
using Sitecore.FakeDb.Sites;
using Sitecore.Feature.Demo.Services;
using Sitecore.Sites;
using Xunit;
public class ProfileProviderTests
{
[Theory]
[AutoProfileDbData]
public void LoadProfiles_SettingWithProfiles_ShouldReturnExistentProfilesEnumerable([Content] Item item, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
{
var profileSettingItem = item.Add("profileSetting", new TemplateID(Templates.ProfilingSettings.ID));
var profileItem = item.Add("profile", new TemplateID(ProfileItem.TemplateID));
using (new EditContext(profileSettingItem))
{
profileSettingItem.Fields[Templates.ProfilingSettings.Fields.SiteProfiles].Value = profileItem.ID.ToString();
}
var provider = new ProfileProvider();
var fakeSiteContext = new FakeSiteContext(new StringDictionary
{
{
"rootPath", "/sitecore"
},
{
"startItem", profileSettingItem.Paths.FullPath.Remove(0, "/sitecore".Length)
}
});
fakeSiteContext.Database = item.Database;
using (new SiteContextSwitcher(fakeSiteContext))
{
var siteProfiles = provider.GetSiteProfiles();
siteProfiles.Count().Should().Be(1);
}
}
[Theory]
[AutoProfileDbData]
public void LoadProfiles_SettingsIsEmpty_ShouldReturnExistentProfilesEnumerable([Content] Item item, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
{
var profileSettingItem = item.Add("profileSetting", new TemplateID(Templates.ProfilingSettings.ID));
var profileItem = item.Add("profile", new TemplateID(ProfileItem.TemplateID));
var provider = new ProfileProvider();
var fakeSiteContext = new FakeSiteContext(new StringDictionary
{
{
"rootPath", "/sitecore"
},
{
"startItem", profileSettingItem.Paths.FullPath.Remove(0, "/sitecore".Length)
}
});
fakeSiteContext.Database = item.Database;
using (new SiteContextSwitcher(fakeSiteContext))
{
provider.GetSiteProfiles().Count().Should().Be(0);
}
}
[Theory]
[AutoProfileDbData]
public void LoadProfiles_SettingsNotExists_ShouldReturnExistentProfilesEnumerable([Content] Item item)
{
var fakeSiteContext = new FakeSiteContext(new StringDictionary
{
{
"rootPath", "/sitecore"
},
{
"startItem", item.Paths.FullPath.Remove(0, "/sitecore".Length)
}
});
fakeSiteContext.Database = item.Database;
using (new SiteContextSwitcher(fakeSiteContext))
{
var provider = new ProfileProvider();
provider.GetSiteProfiles().Count().Should().Be(0);
}
}
[Theory]
[AutoProfileDbData]
public void HasMatchingPattern_ItemNotExists_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
{
tracker.Interaction.Returns(currentInteraction);
currentInteraction.Profiles[null].ReturnsForAnyArgs(profile);
profile.PatternId = Guid.NewGuid();
var fakeSiteContext = new FakeSiteContext("fake")
{
Database = Database.GetDatabase("master")
};
using (new TrackerSwitcher(tracker))
{
using (new SiteContextSwitcher(fakeSiteContext))
{
var provider = new ProfileProvider();
provider.HasMatchingPattern(new ProfileItem(profileItem)).Should().BeFalse();
}
}
}
[Theory]
[AutoProfileDbData]
public void HasMatchingPattern_ItemExists_ShouldReturnTrue([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
{
tracker.Interaction.Returns(currentInteraction);
currentInteraction.Profiles[null].ReturnsForAnyArgs(profile);
var pattern = profileItem.Add("fakePattern", new TemplateID(PatternCardItem.TemplateID));
profile.PatternId = pattern.ID.Guid;
var fakeSiteContext = new FakeSiteContext("fake")
{
Database = Database.GetDatabase("master")
};
using (new TrackerSwitcher(tracker))
{
using (new SiteContextSwitcher(fakeSiteContext))
{
var provider = new ProfileProvider();
provider.HasMatchingPattern(new ProfileItem(profileItem)).Should().BeTrue();
}
}
}
[Theory]
[AutoProfileDbData]
public void HasMatchingPattern_TrackerReturnsNull_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
{
tracker.Interaction.Returns(currentInteraction);
currentInteraction.Profiles[null].ReturnsForAnyArgs((Profile)null);
var fakeSiteContext = new FakeSiteContext("fake")
{
Database = Database.GetDatabase("master")
};
using (new TrackerSwitcher(tracker))
{
using (new SiteContextSwitcher(fakeSiteContext))
{
var provider = new ProfileProvider();
provider.HasMatchingPattern(new ProfileItem(profileItem)).Should().BeFalse();
}
}
}
[Theory]
[AutoProfileDbData]
public void HasMatchingPattern_TrackerReturnsProfileWithoutID_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
{
tracker.Interaction.Returns(currentInteraction);
currentInteraction.Profiles[null].ReturnsForAnyArgs(profile);
profile.PatternId = null;
var fakeSiteContext = new FakeSiteContext("fake")
{
Database = Database.GetDatabase("master")
};
using (new TrackerSwitcher(tracker))
{
using (new SiteContextSwitcher(fakeSiteContext))
{
var provider = new ProfileProvider();
provider.HasMatchingPattern(new ProfileItem(profileItem)).Should().BeFalse();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using GuruComponents.Netrix.HelpLine.Events;
using GuruComponents.Netrix.PlugIns;
using GuruComponents.Netrix.WebEditing.Elements;
using GuruComponents.Netrix;
using GuruComponents.Netrix.Designer;
using GuruComponents.Netrix.ComInterop;
using System.Collections.Generic;
using System.ComponentModel.Design;
namespace GuruComponents.Netrix.HelpLine
{
/// <summary>
/// Designer for HelpLine support.
/// </summary>
/// <remarks>
/// Checks for mouse over cross, moves and draws the
/// helpline. This designer may work if it is attached as behavior to body and as edit designer
/// to mshtml site. The host application may switch on/off the behavior but never removes the designer.
/// <para>
/// Additional features available for helplines:
/// <list type="bullet">
/// <item>
/// <term>Snap helpline to grid (default: On)</term>
/// <description>You can define a (invisible) grid which the helpline snaps into. The grids default distance is 16 pixels.</description>
/// <term>Snap Elements to helpline (Default: On)</term>
/// <description>If the control is in 2D (absolute) position mode the elements can be snapped to the line. The magnetic zone is 4 pixels.</description>
/// <term>Change the Color and Width of the Pen (Default: Blue, width 1 pixel)</term>
/// <description>You can use a <see cref="System.Drawing.Pen">Pen</see> object to change the style of the lines.</description>
/// </item>
/// </list>
/// The helpline can be moved using the mouse either on the cross (changes x and y coordinates the same time) or on each
/// line (moves only x or y, respectively). During the move with the cross the mouse pointer becomes a hand and the Ctrl-Key
/// can be used to modify the behavior.
/// </para>
/// <para>
/// <b>Usage instructions:</b>
/// </para>
/// <para>
/// To use the helpline you must retrieve an instance of that class using the property
/// <see cref="GuruComponents.Netrix.HelpLine.HelpLine">HelpLine</see>. The returned object can be changed
/// in any way. After changing must use the command
/// <see cref="GuruComponents.Netrix.HelpLine.HelplineCommands.Activate">Activate</see> to make the lines visible.
/// The behavior can changed at any time. The object returned from <see cref="GuruComponents.Netrix.HelpLine.HelpLine">HelpLine</see>
/// is always the same (singleton).
/// </para>
/// </remarks>
[ToolboxItem(true)]
[ToolboxBitmap(typeof(GuruComponents.Netrix.HelpLine.HelpLine), "Resources.HelpLine.ico")]
[ProvideProperty("HelpLine", typeof(GuruComponents.Netrix.IHtmlEditor))]
public class HelpLine : Component, System.ComponentModel.IExtenderProvider, GuruComponents.Netrix.PlugIns.IPlugIn
{
private Hashtable properties;
private Hashtable behaviors;
/// <summary>
/// Default Constructor supports design time behavior
/// </summary>
public HelpLine()
{
properties = new Hashtable();
behaviors = new Hashtable();
}
/// <summary>
/// Ctor used from designer
/// </summary>
/// <param name="parent"></param>
public HelpLine(IContainer parent) : this()
{
properties = new Hashtable();
parent.Add(this);
}
private HelpLineProperties EnsurePropertiesExists(IHtmlEditor key)
{
HelpLineProperties p = (HelpLineProperties) properties[key];
if (p == null)
{
p = new HelpLineProperties();
properties[key] = p;
}
return p;
}
private HelpLineBehavior EnsureBehaviorExists(IHtmlEditor key)
{
HelpLineBehavior b = (HelpLineBehavior) behaviors[key];
if (b == null)
{
b = new HelpLineBehavior(key as IHtmlEditor, EnsurePropertiesExists(key), this);
behaviors[key] = b;
}
return b;
}
# region +++++ Block: HelpLine
/// <summary>
/// Fired if the mouse is released at the final position of the HelpLine.
/// </summary>
/// <remarks>
/// Normally this event is used to update an display which informs the user about the final position of the helpline.
/// </remarks>
[Category("NetRix Events"), Description("Fired if the mouse is released at the final position of the HelpLine.")]
public event HelpLineMoved HelpLineMoved;
/// <summary>
/// Fired during the helpline move at any mouse move step to update an display that shows the
/// current position of the HelpLine.
/// </summary>
[Category("NetRix Events"), Description("Fired during the helpline move at any mouse move.")]
public event HelpLineMoving HelpLineMoving;
/// <summary>
/// Method to fire the helpline moved event, if any handler is attached. This method
/// is called from the HelpLine designer host class if the user releases the mouse (mouse up)
/// and the HelpLine is fixed at the final position. The position is the EventArgs.
/// </summary>
/// <param name="htmlEditor"></param>
/// <param name="xy"></param>
internal void OnHelpLineMoved(IHtmlEditor htmlEditor, Point xy)
{
if (HelpLineMoved != null)
{
HelpLineMoved(htmlEditor, new HelplineMovedEventArgs(xy));
}
}
/// <summary>
/// Method to fire the helpline moving event, if any handler is attached. This method
/// is called from the HelpLine designer host class if the user moves the mouse and HelpLine.
/// </summary>
/// <param name="htmlEditor"></param>
/// <param name="xy"></param>
internal void OnHelpLineMoving(IHtmlEditor htmlEditor, Point xy)
{
if (HelpLineMoving != null)
{
HelpLineMoving(htmlEditor, new HelplineMovedEventArgs(xy));
}
}
/// <summary>
/// Support the extender infrastructure.
/// </summary>
/// <remarks>Should not be called directly from user code.</remarks>
/// <param name="htmlEditor"></param>
/// <returns></returns>
[ExtenderProvidedProperty(), Category("NetRix Component"), Description("HelpLine Properties")]
[TypeConverter(typeof(ExpandableObjectConverter))]
public HelpLineProperties GetHelpLine(IHtmlEditor htmlEditor)
{
return this.EnsurePropertiesExists(htmlEditor);
}
/// <summary>
/// Support the extender infrastructure.
/// </summary>
/// <remarks>Should not be called directly from user code.</remarks>
/// <param name="htmlEditor"></param>
/// <param name="Properties"></param>
public void SetHelpLine(IHtmlEditor htmlEditor, HelpLineProperties Properties)
{
EnsurePropertiesExists(htmlEditor).SetBehaviorReference(EnsureBehaviorExists(htmlEditor));
EnsurePropertiesExists(htmlEditor).Active = Properties.Active;
EnsurePropertiesExists(htmlEditor).LineColor = Properties.LineColor;
EnsurePropertiesExists(htmlEditor).LineWidth = Properties.LineWidth;
EnsurePropertiesExists(htmlEditor).CrossEnabled = Properties.CrossEnabled;
EnsurePropertiesExists(htmlEditor).LineVisible = Properties.LineVisible;
EnsurePropertiesExists(htmlEditor).LineXEnabled = Properties.LineXEnabled;
EnsurePropertiesExists(htmlEditor).LineYEnabled = Properties.LineYEnabled;
EnsurePropertiesExists(htmlEditor).SnapToGrid = Properties.SnapToGrid;
EnsurePropertiesExists(htmlEditor).SnapElements = Properties.SnapElements;
EnsurePropertiesExists(htmlEditor).SnapGrid = Properties.SnapGrid;
EnsurePropertiesExists(htmlEditor).SnapOnResize = Properties.SnapOnResize;
EnsurePropertiesExists(htmlEditor).SnapZone = Properties.SnapZone;
EnsurePropertiesExists(htmlEditor).X = Properties.X;
EnsurePropertiesExists(htmlEditor).Y = Properties.Y;
// Designer
htmlEditor.AddEditDesigner(EnsureBehaviorExists(htmlEditor) as Interop.IHTMLEditDesigner);
// activate behaviors when document is ready, otherwise it will fail
htmlEditor.BeforeSnapRect += new GuruComponents.Netrix.Events.BeforeSnapRectEventHandler(htmlEditor_BeforeSnapRect);
// Done register
htmlEditor.RegisterPlugIn(this);
}
private HelplineCommands commands;
/// <summary>
/// Returns the available commands.
/// </summary>
[Browsable(false)]
public HelplineCommands Commands
{
get
{
if (commands == null)
{
commands = new HelplineCommands();
}
return commands;
}
}
private void HelplineOperation(object sender, EventArgs e)
{
CommandWrapper cw = (CommandWrapper) sender;
if (cw.CommandID.Guid.Equals(Commands.CommandGroup))
{
switch ((HelplineCommand)cw.ID)
{
case HelplineCommand.Activate:
EnsureBehaviorExists(cw.TargetEditor).LineVisible = true;
break;
case HelplineCommand.Deactivate:
EnsureBehaviorExists(cw.TargetEditor).LineVisible = false;
break;
}
}
}
private void ActivateBehavior(IHtmlEditor htmlEditor)
{
if (htmlEditor == null) return;
IElement body = htmlEditor.GetBodyElement();
if (body != null)
{
body.ElementBehaviors.AddBehavior(EnsureBehaviorExists(htmlEditor));
}
}
/// <summary>
/// Removes the current behavior for the specified editor.
/// </summary>
/// <param name="htmlEditor">The editor the helpline is attached to.</param>
public void RemoveBehavior(IHtmlEditor htmlEditor)
{
if (htmlEditor == null) return;
IElement body = htmlEditor.GetBodyElement();
if (body != null)
{
body.ElementBehaviors.RemoveBehavior(EnsureBehaviorExists(htmlEditor));
}
}
/// <summary>
/// Current assembly version
/// </summary>
[Browsable(true), ReadOnly(true)]
public string Version
{
get
{
return this.GetType().Assembly.GetName().Version.ToString();
}
}
/// <summary>
/// Ensures properties and returns <c>true</c>.
/// </summary>
/// <param name="htmlEditor"></param>
/// <returns></returns>
public bool ShouldSerializeHelpLine(IHtmlEditor htmlEditor)
{
HelpLineProperties p = EnsurePropertiesExists(htmlEditor);
return true;
}
# endregion
#region IExtenderProvider Member
/// <summary>
/// Controls the behavior of the extender.
/// </summary>
/// <param name="extendee"></param>
/// <returns></returns>
public bool CanExtend(object extendee)
{
if (extendee is IHtmlEditor)
{
return true;
}
else
{
return false;
}
}
#endregion
/// <summary>
/// By calling this method the plugin gets notified that the control is ready.
/// </summary>
/// <remarks>Should not be called from user code.</remarks>
/// <param name="editor">Editor component reference.</param>
public void NotifyReadyStateCompleted(IHtmlEditor editor)
{
if (editor.DesignModeEnabled)
{
ActivateBehavior(editor);
// Commands
editor.AddCommand(new CommandWrapper(new EventHandler(HelplineOperation), Commands.Activate));
editor.AddCommand(new CommandWrapper(new EventHandler(HelplineOperation), Commands.Deactivate));
}
else
{
//RemoveBehavior(editor);
}
}
/// <summary>
/// Supports propertsgrid.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "Click + for details";
}
#region IPlugIn Member
/// <summary>
/// Name of Plug-in.
/// </summary>
public string Name
{
get
{
return "HelpLine";
}
}
/// <summary>
/// Indicates whether this is an extender.
/// </summary>
[Browsable(false)]
public bool IsExtenderProvider
{
get
{
return true;
}
}
/// <summary>
///
/// </summary>
[Browsable(false)]
public Type Type
{
get
{
return this.GetType();
}
}
/// <summary>
/// Editor features.
/// </summary>
[Browsable(false)]
Feature IPlugIn.Features
{
get { return Feature.None; }
}
/// <summary>
/// Returns supported namespaces.
/// </summary>
/// <remarks>This Plugin does not supprt namespaces and hence this method always returns <c>null</c>.
/// </remarks>
/// <param name="key">Editor component reference.</param>
/// <returns>Always returns <c>null</c>.</returns>
[Browsable(false)]
public IDictionary GetSupportedNamespaces(IHtmlEditor key)
{
return null;
}
System.Web.UI.Control IPlugIn.CreateElement(string tagName, IHtmlEditor editor)
{
throw new Exception("The method or operation is not available.");
}
/// <summary>
/// List of element types, which the extender plugin extends.
/// </summary>
/// <remarks>
/// See <see cref="GuruComponents.Netrix.PlugIns.CommandExtender">CommandExtender</see> for background information.
/// <para>
/// For this plugin the method always returns <c>null</c>.
/// </para>
/// </remarks>
public List<CommandExtender> GetElementExtenders(IElement component)
{
return null;
}
#endregion
private void htmlEditor_BeforeSnapRect(object sender, GuruComponents.Netrix.Events.BeforeSnapRectEventArgs e)
{
Rectangle r = e.Rectangle;
Snap.SnapRectToHelpLine(ref r, e.SnapZone, EnsurePropertiesExists(((IHtmlEditor)sender)), e.ScrollPos);
e.Rectangle = r;
}
}
}
| |
// 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 Internal.IL.Stubs;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public abstract partial class TypeSystemContext
{
private MethodDesc _objectEqualsMethod;
private class ValueTypeMethodHashtable : LockFreeReaderHashtable<DefType, MethodDesc>
{
protected override int GetKeyHashCode(DefType key) => key.GetHashCode();
protected override int GetValueHashCode(MethodDesc value) => value.OwningType.GetHashCode();
protected override bool CompareKeyToValue(DefType key, MethodDesc value) => key == value.OwningType;
protected override bool CompareValueToValue(MethodDesc v1, MethodDesc v2) => v1.OwningType == v2.OwningType;
protected override MethodDesc CreateValueFromKey(DefType key)
{
return new ValueTypeGetFieldHelperMethodOverride(key);
}
}
private ValueTypeMethodHashtable _valueTypeMethodHashtable = new ValueTypeMethodHashtable();
protected virtual IEnumerable<MethodDesc> GetAllMethodsForValueType(TypeDesc valueType)
{
TypeDesc valueTypeDefinition = valueType.GetTypeDefinition();
if (RequiresGetFieldHelperMethod((MetadataType)valueTypeDefinition))
{
MethodDesc getFieldHelperMethod = _valueTypeMethodHashtable.GetOrCreateValue((DefType)valueTypeDefinition);
if (valueType != valueTypeDefinition)
{
yield return GetMethodForInstantiatedType(getFieldHelperMethod, (InstantiatedType)valueType);
}
else
{
yield return getFieldHelperMethod;
}
}
foreach (MethodDesc method in valueType.GetMethods())
yield return method;
}
private bool RequiresGetFieldHelperMethod(MetadataType valueType)
{
if (_objectEqualsMethod == null)
_objectEqualsMethod = GetWellKnownType(WellKnownType.Object).GetMethod("Equals", null);
// If the classlib doesn't have Object.Equals, we don't need this.
if (_objectEqualsMethod == null)
return false;
// Byref-like valuetypes cannot be boxed.
if (valueType.IsByRefLike)
return false;
// Enums get their overrides from System.Enum.
if (valueType.IsEnum)
return false;
return !_typeStateHashtable.GetOrCreateValue(valueType).CanCompareValueTypeBits;
}
private class TypeState
{
private enum Flags
{
CanCompareValueTypeBits = 0x0000_0001,
CanCompareValueTypeBitsComputed = 0x0000_0002,
}
private volatile Flags _flags;
private readonly TypeStateHashtable _hashtable;
public TypeDesc Type { get; }
public bool CanCompareValueTypeBits
{
get
{
Flags flags = _flags;
if ((flags & Flags.CanCompareValueTypeBitsComputed) == 0)
{
Debug.Assert(Type.IsValueType);
if (ComputeCanCompareValueTypeBits((MetadataType)Type))
flags |= Flags.CanCompareValueTypeBits;
flags |= Flags.CanCompareValueTypeBitsComputed;
_flags = flags;
}
return (flags & Flags.CanCompareValueTypeBits) != 0;
}
}
public TypeState(TypeDesc type, TypeStateHashtable hashtable)
{
Type = type;
_hashtable = hashtable;
}
private bool ComputeCanCompareValueTypeBits(MetadataType type)
{
Debug.Assert(type.IsValueType);
if (type.ContainsGCPointers)
return false;
if (type.IsGenericDefinition)
return false;
OverlappingFieldTracker overlappingFieldTracker = new OverlappingFieldTracker(type);
bool result = true;
foreach (var field in type.GetFields())
{
if (field.IsStatic)
continue;
if (!overlappingFieldTracker.TrackField(field))
{
// This field overlaps with another field - can't compare memory
result = false;
break;
}
TypeDesc fieldType = field.FieldType;
if (fieldType.IsPrimitive || fieldType.IsEnum || fieldType.IsPointer || fieldType.IsFunctionPointer)
{
TypeFlags category = fieldType.UnderlyingType.Category;
if (category == TypeFlags.Single || category == TypeFlags.Double)
{
// Double/Single have weird behaviors around negative/positive zero
result = false;
break;
}
}
else
{
// Would be a suprise if this wasn't a valuetype. We checked ContainsGCPointers above.
Debug.Assert(fieldType.IsValueType);
MethodDesc objectEqualsMethod = fieldType.Context._objectEqualsMethod;
// If the field overrides Equals, we can't use the fast helper because we need to call the method.
if (fieldType.FindVirtualFunctionTargetMethodOnObjectType(objectEqualsMethod).OwningType == fieldType)
{
result = false;
break;
}
if (!_hashtable.GetOrCreateValue((MetadataType)fieldType).CanCompareValueTypeBits)
{
result = false;
break;
}
}
}
// If there are gaps, we can't memcompare
if (result && overlappingFieldTracker.HasGaps)
result = false;
return result;
}
}
private class TypeStateHashtable : LockFreeReaderHashtable<TypeDesc, TypeState>
{
protected override int GetKeyHashCode(TypeDesc key) => key.GetHashCode();
protected override int GetValueHashCode(TypeState value) => value.Type.GetHashCode();
protected override bool CompareKeyToValue(TypeDesc key, TypeState value) => key == value.Type;
protected override bool CompareValueToValue(TypeState v1, TypeState v2) => v1.Type == v2.Type;
protected override TypeState CreateValueFromKey(TypeDesc key)
{
return new TypeState(key, this);
}
}
private TypeStateHashtable _typeStateHashtable = new TypeStateHashtable();
private struct OverlappingFieldTracker
{
private bool[] _usedBytes;
public OverlappingFieldTracker(MetadataType type)
{
_usedBytes = new bool[type.InstanceFieldSize.AsInt];
}
public bool TrackField(FieldDesc field)
{
int fieldBegin = field.Offset.AsInt;
TypeDesc fieldType = field.FieldType;
int fieldEnd;
if (fieldType.IsPointer || fieldType.IsFunctionPointer)
{
fieldEnd = fieldBegin + field.Context.Target.PointerSize;
}
else
{
Debug.Assert(fieldType.IsValueType);
fieldEnd = fieldBegin + ((DefType)fieldType).InstanceFieldSize.AsInt;
}
for (int i = fieldBegin; i < fieldEnd; i++)
{
if (_usedBytes[i])
return false;
_usedBytes[i] = true;
}
return true;
}
public bool HasGaps
{
get
{
for (int i = 0; i < _usedBytes.Length; i++)
if (!_usedBytes[i])
return true;
return false;
}
}
}
}
}
| |
// GENERATED CODE ==> EDITS WILL BE LOST AFTER NEXT GENERATION!
// Version for Mac / UNIX
using UnityEngine;
namespace AnimatorAccess {
[Scio.CodeGeneration.GeneratedClassAttribute ("07/11/2014 15:16:18")]
/// <summary>
/// Convenience class to access Animator states and parameters.
/// Edits will be lost when this class is regenerated.
/// Hint: Editing might be useful after renaming animator items in complex projects:
/// - Right click on an obsolete member and select Refactor/Rename.
/// - Change it to the new name.
/// - Delete this member to avoid comile error CS0102 ... already contains a definition ...''.
/// </summary>
public class ExamplePlayerAnimatorAccess : BaseAnimatorAccess
{
/// <summary>
/// Hash of Animator state Base Layer.Walking
/// </summary>
public readonly int stateIdWalking = -2010423537;
/// <summary>
/// Hash of Animator state Base Layer.Idle
/// </summary>
public readonly int stateIdIdle = 1432961145;
/// <summary>
/// Hash of Animator state Base Layer.Yawning
/// </summary>
public readonly int stateIdYawning = -117804301;
/// <summary>
/// Hash of Animator state Base Layer.Jumping
/// </summary>
public readonly int stateIdJumping = -1407378526;
/// <summary>
/// Hash of Animator state Rot.Rotate-Left
/// </summary>
public readonly int stateIdRot_Rotate_Left = -1817809755;
/// <summary>
/// Hash of Animator state Rot.Rotate-Right
/// </summary>
public readonly int stateIdRot_Rotate_Right = 1375079058;
/// <summary>
/// Hash of Animator state Rot.Centered
/// </summary>
public readonly int stateIdRot_Centered = -1799351532;
/// <summary>
/// Hash of parameter Speed
/// </summary>
public readonly int paramIdSpeed = -823668238;
/// <summary>
/// Hash of parameter JumpTrigger
/// </summary>
public readonly int paramIdJumpTrigger = 113680519;
/// <summary>
/// Hash of parameter YawnTrigger
/// </summary>
public readonly int paramIdYawnTrigger = 1330169897;
/// <summary>
/// Hash of parameter Rotate
/// </summary>
public readonly int paramIdRotate = 807753530;
public override int AllTransitionsHash {
get{ return 859155473; }
}
public void Awake () {
animator = GetComponent<Animator> ();
}
public override void InitialiseEventManager () {
StateInfos.Add (-2010423537, new StateInfo (-2010423537, 0, "Base Layer", "Base Layer.Walking", "", 1f, false, false, "Walk", 1.208333f));
StateInfos.Add (1432961145, new StateInfo (1432961145, 0, "Base Layer", "Base Layer.Idle", "", 1f, false, false, "Idle", 2.708333f));
StateInfos.Add (-117804301, new StateInfo (-117804301, 0, "Base Layer", "Base Layer.Yawning", "", 1f, false, false, "Yawn", 2.291667f));
StateInfos.Add (-1407378526, new StateInfo (-1407378526, 0, "Base Layer", "Base Layer.Jumping", "", 1f, false, false, "Jump", 0.7916667f));
StateInfos.Add (-1817809755, new StateInfo (-1817809755, 1, "Rot", "Rot.Rotate-Left", "", 1f, false, false, "Rotate-Left", 0.1666667f));
StateInfos.Add (1375079058, new StateInfo (1375079058, 1, "Rot", "Rot.Rotate-Right", "", 1f, false, false, "Rotate-Right", 0.1666667f));
StateInfos.Add (-1799351532, new StateInfo (-1799351532, 1, "Rot", "Rot.Centered", "", 1f, false, false, "Centered", 0.1666667f));
TransitionInfos.Add (708569559, new TransitionInfo (708569559, "Base Layer.Walking -> Base Layer.Idle", 0, "Base Layer", -2010423537, 1432961145, true, 0.2068965f, false, 0f, false));
TransitionInfos.Add (-2057610033, new TransitionInfo (-2057610033, "Base Layer.Walking -> Base Layer.Jumping", 0, "Base Layer", -2010423537, -1407378526, true, 0.2068965f, false, 0f, false));
TransitionInfos.Add (856518066, new TransitionInfo (856518066, "Base Layer.Idle -> Base Layer.Walking", 0, "Base Layer", 1432961145, -2010423537, true, 0.09230769f, false, 0f, false));
TransitionInfos.Add (1138507854, new TransitionInfo (1138507854, "Base Layer.Idle -> Base Layer.Yawning", 0, "Base Layer", 1432961145, -117804301, true, 0.09230769f, false, 0f, false));
TransitionInfos.Add (389753119, new TransitionInfo (389753119, "Base Layer.Idle -> Base Layer.Jumping", 0, "Base Layer", 1432961145, -1407378526, true, 0.09230769f, false, 0f, false));
TransitionInfos.Add (781957174, new TransitionInfo (781957174, "Base Layer.Yawning -> Base Layer.Idle", 0, "Base Layer", -117804301, 1432961145, true, 0.1090909f, false, 0f, false));
TransitionInfos.Add (1298684863, new TransitionInfo (1298684863, "Base Layer.Jumping -> Base Layer.Idle", 0, "Base Layer", -1407378526, 1432961145, true, 0.3157895f, false, 0f, false));
TransitionInfos.Add (-1019719959, new TransitionInfo (-1019719959, "Base Layer.Jumping -> Base Layer.Walking", 0, "Base Layer", -1407378526, -2010423537, true, 0.3157895f, false, 0f, false));
TransitionInfos.Add (796133751, new TransitionInfo (796133751, "Rot.Rotate-Left -> Rot.Rotate-Right", 1, "Rot", -1817809755, 1375079058, true, 0.75f, false, 0f, false));
TransitionInfos.Add (-1706334441, new TransitionInfo (-1706334441, "Rot.Rotate-Left -> Rot.Centered", 1, "Rot", -1817809755, -1799351532, false, 0.4559997f, false, 0f, false));
TransitionInfos.Add (-1985854260, new TransitionInfo (-1985854260, "Rot.Rotate-Right -> Rot.Rotate-Left", 1, "Rot", 1375079058, -1817809755, true, 0.75f, false, 0f, false));
TransitionInfos.Add (-1394703878, new TransitionInfo (-1394703878, "Rot.Rotate-Right -> Rot.Centered", 1, "Rot", 1375079058, -1799351532, false, 0.2279998f, false, 0f, false));
TransitionInfos.Add (699184725, new TransitionInfo (699184725, "Rot.Centered -> Rot.Rotate-Right", 1, "Rot", -1799351532, 1375079058, true, 0.7415018f, false, 0.001918154f, false));
TransitionInfos.Add (-825030163, new TransitionInfo (-825030163, "Rot.Centered -> Rot.Rotate-Left", 1, "Rot", -1799351532, -1817809755, true, 0.25f, false, 0f, false));
}
/// <summary>
/// true if the current Animator state of layer 0 is "Base Layer.Walking".
/// </summary>
public bool IsWalking () {
return stateIdWalking == animator.GetCurrentAnimatorStateInfo (0).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Base Layer.Walking").
/// </summary>
public bool IsWalking (int nameHash) {
return nameHash == stateIdWalking;
}
/// <summary>
/// true if the current Animator state of layer 0 is "Base Layer.Idle".
/// </summary>
public bool IsIdle () {
return stateIdIdle == animator.GetCurrentAnimatorStateInfo (0).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Base Layer.Idle").
/// </summary>
public bool IsIdle (int nameHash) {
return nameHash == stateIdIdle;
}
/// <summary>
/// true if the current Animator state of layer 0 is "Base Layer.Yawning".
/// </summary>
public bool IsYawning () {
return stateIdYawning == animator.GetCurrentAnimatorStateInfo (0).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Base Layer.Yawning").
/// </summary>
public bool IsYawning (int nameHash) {
return nameHash == stateIdYawning;
}
/// <summary>
/// true if the current Animator state of layer 0 is "Base Layer.Jumping".
/// </summary>
public bool IsJumping () {
return stateIdJumping == animator.GetCurrentAnimatorStateInfo (0).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Base Layer.Jumping").
/// </summary>
public bool IsJumping (int nameHash) {
return nameHash == stateIdJumping;
}
/// <summary>
/// true if the current Animator state of layer 1 is "Rot.Rotate-Left".
/// </summary>
public bool IsRot_Rotate_Left () {
return stateIdRot_Rotate_Left == animator.GetCurrentAnimatorStateInfo (1).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Rot.Rotate-Left").
/// </summary>
public bool IsRot_Rotate_Left (int nameHash) {
return nameHash == stateIdRot_Rotate_Left;
}
/// <summary>
/// true if the current Animator state of layer 1 is "Rot.Rotate-Right".
/// </summary>
public bool IsRot_Rotate_Right () {
return stateIdRot_Rotate_Right == animator.GetCurrentAnimatorStateInfo (1).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Rot.Rotate-Right").
/// </summary>
public bool IsRot_Rotate_Right (int nameHash) {
return nameHash == stateIdRot_Rotate_Right;
}
/// <summary>
/// true if the current Animator state of layer 1 is "Rot.Centered".
/// </summary>
public bool IsRot_Centered () {
return stateIdRot_Centered == animator.GetCurrentAnimatorStateInfo (1).nameHash;
}
/// <summary>
/// true if the given (state) nameHash equals Animator.StringToHash ("Rot.Centered").
/// </summary>
public bool IsRot_Centered (int nameHash) {
return nameHash == stateIdRot_Centered;
}
/// <summary>
/// Set float parameter of Speed using damp and delta time .
/// <param name="newValue">New value for float parameter Speed.</param>
/// <param name="dampTime">The time allowed to parameter Speed to reach the value.</param>
/// <param name="deltaTime">The current frame deltaTime.</param>
/// </summary>
public void SetSpeed (float newValue, float dampTime, float deltaTime) {
animator.SetFloat (paramIdSpeed, newValue, dampTime, deltaTime);
}
/// <summary>
/// Set float value of parameter Speed.
/// <param name="newValue">New value for float parameter Speed.</param>
/// </summary>
public void SetSpeed (float newValue) {
animator.SetFloat (paramIdSpeed, newValue);
}
/// <summary>
/// Access to float parameter Speed, default is: 0.
/// </summary>
public float GetSpeed () {
return animator.GetFloat (paramIdSpeed);
}
/// <summary>
/// Activate trigger of parameter JumpTrigger.
/// </summary>
public void SetJumpTrigger () {
animator.SetTrigger (paramIdJumpTrigger);
}
/// <summary>
/// Activate trigger of parameter YawnTrigger.
/// </summary>
public void SetYawnTrigger () {
animator.SetTrigger (paramIdYawnTrigger);
}
/// <summary>
/// Set integer value of parameter Rotate.
/// <param name="newValue">New value for integer parameter Rotate.</param>
/// </summary>
public void SetRotate (int newValue) {
animator.SetInteger (paramIdRotate, newValue);
}
/// <summary>
/// Access to integer parameter Rotate, default is: 1.
/// </summary>
public int GetRotate () {
return animator.GetInteger (paramIdRotate);
}
private void FixedUpdate () {
CheckForAnimatorStateChanges ();
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using Rotorz.Games.UnityEditorExtensions;
using Rotorz.Settings;
using Rotorz.Tile.Internal;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Rotorz.Tile.Editor
{
/// <summary>
/// Custom inspector for tile system.
/// </summary>
/// <remarks>
/// <para>This class is automatically instantiated by <see cref="TileSystemEditor"/> when
/// inspector GUI is first drawn.</para>
/// </remarks>
/// <seealso cref="TileSystemEditor"/>
internal sealed class TileSystemInspector
{
#region Editor Preferences
static TileSystemInspector()
{
var settings = AssetSettingManagement.GetGroup("Inspector.TileSystem");
s_setting_ToggleModifyGrid = settings.Fetch<bool>("ExpandModifyGrid", true);
s_setting_ToggleStripping = settings.Fetch<bool>("ExpandStripping", false);
s_setting_ToggleBuildOptions = settings.Fetch<bool>("ExpandBuildOptions", false);
s_setting_ToggleRuntimeOptions = settings.Fetch<bool>("ExpandRuntimeOptions", false);
}
private static readonly Setting<bool> s_setting_ToggleModifyGrid;
private static readonly Setting<bool> s_setting_ToggleStripping;
private static readonly Setting<bool> s_setting_ToggleBuildOptions;
private static readonly Setting<bool> s_setting_ToggleRuntimeOptions;
private static bool s_ToggleBuildOptions_AdvancedUV2;
#endregion
/// <summary>
/// The parent <see cref="TileSystemEditor"/> instances which controls the behaviour
/// of this inspector instance.
/// </summary>
private readonly TileSystemEditor parent;
/// <summary>
/// Gets the serialized object.
/// </summary>
private SerializedObject serializedObject {
get { return this.parent.serializedObject; }
}
/// <summary>
/// Gets array of objects that are targeted by this inspector.
/// </summary>
private Object[] targets {
get { return this.parent.targets; }
}
/// <summary>
/// Gets the active tile system that is targeted by this inspector.
/// </summary>
private TileSystem target {
get { return this.parent.target as TileSystem; }
}
/// <summary>
/// Initialize new <see cref="TileSystemInspector"/> instance.
/// </summary>
/// <param name="parent">The parent editor.</param>
public TileSystemInspector(TileSystemEditor parent)
{
this.parent = parent;
this.InitModifyGridSection();
this.InitStrippingSection();
this.InitBuildOptionsSection();
this.InitRuntimeOptionsSection();
}
/// <summary>
/// Handles GUI events for inspector.
/// </summary>
public void OnGUI()
{
float initialLabelWidth = EditorGUIUtility.labelWidth;
RotorzEditorGUI.UseExtendedLabelWidthForLocalization();
bool formerAddNormals = this.target.addProceduralNormals;
this.serializedObject.Update();
GUILayout.Space(6);
this.DrawToolbar();
GUILayout.Space(6);
if (!this.target.IsEditable) {
EditorGUILayout.HelpBox(TileLang.Text("Tile system has been built and can no longer be edited."), MessageType.Info, true);
return;
}
// Display message if any of the target tile systems are locked.
foreach (TileSystem tileSystem in this.targets) {
if (tileSystem.Locked) {
string message = this.targets.Length == 1
? TileLang.Text("Tile system is locked. Select 'Toggle Lock' from context menu to unlock inspector.")
: TileLang.Text("One or more selected tile systems are locked. Unlock tile systems to unlock inspector.");
EditorGUILayout.HelpBox(message, MessageType.Info, true);
return;
}
}
s_setting_ToggleModifyGrid.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleModifyGrid,
label: TileLang.ParticularText("Section", "Modify Grid"),
callback: this.DrawModifyGridSection,
paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
);
s_setting_ToggleStripping.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleStripping,
label: TileLang.ParticularText("Section", "Stripping"),
callback: this.DrawStrippingSection,
paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
);
s_setting_ToggleBuildOptions.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleBuildOptions,
label: TileLang.ParticularText("Section", "Build Options"),
callback: this.DrawBuildOptionsSection,
paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
);
s_setting_ToggleRuntimeOptions.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleRuntimeOptions,
label: TileLang.ParticularText("Section", "Runtime Options"),
callback: this.DrawRuntimeOptionsSection,
paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
);
// Ensure that changes are saved.
if (GUI.changed) {
EditorUtility.SetDirty(this.target);
this.serializedObject.ApplyModifiedProperties();
if (formerAddNormals != this.target.addProceduralNormals) {
this.target.UpdateProceduralTiles(true);
}
}
EditorGUIUtility.labelWidth = initialLabelWidth;
}
#region Section: Modify Grid
private SerializedProperty propertyCellSize;
private SerializedProperty propertyTilesFacing;
private SerializedProperty propertyHintForceRefresh;
private void InitModifyGridSection()
{
this.propertyCellSize = this.serializedObject.FindProperty("cellSize");
this.propertyTilesFacing = this.serializedObject.FindProperty("tilesFacing");
this.propertyHintForceRefresh = this.serializedObject.FindProperty("hintForceRefresh");
this.RefreshModifyGridParamsFromTileSystem();
}
private int inputNewRows;
private int inputNewColumns;
private int inputRowOffset;
private int inputColumnOffset;
private int inputNewChunkWidth;
private int inputNewChunkHeight;
private bool inputMaintainTilePositionsInWorldResize;
private bool inputMaintainTilePositionsInWorldOffset;
private static GUIStyle s_ModifyGridGroupStyle;
private void DrawModifyGridSection()
{
if (this.targets.Length > 1) {
EditorGUILayout.HelpBox(TileLang.Text("Cannot modify structure of multiple tile systems at the same time."), MessageType.Info);
return;
}
var tileSystem = this.target as TileSystem;
if (PrefabUtility.GetPrefabType(tileSystem) == PrefabType.Prefab) {
EditorGUILayout.HelpBox(TileLang.Text("Prefab must be instantiated in order to modify tile system structure."), MessageType.Info);
return;
}
float restoreLabelWidth = EditorGUIUtility.labelWidth;
bool hasGridSizeChanged;
bool hasOffsetChanged;
if (s_ModifyGridGroupStyle == null) {
s_ModifyGridGroupStyle = new GUIStyle();
s_ModifyGridGroupStyle.margin.right = 55;
}
Rect modifyGroupRect = EditorGUILayout.BeginVertical(s_ModifyGridGroupStyle);
{
ExtraEditorGUI.MultiPartPrefixLabel(TileLang.ParticularText("Property", "Grid Size (in tiles)"));
GUILayout.BeginHorizontal();
{
GUILayout.Space(18);
EditorGUIUtility.labelWidth = 65;
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Rows"));
this.inputNewRows = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewRows));
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Columns"));
this.inputNewColumns = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewColumns));
EditorGUIUtility.labelWidth = restoreLabelWidth;
}
GUILayout.EndHorizontal();
ExtraEditorGUI.MultiPartPrefixLabel(TileLang.ParticularText("Property", "Offset Amount (in tiles)"));
GUILayout.BeginHorizontal();
{
GUILayout.Space(18);
EditorGUIUtility.labelWidth = 65;
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Rows"));
this.inputRowOffset = EditorGUILayout.IntField(this.inputRowOffset);
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Columns"));
this.inputColumnOffset = EditorGUILayout.IntField(this.inputColumnOffset);
EditorGUIUtility.labelWidth = restoreLabelWidth;
}
GUILayout.EndHorizontal();
hasGridSizeChanged = (this.inputNewRows != tileSystem.RowCount || this.inputNewColumns != tileSystem.ColumnCount);
hasOffsetChanged = (this.inputRowOffset != 0 || this.inputColumnOffset != 0);
if (hasGridSizeChanged) {
this.DrawMaintainTilePositionsInWorld(ref this.inputMaintainTilePositionsInWorldResize);
}
else if (hasOffsetChanged) {
this.DrawMaintainTilePositionsInWorld(ref this.inputMaintainTilePositionsInWorldOffset);
}
EditorGUIUtility.labelWidth = restoreLabelWidth;
ExtraEditorGUI.MultiPartPrefixLabel(TileLang.ParticularText("Property", "Chunk Size (in tiles)"));
GUILayout.BeginHorizontal();
{
GUILayout.Space(18);
EditorGUIUtility.labelWidth = 65;
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height"));
this.inputNewChunkHeight = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewChunkHeight));
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width"));
this.inputNewChunkWidth = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewChunkWidth));
EditorGUIUtility.labelWidth = restoreLabelWidth;
}
GUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
Rect buttonRect = new Rect(modifyGroupRect.xMax + 5, modifyGroupRect.y + 3, 45, 35);
using (var content = ControlContent.Basic(
RotorzEditorStyles.Skin.Trim,
TileLang.ParticularText("Action", "Trim")
)) {
if (GUI.Button(buttonRect, content)) {
this.OnTrimTileSystem();
GUIUtility.ExitGUI();
}
}
buttonRect.y = buttonRect.yMax + 3;
EditorGUI.BeginDisabledGroup(!hasGridSizeChanged);
{
using (var content = ControlContent.Basic(
RotorzEditorStyles.Skin.CentralizeUsed,
TileLang.ParticularText("Action", "Centralize Tile Bounds")
)) {
if (GUI.Button(buttonRect, content)) {
this.OnCentralizeUsedTileSystem();
GUIUtility.ExitGUI();
}
}
buttonRect.y = buttonRect.yMax + 3;
using (var content = ControlContent.Basic(
RotorzEditorStyles.Skin.Centralize,
TileLang.ParticularText("Action", "Centralize")
)) {
if (GUI.Button(buttonRect, content)) {
this.OnCentralizeTileSystem();
GUIUtility.ExitGUI();
}
}
}
EditorGUI.EndDisabledGroup();
bool hasChunkSizeChanged = (this.inputNewChunkWidth != tileSystem.ChunkWidth || this.inputNewChunkHeight != tileSystem.ChunkHeight);
// Display "Rebuild" button?
if (hasGridSizeChanged || hasOffsetChanged || hasChunkSizeChanged) {
GUILayout.Space(6);
GUILayout.BeginHorizontal();
{
EditorGUILayout.HelpBox(TileLang.Text("Tile system must be reconstructed, some tiles may be force refreshed."), MessageType.Warning);
if (GUILayout.Button(TileLang.ParticularText("Action", "Rebuild"), GUILayout.Width(75), GUILayout.Height(40))) {
GUIUtility.keyboardControl = 0;
this.OnResizeTileSystem();
GUIUtility.ExitGUI();
}
if (GUILayout.Button(TileLang.ParticularText("Action", "Cancel"), GUILayout.Width(75), GUILayout.Height(40))) {
GUIUtility.keyboardControl = 0;
this.RefreshModifyGridParamsFromTileSystem();
GUIUtility.ExitGUI();
}
}
GUILayout.EndHorizontal();
GUILayout.Space(2);
}
ExtraEditorGUI.SeparatorLight();
using (var content = ControlContent.Basic(
TileLang.ParticularText("Property", "Cell Size"),
TileLang.Text("Span of an individual tile.")
)) {
Vector3 newCellSize = Vector3.Max(new Vector3(0.0001f, 0.0001f, 0.0001f), EditorGUILayout.Vector3Field(content, tileSystem.CellSize));
if (tileSystem.CellSize != newCellSize) {
this.propertyCellSize.vector3Value = newCellSize;
this.propertyHintForceRefresh.boolValue = true;
}
}
GUILayout.Space(5);
using (var content = ControlContent.Basic(
TileLang.ParticularText("Property", "Tiles Facing"),
TileLang.Text("Direction that tiles will face when painted. 'Sideways' is good for platform and 2D games. 'Upwards' is good for top-down.")
)) {
TileFacing newTilesFacing = (TileFacing)EditorGUILayout.EnumPopup(content, tileSystem.TilesFacing);
if (tileSystem.TilesFacing != newTilesFacing) {
this.propertyTilesFacing.intValue = (int)newTilesFacing;
this.propertyHintForceRefresh.boolValue = true;
}
}
GUILayout.Space(5);
// Display suitable warning message when force refresh is required.
if (this.propertyHintForceRefresh.boolValue) {
if (!RotorzEditorGUI.InfoBoxClosable(TileLang.Text("Changes may not take effect until tile system is force refreshed without preserving manual offsets, or cleared."), MessageType.Warning)) {
this.propertyHintForceRefresh.boolValue = false;
this.serializedObject.ApplyModifiedProperties();
GUIUtility.ExitGUI();
}
}
else {
ExtraEditorGUI.SeparatorLight(marginTop: 0, marginBottom: 0, thickness: 1);
}
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
// Display extra padding to right of buttons to avoid accidental click when
// clicking close button of warning message.
GUILayoutOption columnWidth = GUILayout.Width((EditorGUIUtility.currentViewWidth - 30) / 3 - GUI.skin.button.margin.horizontal);
GUILayout.BeginVertical(columnWidth);
if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Refresh")))) {
TileSystemCommands.Command_Refresh(this.target);
GUIUtility.ExitGUI();
}
GUILayout.Space(2);
if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Refresh Plops")))) {
TileSystemCommands.Command_RefreshPlops(this.target);
GUIUtility.ExitGUI();
}
GUILayout.EndVertical();
GUILayout.BeginVertical(columnWidth);
if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Repair")))) {
TileSystemCommands.Command_Repair(this.target);
GUIUtility.ExitGUI();
}
GUILayout.Space(2);
if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Clear Plops")))) {
TileSystemCommands.Command_ClearPlops(this.target);
GUIUtility.ExitGUI();
}
GUILayout.EndVertical();
GUILayout.BeginVertical(columnWidth);
if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Clear")))) {
TileSystemCommands.Command_Clear(this.target);
GUIUtility.ExitGUI();
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
}
private void DrawMaintainTilePositionsInWorld(ref bool flag)
{
++EditorGUI.indentLevel;
// "Maintain tile positions in world space"
using (var content = ControlContent.Basic(TileLang.ParticularText("Property", "Maintain tile positions in world space"))) {
flag = EditorGUILayout.ToggleLeft(content, flag);
}
--EditorGUI.indentLevel;
}
private void RefreshModifyGridParamsFromTileSystem()
{
var tileSystem = this.target;
this.inputNewRows = tileSystem.RowCount;
this.inputNewColumns = tileSystem.ColumnCount;
this.inputRowOffset = this.inputColumnOffset = 0;
this.inputMaintainTilePositionsInWorldResize = true;
this.inputMaintainTilePositionsInWorldOffset = false;
this.inputNewChunkWidth = tileSystem.ChunkWidth;
this.inputNewChunkHeight = tileSystem.ChunkHeight;
}
private void OnResizeTileSystem()
{
var tileSystem = this.target as TileSystem;
bool eraseOutOfBounds = false;
// Display suitable warning message to user if resized tile
// system will cause out-of-bound tiles to be erased.
if (TileSystemUtility.WillHaveOutOfBoundTiles(tileSystem, this.inputNewRows, this.inputNewColumns, this.inputRowOffset, this.inputColumnOffset)) {
if (!EditorUtility.DisplayDialog(
TileLang.ParticularText("Action", "Rebuild Tile System"),
TileLang.Text("Upon modifying tile system some tiles will become out-of-bounds and will be erased.\n\nWould you like to proceed?"),
TileLang.ParticularText("Action", "Yes"),
TileLang.ParticularText("Action", "No")
)) {
return;
}
eraseOutOfBounds = true;
}
Undo.RegisterFullObjectHierarchyUndo(tileSystem.gameObject, TileLang.ParticularText("Action", "Rebuild Tile System"));
bool maintainFlag = (this.inputNewRows != tileSystem.RowCount || this.inputNewColumns != tileSystem.ColumnCount)
? this.inputMaintainTilePositionsInWorldResize
: this.inputMaintainTilePositionsInWorldOffset;
var resizer = new TileSystemResizer();
resizer.Resize(tileSystem, this.inputNewRows, this.inputNewColumns, this.inputRowOffset, this.inputColumnOffset, this.inputNewChunkWidth, this.inputNewChunkHeight, maintainFlag, eraseOutOfBounds);
// Refresh "Modify Grid" parameters from new state of tile system.
this.RefreshModifyGridParamsFromTileSystem();
SceneView.RepaintAll();
}
private void OnTrimTileSystem()
{
TileIndex min, max;
GUIUtility.keyboardControl = 0;
this.inputMaintainTilePositionsInWorldResize = true;
// Bail if invalid range was encountered.
if (!TileSystemUtility.FindTileBounds(this.target, out min, out max)) {
this.inputNewRows = this.target.RowCount;
this.inputNewColumns = this.target.ColumnCount;
this.inputRowOffset = 0;
this.inputColumnOffset = 0;
return;
}
++max.row;
++max.column;
this.inputRowOffset = -min.row;
this.inputColumnOffset = -min.column;
this.inputNewRows = max.row - min.row;
this.inputNewColumns = max.column - min.column;
}
private void OnCentralizeUsedTileSystem()
{
TileIndex min, max;
GUIUtility.keyboardControl = 0;
this.inputMaintainTilePositionsInWorldResize = true;
// Bail if invalid range was encountered.
if (!TileSystemUtility.FindTileBounds(this.target, out min, out max)) {
this.inputRowOffset = 0;
this.inputColumnOffset = 0;
return;
}
++max.row;
++max.column;
int boundRows = max.row - min.row;
int boundColumns = max.column - min.column;
this.inputRowOffset = -(min.row - (this.inputNewRows - boundRows) / 2);
this.inputColumnOffset = -(min.column - (this.inputNewColumns - boundColumns) / 2);
}
private void OnCentralizeTileSystem()
{
GUIUtility.keyboardControl = 0;
this.inputMaintainTilePositionsInWorldResize = true;
this.inputRowOffset = -(0 - (this.inputNewRows - this.target.RowCount) / 2);
this.inputColumnOffset = -(0 - (this.inputNewColumns - this.target.ColumnCount) / 2);
}
#endregion
#region Section: Stripping Options
private SerializedProperty propertyStrippingPreset;
private SerializedProperty propertyStrippingOptionMask;
private void InitStrippingSection()
{
this.propertyStrippingPreset = this.serializedObject.FindProperty("strippingPreset");
this.propertyStrippingOptionMask = this.serializedObject.FindProperty("strippingOptionMask");
}
private void DrawStrippingSection()
{
// "Stripping Preset"
using (var content = ControlContent.Basic(
TileLang.ParticularText("Property", "Stripping Preset"),
TileLang.Text("Custom level of stripping can be applied to tile system upon build.")
)) {
EditorGUILayout.PropertyField(this.propertyStrippingPreset, content);
}
// "Stripping Preset Toggles"
if (!this.propertyStrippingPreset.hasMultipleDifferentValues) {
var targetSystems = this.targets.Cast<TileSystem>().ToArray();
int mixedMask = RotorzEditorGUI.GetMixedStrippingOptionsMask(targetSystems);
StrippingPreset preset = targetSystems[0].StrippingPreset;
int options = targetSystems[0].StrippingOptions & ~mixedMask;
EditorGUI.showMixedValue = this.propertyStrippingOptionMask.hasMultipleDifferentValues;
int diff = RotorzEditorGUI.StrippingOptions(preset, options, mixedMask);
if (diff != 0 && preset == StrippingPreset.Custom) {
int addBits = diff & ~options;
int removeBits = diff & options;
Undo.RecordObjects(this.targets, TileLang.ParticularText("Action", "Modify Stripping Options"));
foreach (var tileSystem in targetSystems) {
tileSystem.StrippingOptions = (tileSystem.StrippingOptions & ~removeBits) | addBits;
EditorUtility.SetDirty(tileSystem);
}
}
EditorGUI.showMixedValue = false;
}
GUILayout.Space(5);
}
#endregion
#region Section: Build Options
private SerializedProperty propertyCombineMethod;
private SerializedProperty propertyCombineChunkWidth;
private SerializedProperty propertyCombineChunkHeight;
private SerializedProperty propertyCombineIntoSubmeshes;
private SerializedProperty propertyVertexSnapThreshold;
private SerializedProperty propertyStaticSnapping;
private SerializedProperty propertyGenerateSecondUVs;
private SerializedProperty propertyGenerateSecondUVsHardAngle;
private SerializedProperty propertyGenerateSecondUVsPackMargin;
private SerializedProperty propertyGenerateSecondUVsAngleError;
private SerializedProperty propertyGenerateSecondUVsAreaError;
private SerializedProperty propertyPregenerateProcedural;
private SerializedProperty propertyReduceColliders;
private void InitBuildOptionsSection()
{
this.propertyCombineMethod = this.serializedObject.FindProperty("combineMethod");
this.propertyCombineChunkWidth = this.serializedObject.FindProperty("combineChunkWidth");
this.propertyCombineChunkHeight = this.serializedObject.FindProperty("combineChunkHeight");
this.propertyCombineIntoSubmeshes = this.serializedObject.FindProperty("combineIntoSubmeshes");
this.propertyVertexSnapThreshold = this.serializedObject.FindProperty("vertexSnapThreshold");
this.propertyStaticSnapping = this.serializedObject.FindProperty("staticVertexSnapping");
this.propertyGenerateSecondUVs = this.serializedObject.FindProperty("generateSecondUVs");
this.propertyGenerateSecondUVsHardAngle = this.serializedObject.FindProperty("generateSecondUVsHardAngle");
this.propertyGenerateSecondUVsPackMargin = this.serializedObject.FindProperty("generateSecondUVsPackMargin");
this.propertyGenerateSecondUVsAngleError = this.serializedObject.FindProperty("generateSecondUVsAngleError");
this.propertyGenerateSecondUVsAreaError = this.serializedObject.FindProperty("generateSecondUVsAreaError");
this.propertyPregenerateProcedural = this.serializedObject.FindProperty("pregenerateProcedural");
this.propertyReduceColliders = this.serializedObject.FindProperty("reduceColliders");
}
private void DrawBuildOptionsSection()
{
var tileSystem = this.target as TileSystem;
using (var content = ControlContent.Basic(
TileLang.ParticularText("Property", "Combine Method")
)) {
EditorGUILayout.PropertyField(this.propertyCombineMethod, content);
if (!this.propertyCombineMethod.hasMultipleDifferentValues) {
if (tileSystem.combineMethod == BuildCombineMethod.CustomChunkInTiles) {
GUILayout.BeginHorizontal();
++EditorGUI.indentLevel;
EditorGUIUtility.labelWidth = 65;
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height"));
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(this.propertyCombineChunkHeight, GUIContent.none);
if (EditorGUI.EndChangeCheck()) {
this.propertyCombineChunkHeight.intValue = Mathf.Max(1, this.propertyCombineChunkHeight.intValue);
}
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width"));
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(this.propertyCombineChunkWidth, GUIContent.none);
if (EditorGUI.EndChangeCheck()) {
this.propertyCombineChunkWidth.intValue = Mathf.Max(1, this.propertyCombineChunkWidth.intValue);
}
EditorGUIUtility.labelWidth = 0;
--EditorGUI.indentLevel;
GUILayout.EndHorizontal();
}
if (tileSystem.combineMethod != BuildCombineMethod.None) {
++EditorGUI.indentLevel;
{
using (var content2 = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Combine into submeshes"),
TileLang.Text("Determines whether to use submeshes, or an individual mesh for each material.")
)) {
ExtraEditorGUI.ToggleLeft(this.propertyCombineIntoSubmeshes, content2);
ExtraEditorGUI.TrailingTip(content2);
}
}
--EditorGUI.indentLevel;
RotorzEditorGUI.InfoBox(TileLang.Text("Avoid generation of meshes with vertices in excess of 64k."), MessageType.Warning);
}
}
}
EditorGUILayout.Space();
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Vertex Snap Threshold"),
TileLang.Text("Increase threshold to snap vertices that are more widely spread.")
)) {
EditorGUILayout.PropertyField(this.propertyVertexSnapThreshold, content);
if (!this.propertyVertexSnapThreshold.hasMultipleDifferentValues) {
if (this.propertyVertexSnapThreshold.floatValue == 0f) {
EditorGUILayout.HelpBox(TileLang.Text("No snapping occurs when threshold is 0."), MessageType.Warning, true);
}
}
ExtraEditorGUI.TrailingTip(content);
}
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Static Snapping"),
TileLang.Text("Applies vertex snapping to static tiles to avoid tiny gaps due to numerical inaccuracies. Vertex snapping is always applied to 'smooth' tiles.")
)) {
EditorGUILayout.PropertyField(this.propertyStaticSnapping, content);
ExtraEditorGUI.TrailingTip(content);
}
using (var content = ControlContent.Basic(
TileLang.ParticularText("Property", "Generate Lightmap UVs")
)) {
EditorGUILayout.PropertyField(this.propertyGenerateSecondUVs, content);
if (this.propertyGenerateSecondUVs.boolValue) {
++EditorGUI.indentLevel;
s_ToggleBuildOptions_AdvancedUV2 = EditorGUILayout.Foldout(s_ToggleBuildOptions_AdvancedUV2, TileLang.ParticularText("Section", "Advanced"));
if (s_ToggleBuildOptions_AdvancedUV2) {
float hardAngle = this.propertyGenerateSecondUVsHardAngle.floatValue;
float packMargin = this.propertyGenerateSecondUVsPackMargin.floatValue * 1024f;
float angleError = this.propertyGenerateSecondUVsAngleError.floatValue * 100f;
float areaError = this.propertyGenerateSecondUVsAreaError.floatValue * 100f;
using (var content2 = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Hard Angle"),
TileLang.Text("Angle between neighbor triangles that will generate seam.")
)) {
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = this.propertyGenerateSecondUVsHardAngle.hasMultipleDifferentValues;
hardAngle = EditorGUILayout.Slider(content2, hardAngle, 0f, 180f);
if (EditorGUI.EndChangeCheck()) {
this.propertyGenerateSecondUVsHardAngle.floatValue = Mathf.Ceil(hardAngle);
}
ExtraEditorGUI.TrailingTip(content2);
}
using (var content2 = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Pack Margin"),
TileLang.Text("Measured in pixels, assuming mesh will cover an entire 1024x1024 lightmap.")
)) {
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = this.propertyGenerateSecondUVsPackMargin.hasMultipleDifferentValues;
packMargin = EditorGUILayout.Slider(content2, packMargin, 1f, 64f);
if (EditorGUI.EndChangeCheck()) {
this.propertyGenerateSecondUVsPackMargin.floatValue = Mathf.Ceil(packMargin) / 1024f;
}
ExtraEditorGUI.TrailingTip(content2);
}
using (var content2 = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Angle Error"),
TileLang.Text("Measured in percents. Angle error measures deviation of UV angles from geometry angles. Area error measure deviation of UV triangles area from geometry triangles if they were uniformly scaled.")
)) {
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = this.propertyGenerateSecondUVsAngleError.hasMultipleDifferentValues;
angleError = EditorGUILayout.Slider(content2, angleError, 1f, 75f);
if (EditorGUI.EndChangeCheck()) {
this.propertyGenerateSecondUVsAngleError.floatValue = Mathf.Ceil(angleError) / 100f;
}
ExtraEditorGUI.TrailingTip(content2);
}
using (var content2 = ControlContent.Basic(
TileLang.ParticularText("Property", "Area Error")
)) {
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = this.propertyGenerateSecondUVsAreaError.hasMultipleDifferentValues;
areaError = EditorGUILayout.Slider(content2, areaError, 1f, 75f);
if (EditorGUI.EndChangeCheck()) {
this.propertyGenerateSecondUVsAreaError.floatValue = Mathf.Ceil(areaError) / 100f;
}
}
EditorGUI.showMixedValue = false;
}
--EditorGUI.indentLevel;
}
}
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Pre-generate Procedural"),
TileLang.Text("Increases size of scene but allows brushes to be stripped from builds.")
)) {
EditorGUILayout.PropertyField(this.propertyPregenerateProcedural, content);
ExtraEditorGUI.TrailingTip(content);
}
RotorzEditorGUI.InfoBox(TileLang.Text("Stripping capabilities are reduced when procedural tiles are present but are not pre-generated since they are otherwise generated at runtime."), MessageType.Info);
GUILayout.Space(5);
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Reduce Box Colliders"),
TileLang.Text("Reduces count of box colliders by coalescing adjacent colliders.")
)) {
EditorGUILayout.PropertyField(this.propertyReduceColliders, content);
ExtraEditorGUI.TrailingTip(content);
}
}
#endregion
#region Section: Runtime Options
private SerializedProperty propertyApplyRuntimeStripping;
private SerializedProperty propertyHintEraseEmptyChunks;
private SerializedProperty propertyUpdateProceduralAtStart;
private SerializedProperty propertyMarkProceduralDynamic;
private SerializedProperty propertyAddProceduralNormals;
private SerializedProperty propertySortingLayerID;
private SerializedProperty propertySortingOrder;
private void InitRuntimeOptionsSection()
{
this.propertyApplyRuntimeStripping = this.serializedObject.FindProperty("applyRuntimeStripping");
this.propertyHintEraseEmptyChunks = this.serializedObject.FindProperty("hintEraseEmptyChunks");
this.propertyUpdateProceduralAtStart = this.serializedObject.FindProperty("updateProceduralAtStart");
this.propertyMarkProceduralDynamic = this.serializedObject.FindProperty("markProceduralDynamic");
this.propertyAddProceduralNormals = this.serializedObject.FindProperty("addProceduralNormals");
this.propertySortingLayerID = this.serializedObject.FindProperty("sortingLayerID");
this.propertySortingOrder = this.serializedObject.FindProperty("sortingOrder");
}
private void DrawRuntimeOptionsSection()
{
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Erase Empty Chunks"),
TileLang.Text("Hints that empty chunks should be erased when they become empty at runtime.")
)) {
EditorGUILayout.PropertyField(this.propertyHintEraseEmptyChunks, content);
ExtraEditorGUI.TrailingTip(content);
}
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Apply Basic Stripping"),
TileLang.Text("Applies a basic degree of stripping at runtime upon awakening.")
)) {
EditorGUILayout.PropertyField(this.propertyApplyRuntimeStripping, content);
ExtraEditorGUI.TrailingTip(content);
}
ExtraEditorGUI.SeparatorLight();
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Update Procedural at Start"),
TileLang.Text("Automatically updates procedural meshes at runtime upon awakening.")
)) {
EditorGUILayout.PropertyField(this.propertyUpdateProceduralAtStart, content);
ExtraEditorGUI.TrailingTip(content);
}
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Mark Procedural Dynamic"),
TileLang.Text("Helps to improve performance when procedural tiles are updated frequently at runtime. Unset if only updated at start of level.")
)) {
EditorGUILayout.PropertyField(this.propertyMarkProceduralDynamic, content);
ExtraEditorGUI.TrailingTip(content);
}
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Add Procedural Normals"),
TileLang.Text("Adds normals to procedural meshes.")
)) {
EditorGUILayout.PropertyField(this.propertyAddProceduralNormals, content);
ExtraEditorGUI.TrailingTip(content);
}
ExtraEditorGUI.SeparatorLight();
EditorGUI.BeginChangeCheck();
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Procedural Sorting Layer"),
TileLang.Text("Sorting layer for procedural tileset meshes.")
)) {
RotorzEditorGUI.SortingLayerField(this.propertySortingLayerID, content);
ExtraEditorGUI.TrailingTip(content);
}
using (var content = ControlContent.WithTrailableTip(
TileLang.ParticularText("Property", "Procedural Order in Layer"),
TileLang.Text("Order in sorting layer.")
)) {
EditorGUILayout.PropertyField(this.propertySortingOrder, content);
ExtraEditorGUI.TrailingTip(content);
}
if (EditorGUI.EndChangeCheck()) {
int sortingLayerID = this.propertySortingLayerID.intValue;
int sortingOrder = this.propertySortingOrder.intValue;
// Update existing procedurally generated tileset meshes immediately.
foreach (var target in this.targets) {
((TileSystem)target).ApplySortingPropertiesToExistingProceduralMeshes(sortingLayerID, sortingOrder);
}
}
}
#endregion
private void DrawToolbar()
{
GUILayout.BeginHorizontal(EditorStyles.toolbar);
EditorGUI.BeginDisabledGroup(PrefabUtility.GetPrefabType(this.target) == PrefabType.Prefab || this.targets.Length != 1);
if (this.target.IsEditable && GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Build Prefab")), RotorzEditorStyles.Instance.ToolbarButtonPaddedExtra)) {
TileSystemCommands.Command_BuildPrefab(this.target);
GUIUtility.ExitGUI();
}
EditorGUI.EndDisabledGroup();
GUILayout.FlexibleSpace();
using (var content = ControlContent.Basic(
RotorzEditorStyles.Skin.GridToggle,
TileLang.ParticularText("Action", "Toggle Grid Display")
)) {
RtsPreferences.ShowGrid.Value = GUILayout.Toggle(RtsPreferences.ShowGrid, content, RotorzEditorStyles.Instance.ToolbarButtonPadded);
}
using (var content = ControlContent.Basic(
RotorzEditorStyles.Skin.ChunkToggle,
TileLang.ParticularText("Action", "Toggle Chunk Display")
)) {
RtsPreferences.ShowChunks.Value = GUILayout.Toggle(RtsPreferences.ShowChunks, content, RotorzEditorStyles.Instance.ToolbarButtonPadded);
}
EditorGUILayout.Space();
this.DrawHelpButton();
GUILayout.EndHorizontal();
}
private void DrawHelpButton()
{
using (var content = ControlContent.Basic(RotorzEditorStyles.Skin.ContextHelp)) {
Rect position = GUILayoutUtility.GetRect(content, RotorzEditorStyles.Instance.ToolbarButtonPadded);
if (EditorInternalUtility.DropdownMenu(position, content, RotorzEditorStyles.Instance.ToolbarButtonPadded)) {
var helpMenu = new EditorMenu();
helpMenu.AddCommand(TileLang.ParticularText("Action", "Show Tips"))
.Checked(ControlContent.TrailingTipsVisible)
.Action(() => {
ControlContent.TrailingTipsVisible = !ControlContent.TrailingTipsVisible;
});
--position.y;
helpMenu.ShowAsDropdown(position);
}
}
}
}
}
| |
// 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.Web.UI.WebControls.MenuItem.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.Web.UI.WebControls
{
sealed public partial class MenuItem : System.Web.UI.IStateManager, ICloneable
{
#region Methods and constructors
public MenuItem()
{
}
public MenuItem(string text, string value)
{
}
public MenuItem(string text, string value, string imageUrl, string navigateUrl, string target)
{
}
public MenuItem(string text, string value, string imageUrl)
{
}
public MenuItem(string text, string value, string imageUrl, string navigateUrl)
{
}
public MenuItem(string text)
{
}
Object System.ICloneable.Clone()
{
return default(Object);
}
void System.Web.UI.IStateManager.LoadViewState(Object state)
{
}
Object System.Web.UI.IStateManager.SaveViewState()
{
return default(Object);
}
void System.Web.UI.IStateManager.TrackViewState()
{
}
#endregion
#region Properties and indexers
public MenuItemCollection ChildItems
{
get
{
return default(MenuItemCollection);
}
}
public bool DataBound
{
get
{
return default(bool);
}
}
public Object DataItem
{
get
{
return default(Object);
}
}
public string DataPath
{
get
{
return default(string);
}
}
public int Depth
{
get
{
return default(int);
}
}
public bool Enabled
{
get
{
return default(bool);
}
set
{
}
}
public string ImageUrl
{
get
{
return default(string);
}
set
{
}
}
public string NavigateUrl
{
get
{
return default(string);
}
set
{
}
}
public System.Web.UI.WebControls.MenuItem Parent
{
get
{
return default(System.Web.UI.WebControls.MenuItem);
}
}
public string PopOutImageUrl
{
get
{
return default(string);
}
set
{
}
}
public bool Selectable
{
get
{
return default(bool);
}
set
{
}
}
public bool Selected
{
get
{
return default(bool);
}
set
{
}
}
public string SeparatorImageUrl
{
get
{
return default(string);
}
set
{
}
}
bool System.Web.UI.IStateManager.IsTrackingViewState
{
get
{
return default(bool);
}
}
public string Target
{
get
{
return default(string);
}
set
{
}
}
public string Text
{
get
{
return default(string);
}
set
{
}
}
public string ToolTip
{
get
{
return default(string);
}
set
{
}
}
public string Value
{
get
{
return default(string);
}
set
{
}
}
public string ValuePath
{
get
{
return default(string);
}
}
#endregion
}
}
| |
using OpenSource.UPnP;
namespace UPnPRelay
{
/// <summary>
/// Transparent DeviceSide UPnP Service
/// </summary>
public class DvGateKeeper : IUPnPService
{
// Place your declarations above this line
#region AutoGenerated Code Section [Do NOT Modify, unless you know what you're doing]
//{{{{{ Begin Code Block
private _DvGateKeeper _S;
public static string URN = "urn:schemas-upnp-org:service:UPnPRelay:1";
public double VERSION
{
get
{
return(double.Parse(_S.GetUPnPService().Version));
}
}
public System.Boolean Reverse
{
get
{
return((System.Boolean)_S.GetStateVariable("Reverse"));
}
set
{
_S.SetStateVariable("Reverse", value);
}
}
public System.String ErrorString
{
get
{
return((System.String)_S.GetStateVariable("ErrorString"));
}
set
{
_S.SetStateVariable("ErrorString", value);
}
}
public System.String StateVariableName
{
get
{
return((System.String)_S.GetStateVariable("StateVariableName"));
}
set
{
_S.SetStateVariable("StateVariableName", value);
}
}
public System.String ServiceID
{
get
{
return((System.String)_S.GetStateVariable("ServiceID"));
}
set
{
_S.SetStateVariable("ServiceID", value);
}
}
public System.Byte[] Document
{
get
{
return((System.Byte[])_S.GetStateVariable("Document"));
}
set
{
_S.SetStateVariable("Document", value);
}
}
public System.Byte[] Args
{
get
{
return((System.Byte[])_S.GetStateVariable("Args"));
}
set
{
_S.SetStateVariable("Args", value);
}
}
public System.Int32 Handle
{
get
{
return((System.Int32)_S.GetStateVariable("Handle"));
}
set
{
_S.SetStateVariable("Handle", value);
}
}
public System.Uri ProxyUri
{
get
{
return((System.Uri)_S.GetStateVariable("ProxyUri"));
}
set
{
_S.SetStateVariable("ProxyUri", value);
}
}
public System.String ActionName
{
get
{
return((System.String)_S.GetStateVariable("ActionName"));
}
set
{
_S.SetStateVariable("ActionName", value);
}
}
public System.String StateVariableValue
{
get
{
return((System.String)_S.GetStateVariable("StateVariableValue"));
}
set
{
_S.SetStateVariable("StateVariableValue", value);
}
}
public System.String DeviceUDN
{
get
{
return((System.String)_S.GetStateVariable("DeviceUDN"));
}
set
{
_S.SetStateVariable("DeviceUDN", value);
}
}
public System.Int32 ErrorCode
{
get
{
return((System.Int32)_S.GetStateVariable("ErrorCode"));
}
set
{
_S.SetStateVariable("ErrorCode", value);
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_Reverse
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Reverse")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Reverse")).Accumulator = value;
}
}
public double ModerationDuration_Reverse
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Reverse")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Reverse")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_ErrorString
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorString")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorString")).Accumulator = value;
}
}
public double ModerationDuration_ErrorString
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorString")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorString")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_StateVariableName
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableName")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableName")).Accumulator = value;
}
}
public double ModerationDuration_StateVariableName
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableName")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableName")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_ServiceID
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ServiceID")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ServiceID")).Accumulator = value;
}
}
public double ModerationDuration_ServiceID
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ServiceID")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ServiceID")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_Document
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Document")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Document")).Accumulator = value;
}
}
public double ModerationDuration_Document
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Document")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Document")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_Args
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Args")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Args")).Accumulator = value;
}
}
public double ModerationDuration_Args
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Args")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Args")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_Handle
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Handle")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Handle")).Accumulator = value;
}
}
public double ModerationDuration_Handle
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Handle")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("Handle")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_ProxyUri
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ProxyUri")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ProxyUri")).Accumulator = value;
}
}
public double ModerationDuration_ProxyUri
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ProxyUri")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ProxyUri")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_ActionName
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ActionName")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ActionName")).Accumulator = value;
}
}
public double ModerationDuration_ActionName
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ActionName")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ActionName")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_StateVariableValue
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableValue")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableValue")).Accumulator = value;
}
}
public double ModerationDuration_StateVariableValue
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableValue")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("StateVariableValue")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_DeviceUDN
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("DeviceUDN")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("DeviceUDN")).Accumulator = value;
}
}
public double ModerationDuration_DeviceUDN
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("DeviceUDN")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("DeviceUDN")).ModerationPeriod = value;
}
}
public UPnPModeratedStateVariable.IAccumulator Accumulator_ErrorCode
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorCode")).Accumulator);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorCode")).Accumulator = value;
}
}
public double ModerationDuration_ErrorCode
{
get
{
return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorCode")).ModerationPeriod);
}
set
{
((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("ErrorCode")).ModerationPeriod = value;
}
}
public delegate void Delegate_Invoke(System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, out System.Byte[] OutArgs);
public delegate void Delegate_FireEvent(System.String DeviceUDN, System.String ServiceID, System.String StateVariable, System.String Value);
public delegate void Delegate_AddDevice(System.String Sender, System.String DeviceUDN);
public delegate void Delegate_InvokeAsync(System.String Caller, System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, System.Int32 Handle);
public delegate void Delegate_GetDocument(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Document);
public delegate void Delegate_InvokeAsyncResponse(System.Int32 Handle, System.Byte[] OutArgs, System.Int32 ErrorCode, System.String ErrorString);
public delegate void Delegate_Register(System.Uri Proxy, System.Boolean Reverse);
public delegate void Delegate_GetStateTable(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Variables);
public delegate void Delegate_RemoveDevice(System.String DeviceUDN);
public delegate void Delegate_UnRegister(System.Uri Proxy);
public Delegate_Invoke External_Invoke = null;
public Delegate_FireEvent External_FireEvent = null;
public Delegate_AddDevice External_AddDevice = null;
public Delegate_InvokeAsync External_InvokeAsync = null;
public Delegate_GetDocument External_GetDocument = null;
public Delegate_InvokeAsyncResponse External_InvokeAsyncResponse = null;
public Delegate_Register External_Register = null;
public Delegate_GetStateTable External_GetStateTable = null;
public Delegate_RemoveDevice External_RemoveDevice = null;
public Delegate_UnRegister External_UnRegister = null;
public void RemoveAction_Invoke()
{
_S.GetUPnPService().RemoveMethod("Invoke");
}
public void RemoveAction_FireEvent()
{
_S.GetUPnPService().RemoveMethod("FireEvent");
}
public void RemoveAction_AddDevice()
{
_S.GetUPnPService().RemoveMethod("AddDevice");
}
public void RemoveAction_InvokeAsync()
{
_S.GetUPnPService().RemoveMethod("InvokeAsync");
}
public void RemoveAction_GetDocument()
{
_S.GetUPnPService().RemoveMethod("GetDocument");
}
public void RemoveAction_InvokeAsyncResponse()
{
_S.GetUPnPService().RemoveMethod("InvokeAsyncResponse");
}
public void RemoveAction_Register()
{
_S.GetUPnPService().RemoveMethod("Register");
}
public void RemoveAction_GetStateTable()
{
_S.GetUPnPService().RemoveMethod("GetStateTable");
}
public void RemoveAction_RemoveDevice()
{
_S.GetUPnPService().RemoveMethod("RemoveDevice");
}
public void RemoveAction_UnRegister()
{
_S.GetUPnPService().RemoveMethod("UnRegister");
}
public System.Net.IPEndPoint GetCaller()
{
return(_S.GetUPnPService().GetCaller());
}
public System.Net.IPEndPoint GetReceiver()
{
return(_S.GetUPnPService().GetReceiver());
}
private class _DvGateKeeper
{
private DvGateKeeper Outer = null;
private UPnPService S;
internal _DvGateKeeper(DvGateKeeper n)
{
Outer = n;
S = BuildUPnPService();
}
public UPnPService GetUPnPService()
{
return(S);
}
public void SetStateVariable(string VarName, object VarValue)
{
S.SetStateVariable(VarName,VarValue);
}
public object GetStateVariable(string VarName)
{
return(S.GetStateVariable(VarName));
}
protected UPnPService BuildUPnPService()
{
UPnPStateVariable[] RetVal = new UPnPStateVariable[12];
RetVal[0] = new UPnPModeratedStateVariable("Reverse", typeof(System.Boolean), false);
RetVal[0].AddAssociation("Register", "Reverse");
RetVal[1] = new UPnPModeratedStateVariable("ErrorString", typeof(System.String), false);
RetVal[1].AddAssociation("InvokeAsyncResponse", "ErrorString");
RetVal[2] = new UPnPModeratedStateVariable("StateVariableName", typeof(System.String), false);
RetVal[2].AddAssociation("FireEvent", "StateVariable");
RetVal[3] = new UPnPModeratedStateVariable("ServiceID", typeof(System.String), false);
RetVal[3].AddAssociation("Invoke", "ServiceID");
RetVal[3].AddAssociation("FireEvent", "ServiceID");
RetVal[3].AddAssociation("InvokeAsync", "ServiceID");
RetVal[3].AddAssociation("GetDocument", "ServiceID");
RetVal[3].AddAssociation("GetStateTable", "ServiceID");
RetVal[4] = new UPnPModeratedStateVariable("Document", typeof(System.Byte[]), false);
RetVal[4].AddAssociation("GetDocument", "Document");
RetVal[5] = new UPnPModeratedStateVariable("Args", typeof(System.Byte[]), false);
RetVal[5].AddAssociation("Invoke", "InArgs");
RetVal[5].AddAssociation("Invoke", "OutArgs");
RetVal[5].AddAssociation("InvokeAsync", "InArgs");
RetVal[5].AddAssociation("InvokeAsyncResponse", "OutArgs");
RetVal[5].AddAssociation("GetStateTable", "Variables");
RetVal[6] = new UPnPModeratedStateVariable("Handle", typeof(System.Int32), false);
RetVal[6].AddAssociation("InvokeAsync", "Handle");
RetVal[6].AddAssociation("InvokeAsyncResponse", "Handle");
RetVal[7] = new UPnPModeratedStateVariable("ProxyUri", typeof(System.Uri), false);
RetVal[7].AddAssociation("Register", "Proxy");
RetVal[7].AddAssociation("UnRegister", "Proxy");
RetVal[8] = new UPnPModeratedStateVariable("ActionName", typeof(System.String), false);
RetVal[8].AddAssociation("Invoke", "Action");
RetVal[8].AddAssociation("InvokeAsync", "Action");
RetVal[9] = new UPnPModeratedStateVariable("StateVariableValue", typeof(System.String), false);
RetVal[9].AddAssociation("FireEvent", "Value");
RetVal[10] = new UPnPModeratedStateVariable("DeviceUDN", typeof(System.String), false);
RetVal[10].AddAssociation("Invoke", "DeviceUDN");
RetVal[10].AddAssociation("FireEvent", "DeviceUDN");
RetVal[10].AddAssociation("AddDevice", "Sender");
RetVal[10].AddAssociation("AddDevice", "DeviceUDN");
RetVal[10].AddAssociation("InvokeAsync", "Caller");
RetVal[10].AddAssociation("InvokeAsync", "DeviceUDN");
RetVal[10].AddAssociation("GetDocument", "DeviceUDN");
RetVal[10].AddAssociation("GetStateTable", "DeviceUDN");
RetVal[10].AddAssociation("RemoveDevice", "DeviceUDN");
RetVal[11] = new UPnPModeratedStateVariable("ErrorCode", typeof(System.Int32), false);
RetVal[11].AddAssociation("InvokeAsyncResponse", "ErrorCode");
UPnPService S = new UPnPService(1, "UPNPRELAY_0-2", "urn:schemas-upnp-org:service:UPnPRelay:1", true, this);
for(int i=0;i<RetVal.Length;++i)
{
S.AddStateVariable(RetVal[i]);
}
S.AddMethod("Invoke");
S.AddMethod("FireEvent");
S.AddMethod("AddDevice");
S.AddMethod("InvokeAsync");
S.AddMethod("GetDocument");
S.AddMethod("InvokeAsyncResponse");
S.AddMethod("Register");
S.AddMethod("GetStateTable");
S.AddMethod("RemoveDevice");
S.AddMethod("UnRegister");
return(S);
}
public void Invoke(System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, out System.Byte[] OutArgs)
{
if(Outer.External_Invoke != null)
{
Outer.External_Invoke(DeviceUDN, ServiceID, Action, InArgs, out OutArgs);
}
else
{
Sink_Invoke(DeviceUDN, ServiceID, Action, InArgs, out OutArgs);
}
}
public void FireEvent(System.String DeviceUDN, System.String ServiceID, System.String StateVariable, System.String Value)
{
if(Outer.External_FireEvent != null)
{
Outer.External_FireEvent(DeviceUDN, ServiceID, StateVariable, Value);
}
else
{
Sink_FireEvent(DeviceUDN, ServiceID, StateVariable, Value);
}
}
public void AddDevice(System.String Sender, System.String DeviceUDN)
{
if(Outer.External_AddDevice != null)
{
Outer.External_AddDevice(Sender, DeviceUDN);
}
else
{
Sink_AddDevice(Sender, DeviceUDN);
}
}
public void InvokeAsync(System.String Caller, System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, System.Int32 Handle)
{
if(Outer.External_InvokeAsync != null)
{
Outer.External_InvokeAsync(Caller, DeviceUDN, ServiceID, Action, InArgs, Handle);
}
else
{
Sink_InvokeAsync(Caller, DeviceUDN, ServiceID, Action, InArgs, Handle);
}
}
public void GetDocument(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Document)
{
if(Outer.External_GetDocument != null)
{
Outer.External_GetDocument(DeviceUDN, ServiceID, out Document);
}
else
{
Sink_GetDocument(DeviceUDN, ServiceID, out Document);
}
}
public void InvokeAsyncResponse(System.Int32 Handle, System.Byte[] OutArgs, System.Int32 ErrorCode, System.String ErrorString)
{
if(Outer.External_InvokeAsyncResponse != null)
{
Outer.External_InvokeAsyncResponse(Handle, OutArgs, ErrorCode, ErrorString);
}
else
{
Sink_InvokeAsyncResponse(Handle, OutArgs, ErrorCode, ErrorString);
}
}
public void Register(System.Uri Proxy, System.Boolean Reverse)
{
if(Outer.External_Register != null)
{
Outer.External_Register(Proxy, Reverse);
}
else
{
Sink_Register(Proxy, Reverse);
}
}
public void GetStateTable(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Variables)
{
if(Outer.External_GetStateTable != null)
{
Outer.External_GetStateTable(DeviceUDN, ServiceID, out Variables);
}
else
{
Sink_GetStateTable(DeviceUDN, ServiceID, out Variables);
}
}
public void RemoveDevice(System.String DeviceUDN)
{
if(Outer.External_RemoveDevice != null)
{
Outer.External_RemoveDevice(DeviceUDN);
}
else
{
Sink_RemoveDevice(DeviceUDN);
}
}
public void UnRegister(System.Uri Proxy)
{
if(Outer.External_UnRegister != null)
{
Outer.External_UnRegister(Proxy);
}
else
{
Sink_UnRegister(Proxy);
}
}
public Delegate_Invoke Sink_Invoke;
public Delegate_FireEvent Sink_FireEvent;
public Delegate_AddDevice Sink_AddDevice;
public Delegate_InvokeAsync Sink_InvokeAsync;
public Delegate_GetDocument Sink_GetDocument;
public Delegate_InvokeAsyncResponse Sink_InvokeAsyncResponse;
public Delegate_Register Sink_Register;
public Delegate_GetStateTable Sink_GetStateTable;
public Delegate_RemoveDevice Sink_RemoveDevice;
public Delegate_UnRegister Sink_UnRegister;
}
public DvGateKeeper()
{
_S = new _DvGateKeeper(this);
_S.Sink_Invoke = new Delegate_Invoke(Invoke);
_S.Sink_FireEvent = new Delegate_FireEvent(FireEvent);
_S.Sink_AddDevice = new Delegate_AddDevice(AddDevice);
_S.Sink_InvokeAsync = new Delegate_InvokeAsync(InvokeAsync);
_S.Sink_GetDocument = new Delegate_GetDocument(GetDocument);
_S.Sink_InvokeAsyncResponse = new Delegate_InvokeAsyncResponse(InvokeAsyncResponse);
_S.Sink_Register = new Delegate_Register(Register);
_S.Sink_GetStateTable = new Delegate_GetStateTable(GetStateTable);
_S.Sink_RemoveDevice = new Delegate_RemoveDevice(RemoveDevice);
_S.Sink_UnRegister = new Delegate_UnRegister(UnRegister);
}
public DvGateKeeper(string ID):this()
{
_S.GetUPnPService().ServiceID = ID;
}
public UPnPService GetUPnPService()
{
return(_S.GetUPnPService());
}
//}}}}} End of Code Block
#endregion
/// <summary>
/// Action: Invoke
/// </summary>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
/// <param name="ServiceID">Associated State Variable: ServiceID</param>
/// <param name="Action">Associated State Variable: ActionName</param>
/// <param name="InArgs">Associated State Variable: Args</param>
/// <param name="OutArgs">Associated State Variable: Args</param>
public void Invoke(System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, out System.Byte[] OutArgs)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: FireEvent
/// </summary>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
/// <param name="ServiceID">Associated State Variable: ServiceID</param>
/// <param name="StateVariable">Associated State Variable: StateVariableName</param>
/// <param name="Value">Associated State Variable: StateVariableValue</param>
public void FireEvent(System.String DeviceUDN, System.String ServiceID, System.String StateVariable, System.String Value)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: AddDevice
/// </summary>
/// <param name="Sender">Associated State Variable: DeviceUDN</param>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
public void AddDevice(System.String Sender, System.String DeviceUDN)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: InvokeAsync
/// </summary>
/// <param name="Caller">Associated State Variable: DeviceUDN</param>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
/// <param name="ServiceID">Associated State Variable: ServiceID</param>
/// <param name="Action">Associated State Variable: ActionName</param>
/// <param name="InArgs">Associated State Variable: Args</param>
/// <param name="Handle">Associated State Variable: Handle</param>
public void InvokeAsync(System.String Caller, System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, System.Int32 Handle)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: GetDocument
/// </summary>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
/// <param name="ServiceID">Associated State Variable: ServiceID</param>
/// <param name="Document">Associated State Variable: Document</param>
public void GetDocument(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Document)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: InvokeAsyncResponse
/// </summary>
/// <param name="Handle">Associated State Variable: Handle</param>
/// <param name="OutArgs">Associated State Variable: Args</param>
/// <param name="ErrorCode">Associated State Variable: ErrorCode</param>
/// <param name="ErrorString">Associated State Variable: ErrorString</param>
public void InvokeAsyncResponse(System.Int32 Handle, System.Byte[] OutArgs, System.Int32 ErrorCode, System.String ErrorString)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: Register
/// </summary>
/// <param name="Proxy">Associated State Variable: ProxyUri</param>
/// <param name="Reverse">Associated State Variable: Reverse</param>
public void Register(System.Uri Proxy, System.Boolean Reverse)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: GetStateTable
/// </summary>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
/// <param name="ServiceID">Associated State Variable: ServiceID</param>
/// <param name="Variables">Associated State Variable: Args</param>
public void GetStateTable(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Variables)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: RemoveDevice
/// </summary>
/// <param name="DeviceUDN">Associated State Variable: DeviceUDN</param>
public void RemoveDevice(System.String DeviceUDN)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
/// <summary>
/// Action: UnRegister
/// </summary>
/// <param name="Proxy">Associated State Variable: ProxyUri</param>
public void UnRegister(System.Uri Proxy)
{
//ToDo: Add Your implementation here, and remove exception
throw(new UPnPCustomException(800,"This method has not been completely implemented..."));
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H03_Continent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="H03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class H03_Continent_Child : BusinessBase<H03_Continent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H03_Continent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H03_Continent_Child"/> object.</returns>
internal static H03_Continent_Child NewH03_Continent_Child()
{
return DataPortal.CreateChild<H03_Continent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="H03_Continent_Child"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID1">The Continent_ID1 parameter of the H03_Continent_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="H03_Continent_Child"/> object.</returns>
internal static H03_Continent_Child GetH03_Continent_Child(int continent_ID1)
{
return DataPortal.FetchChild<H03_Continent_Child>(continent_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H03_Continent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H03_Continent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H03_Continent_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID1">The Continent ID1.</param>
protected void Child_Fetch(int continent_ID1)
{
var args = new DataPortalHookArgs(continent_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IH03_Continent_ChildDal>();
var data = dal.Fetch(continent_ID1);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="H03_Continent_Child"/> object from the given <see cref="H03_Continent_ChildDto"/>.
/// </summary>
/// <param name="data">The H03_Continent_ChildDto to use.</param>
private void Fetch(H03_Continent_ChildDto data)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H03_Continent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H02_Continent parent)
{
var dto = new H03_Continent_ChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IH03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H03_Continent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H02_Continent parent)
{
if (!IsDirty)
return;
var dto = new H03_Continent_ChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="H03_Continent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H02_Continent parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IH03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// 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.Linq;
using System.Threading.Tasks;
using Cassandra.Data.Linq;
using Cassandra.Mapping;
using Cassandra.Tests.Mapping.Pocos;
using Moq;
using NUnit.Framework;
namespace Cassandra.Tests.Mapping.Linq
{
[TestFixture]
public class LinqExecutionProfileTests : MappingTestBase
{
[Test]
[TestCase(true, true)]
[TestCase(false, true)]
[TestCase(true, false)]
[TestCase(false, false)]
public async Task Should_ExecuteBatchCorrectlyWithExecutionProfile_When_ExecutionProfileIsProvided(bool batchV1, bool async)
{
IStatement statement = null;
var session = batchV1
? GetSession<SimpleStatement>(new RowSet(), stmt => statement = stmt, ProtocolVersion.V1)
: GetSession<BatchStatement>(new RowSet(), stmt => statement = stmt, ProtocolVersion.V2);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.StringValue, cm => cm.WithName("val"))
.Column(t => t.UuidValue, cm => cm.WithName("id"))
.PartitionKey(t => t.UuidValue)
.TableName("tbl1");
var batch = session.CreateBatch();
Assert.IsTrue(batchV1 ? batch.GetType() == typeof(BatchV1) : batch.GetType() == typeof(BatchV2));
const int updateCount = 3;
var table = GetTable<AllTypesEntity>(session, map);
var updateGuids = Enumerable.Range(0, updateCount).Select(_ => Guid.NewGuid()).ToList();
var updateCqls = updateGuids.Select(guid => table
.Where(_ => _.UuidValue == guid)
.Select(_ => new AllTypesEntity { StringValue = "newStringFor" + guid })
.Update());
batch.Append(updateCqls);
if (async)
{
await batch.ExecuteAsync("testProfile").ConfigureAwait(false);
}
else
{
batch.Execute("testProfile");
}
Assert.NotNull(statement);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
if (!batchV1)
{
var batchStatement = (BatchStatement) statement;
foreach (var updateGuid in updateGuids)
{
var updateStatement = batchStatement.Queries.First(_ => _.QueryValues.Length == 2 && _.QueryValues[1] as Guid? == updateGuid) as SimpleStatement;
Assert.IsNotNull(updateStatement);
Assert.IsNotNull(updateStatement.QueryValues);
Assert.AreEqual(2, updateStatement.QueryValues.Length);
Assert.AreEqual("newStringFor" + updateGuid, updateStatement.QueryValues[0]);
Assert.AreEqual("UPDATE tbl1 SET val = ? WHERE id = ?", updateStatement.QueryString);
}
}
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteCqlCommandWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
string query = null;
var session = GetSession((q, v) => query = q);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.DoubleValue, cm => cm.WithName("val"))
.Column(t => t.IntValue, cm => cm.WithName("id"))
.PartitionKey(t => t.IntValue)
.KeyspaceName("ks1")
.TableName("tbl1");
var table = GetTable<AllTypesEntity>(session, map);
var cqlDelete = table.Where(t => t.IntValue == 100).Delete();
if (async)
{
await cqlDelete.ExecuteAsync("testProfile").ConfigureAwait(false);
}
else
{
cqlDelete.Execute("testProfile");
}
Assert.AreEqual("DELETE FROM ks1.tbl1 WHERE id = ?", query);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteCqlConditionalCommandWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
string query = null;
var session = GetSession((q, v) => query = q);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.DoubleValue, cm => cm.WithName("val"))
.Column(t => t.IntValue, cm => cm.WithName("id"))
.PartitionKey(t => t.IntValue)
.KeyspaceName("ks1")
.TableName("tbl1");
var table = GetTable<AllTypesEntity>(session, map);
var cqlUpdateIf = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = 123D }).UpdateIf(t => t.DoubleValue > 123D);
if (async)
{
await cqlUpdateIf.ExecuteAsync("testProfile").ConfigureAwait(false);
}
else
{
cqlUpdateIf.Execute("testProfile");
}
Assert.AreEqual("UPDATE ks1.tbl1 SET val = ? WHERE id = ? IF val > ?", query);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteCqlQueryWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
string query = null;
var session = GetSession((q, v) => query = q);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.DoubleValue, cm => cm.WithName("val"))
.Column(t => t.IntValue, cm => cm.WithName("id"))
.PartitionKey(t => t.IntValue)
.KeyspaceName("ks1")
.TableName("tbl1");
var table = GetTable<AllTypesEntity>(session, map);
var cqlSelect = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = t.DoubleValue });
if (async)
{
await cqlSelect.ExecuteAsync("testProfile").ConfigureAwait(false);
}
else
{
cqlSelect.Execute("testProfile");
}
Assert.AreEqual("SELECT val FROM ks1.tbl1 WHERE id = ?", query);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecutePagedCqlQueryWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
string query = null;
var session = GetSession((q, v) => query = q);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.DoubleValue, cm => cm.WithName("val"))
.Column(t => t.IntValue, cm => cm.WithName("id"))
.PartitionKey(t => t.IntValue)
.KeyspaceName("ks1")
.TableName("tbl1");
var table = GetTable<AllTypesEntity>(session, map);
var cqlSelect = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = t.DoubleValue });
if (async)
{
await cqlSelect.ExecutePagedAsync("testProfile").ConfigureAwait(false);
}
else
{
cqlSelect.ExecutePaged("testProfile");
}
Assert.AreEqual("SELECT val FROM ks1.tbl1 WHERE id = ?", query);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteCqlQuerySingleElementWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
string query = null;
var session = GetSession((q, v) => query = q);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.DoubleValue, cm => cm.WithName("val"))
.Column(t => t.IntValue, cm => cm.WithName("id"))
.PartitionKey(t => t.IntValue)
.KeyspaceName("ks1")
.TableName("tbl1");
var table = GetTable<AllTypesEntity>(session, map);
var cqlFirst = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = t.DoubleValue }).First();
if (async)
{
await cqlFirst.ExecuteAsync("testProfile").ConfigureAwait(false);
}
else
{
cqlFirst.Execute("testProfile");
}
Assert.AreEqual("SELECT val FROM ks1.tbl1 WHERE id = ? LIMIT ?", query);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteCqlScalarQueryWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
string query = null;
var session = GetSession((q, v) => query = q);
var map = new Map<AllTypesEntity>()
.ExplicitColumns()
.Column(t => t.DoubleValue, cm => cm.WithName("val"))
.Column(t => t.IntValue, cm => cm.WithName("id"))
.PartitionKey(t => t.IntValue)
.KeyspaceName("ks1")
.TableName("tbl1");
var table = GetTable<AllTypesEntity>(session, map);
var cqlCount = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = t.DoubleValue }).Count();
if (async)
{
await cqlCount.ExecuteAsync("testProfile").ConfigureAwait(false);
}
else
{
cqlCount.Execute("testProfile");
}
Assert.AreEqual("SELECT count(*) FROM ks1.tbl1 WHERE id = ?", query);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once);
Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never);
Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never);
}
}
}
| |
//**************************************************************************
//
//
// National Institute Of Standards and Technology
// DTS Version 1.0
//
// NamedNodeMap Interface
//
// Written by: Carmelo Montanez
// Modified by: Mary Brady
//
// Ported to System.Xml by: Mizrahi Rafael rafim@mainsoft.com
// Mainsoft Corporation (c) 2003-2004
//**************************************************************************
using System;
using System.Xml;
using nist_dom;
using NUnit.Framework;
namespace nist_dom.fundamental
{
[TestFixture]
public class NamedNodeMapTest : Assertion
{
public static int i = 2;
/*
public testResults[] RunTests()
{
testResults[] tests = new testResults[] {core0001M(), core0002M(), core0003M(),core0004M(),
core0005M(), core0006M(), core0007M(), core0008M(),
core0009M(), core0010M(), core0011M(),
core0014M(), core0015M(), core0016M(),
core0017M(), core0018M(), core0019M(), core0020M(),
core0021M()};
return tests;
}
*/
//------------------------ test case core-0001M ------------------------
//
// Testing feature - The "getNamedItem(name)" method retrieves a node
// specified by name.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// listing of the attributes of its last child. Once
// the list is created an invocation of the
// "getNamedItem(name)" method is done where
// name = "domestic". This should result on the domestic
// Attr node being returned.
//
// Semantic Requirements: 1
//
//----------------------------------------------------------------------------
[Test]
public void core0001M()
{
string computedValue = "";
string expectedValue = "domestic";
System.Xml.XmlAttribute domesticAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0001M");
try
{
results.description = "The \"getNamedItem(name)\" method retrieves a node " +
"specified by name.";
//
// Retrieve targeted data.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
domesticAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("domestic");
computedValue = domesticAttr.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0001M --------------------------
//
//--------------------------- test case core-0002M ---------------------------
//
// Testing feature - The "getNamedItem(name)" method returns a node of any
// type specified by name.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// listing of the attributes of its last child. Once
// the list is created an invocation of the
// "getNamedItem(name)" method is done where
// name = "street". This should cause the method to return
// an Attr node.
//
// Semantic Requirements: 2
//
//----------------------------------------------------------------------------
[Test]
public void core0002M()
{
string computedValue = "";
string expectedValue = "street";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0002M");
try
{
results.description = "The \"getNamedItem(name)\" method returns a node "+
"of any type specified by name (test for Attr node).";
//
// Retrieve targeted data and get its attributes.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0002M --------------------------
//
//--------------------------- test case core-0003M ---------------------------
//
// Testing feature - The "getNamedItem(name)" method returns null if the
// specified name did not identify any node in the map.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// listing of the attributes of its last child. Once
// the list is created an invocation of the
// "getNamedItem(name)" method is done where
// name = "district", this name does not match any names
// in the list and the method should return null.
//
// Semantic Requirements: 3
//
//----------------------------------------------------------------------------
[Test]
public void core0003M()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0003M");
try
{
results.description = "The \"getNamedItem(name)\" method returns null if the " +
"specified name did not identify any node in the map.";
//
// Retrieve targeted data and attempt to get a non-existing attribute.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
computedValue = testNode.Attributes.GetNamedItem("district");
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0003M --------------------------
//
//--------------------------- test case core-0004M ---------------------------
//
// Testing feature - The "setNamedItem(arg)" method adds a node using its
// nodeName attribute.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child
// by invoking the "attributes" attribute. Once the
// list is created, the "setNamedItem(arg)" method is
// invoked with arg = newAttr, where newAttr is a new
// Attr Node previously created. The "setNamedItem(arg)"
// method should add the new node to the NamedNodeItem
// object by using its "nodeName" attribute ("district"
// in this case). Further this node is retrieved by using
// the "getNamedItem(name)" method. This test uses the
// "createAttribute(name)" method from the Document
// interface.
//
// Semantic Requirements: 4
//
//----------------------------------------------------------------------------
[Test]
public void core0004M()
{
string computedValue = "";
string expectedValue = "district";
System.Xml.XmlAttribute districtAttr = null;
System.Xml.XmlAttribute newAttr = (System.Xml.XmlAttribute)util.createNode(util.ATTRIBUTE_NODE,"district");
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0004M");
try
{
results.description = "The \"setNamedItem(arg)\" method adds a node "+
"using its nodeName attribute.";
//
// Retrieve targeted data and add new attribute.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
testNode.Attributes.SetNamedItem(newAttr);
districtAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("district");
computedValue = districtAttr.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0004M --------------------------
//
//--------------------------- test case core-0005 ---------------------------
//
// Testing feature - If the node to be added by the "setNamedItem(arg)" method
// already exists in the NamedNodeMap, it is replaced by the
// new one.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child. Once
// the list is created, the "setNamedItem(arg) method is
// invoked with arg = newAttr, where newAttr is a Node Attr
// previously created and whose node name already exist
// in the map. The "setNamedItem(arg)" method should
// replace the already existing node with the new one.
// Further this node is retrieved by using the
// "getNamedItem(name)" method. This test uses the
// "createAttribute(name)" method from the Document
// interface.
//
// Semantic Requirements: 5
//
//----------------------------------------------------------------------------
[Test]
public void core0005M()
{
string computedValue = "";
string expectedValue = "";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlAttribute newAttr = (System.Xml.XmlAttribute)util.createNode(util.ATTRIBUTE_NODE,"street");
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0005M");
try
{
results.description = "If the node to be replaced by the \"setNamedItem(arg)\" " +
"method is already in the list, the existing node should " +
"be replaced by the new one.";
//
// Retrieve targeted data and add new attribute with name matching an
// already existing attribute.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
testNode.Attributes.SetNamedItem(newAttr);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0005M --------------------------
//
//--------------------------- test case core-0006 ---------------------------
//
// Testing feature - If the "setNamedItem(arg)" method replaces an already
// existing node with the same name then the already existing
// node is returned.
//
// Testing approach - Retrieve the third employee and create a "NamedNodeMap"
// object of the attributes in its last child by
// invoking the "attributes" attribute. Once the
// list is created, the "setNamedItem(arg) method is
// invoked with arg = newAttr, where newAttr is a Node Attr
// previously created and whose node name already exist
// in the map. The "setNamedItem(arg)" method should replace
// the already existing node with the new one and return
// the existing node. Further this node is retrieved by
// using the "getNamedItem(name)" method. This test
// uses the "createAttribute(name)" method from the Document
// interface.
//
// Semantic Requirements: 6
//
//----------------------------------------------------------------------------
[Test]
public void core0006M()
{
string computedValue = "";
string expectedValue = "No";
System.Xml.XmlNode returnedNode = null;
System.Xml.XmlAttribute newAttr = (System.Xml.XmlAttribute)util.createNode(util.ATTRIBUTE_NODE,"street");
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0006M");
try
{
results.description = "If the \"setNamedItem(arg)\" method replaces an "+
"already existing node with the same name then it "+
"returns the already existing node.";
//
// Retrieve targeted data and examine value returned by the setNamedItem
// method.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
returnedNode = testNode.Attributes.SetNamedItem(newAttr);
computedValue = returnedNode.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0006M --------------------------
//
//--------------------------- test case core-0007 ---------------------------
//
// Testing feature - The "setNamedItem(arg)" method replace an
// already existing node with the same name. If a node with
// that name is already present in the collection,
// it is replaced by the new one.
//
// Testing approach - Retrieve the third employee and create a NamedNodeMap
// object from the attributes in its last child.
// Once the list is created, the "setNamedItem(arg)"
// method is invoked with arg = newAttr, where newAttr is
// a new previously created Attr node The
// "setNamedItem(arg)" method should add the new node
// and return the new one. Further this node is retrieved by
// using the "getNamedItem(name)" method. This test
// uses the "createAttribute(name)" method from the
// Document interface.
//
// Semantic Requirements: 7
//
//----------------------------------------------------------------------------
[Test]
public void core0007M()
{
string computedValue = "";
string expectedValue = "district";
System.Xml.XmlAttribute newAttr = (System.Xml.XmlAttribute)util.createNode(util.ATTRIBUTE_NODE,"district");
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0007M");
try
{
results.description = "If a node with that name is already present in the collection. The \"setNamedItem(arg)\" method is replacing it by the new one";
//
// Retrieve targeted data and set new attribute.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
computedValue = testNode.Attributes.SetNamedItem(newAttr).Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0007M --------------------------
//
//--------------------------- test case core-0008 ----------------------------
//
// Testing feature - The "removeNamedItem(name)" method removes a node
// specified by name.
//
// Testing approach - Retrieve the third employee and create a NamedNodeMap
// object from the attributes in its last child. Once
// the list is created, the "removeNamedItem(name)"
// method is invoked where "name" is the name of an
// existing attribute. The "removeNamedItem(name)" method
// should remove the specified attribute and its "specified"
// attribute (since this is an Attr node) should be set
// to false.
//
// Semantic Requirements: 8
//
//----------------------------------------------------------------------------
[Test]
public void core0008M()
{
string computedValue = "";
string expectedValue = "False";
System.Xml.XmlNode testNode = null;
System.Xml.XmlAttribute Attr = null;
testResults results = new testResults("Core0008M");
try
{
results.description = "The \"removeNamedItem(name)\" method removes "+
"a node specified by name.";
//
// Retrive targeted data and and remove attribute. It should no longer
// be specified.
//
testNode = (System.Xml.XmlNode)util.nodeObject(util.THIRD,util.SIXTH);
testNode.Attributes.RemoveNamedItem("street");
Attr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = Attr.Specified.ToString();
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0008M --------------------------
//
//--------------------------- test case core-0009 ----------------------------
//
// Testing feature - If the node removed by the "removeNamedItem(name)" method
// is an Attr node with a default value, its is immediately
// replaced.
//
// Testing approach - Retrieve the third employee and create a NamedNodeMap
// object from the attributes in its last child. Once
// the list is created, the "removeNamedItem(name)" method
// is invoked where "name" is the name of an existing
// attribute ("street)". The "removeNamedItem(name)" method
// should remove the "street" attribute and since it has
// a default value of "Yes", that value should immediately
// be the attribute's value.
//
// Semantic Requirements: 9
//
//----------------------------------------------------------------------------
[Test]
public void core0009M()
{
string computedValue = "";
string expectedValue = "Yes";
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0009M");
try
{
results.description = "If the node removed by the \"removeNamedItem(name)\" "+
"method is an Attr node with a default value, then "+
"it is immediately replaced.";
//
// Retrieve targeted data and remove attribute.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
testNode.Attributes.RemoveNamedItem("street");
computedValue = testNode.Attributes.GetNamedItem("street").Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0009M --------------------------
//
//--------------------------- test case core-0010M ---------------------------
//
// Testing feature - The "removeNamedItem(name)" method returns the node removed
// from the map.
//
// Testing approach - Retrieve the third employee and create a NamedNodeMap
// object from the attributes in its last child.
// Once the list is created, the "removeNamedItem(name)"
// method is invoked where "name" is the name of an existing
// attribute ("street)". The "removeNamedItem(name)"
// method should remove the existing "street" attribute
// and return it.
//
// Semantic Requirements: 10
//
//----------------------------------------------------------------------------
[Test]
public void core0010M()
{
string computedValue = "";
string expectedValue = "No";
System.Xml.XmlNode returnedNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0010M");
try
{
results.description = "The \"removeNamedItem(name)\" method returns the "+
"node removed from the map.";
//
// Retrieve targeted data, remove attribute and examine returned value of
// removeNamedItem method.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
returnedNode = testNode.Attributes.RemoveNamedItem("street");
computedValue = returnedNode.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0010M --------------------------
//
//--------------------------- test case core-0011M ---------------------------
//
// Testing feature - The "removeNamedItem(name)" method returns null if the
// name specified does not exists in the map.
//
// Testing approach - Retrieve the third employee and create a NamedNodeMap
// object from the attributes in its last child.
// Once the list is created, the "removeNamedItem(name)"
// method is invoked where "name" does not exist in the
// map. The method should return null.
//
// Semantic Requirements: 11
//
//----------------------------------------------------------------------------
[Test]
public void core0011M()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0011M");
try
{
results.description = "The \"removeNamedItem(name)\" method returns null "+
"if the specified \"name\" is not in the map.";
//
// Retrieve targeted data and attempt to remove a non-existing attribute.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
computedValue = testNode.Attributes.RemoveNamedItem("district");
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0011M --------------------------
//
//--------------------------- test case core-0012M ---------------------------
//
// Testing feature - The "item(index)" method returns the indexth item in the
// map (test for first item).
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child by
// by invoking the "attributes" attribute. Once
// the list is created, the "item(index)" method is
// invoked with index = 0. This should return the node at
// the first position. Since there are no guarantees that
// first item in the map is the one that was listed first
// in the attribute list the test checks for all of them.
//
// Semantic Requirements: 12
//
//----------------------------------------------------------------------------
[Test]
public void core0012M()
{
//string testName = "core-0012M";
string computedValue = "";
// string expectedValue = "domestic or street";
string expectedValue = "domestic";
System.Xml.XmlNode returnedNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0012M");
try
{
results.description = "Retrieve the first item in the map via the \"item(index)\" method.";
//
// Retrieve targeted data and invoke "item" method.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
returnedNode = testNode.Attributes.Item(0);
computedValue = returnedNode.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0012M --------------------------
//
//--------------------------- test case core-0013M ---------------------------
//
// Testing feature - The "item(index)" method returns the indexth item in the
// map (test for last item).
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child.
// Once the list is created, the "item(index)" method is
// invoked with index = 1. This should return the node at
// the last position. Since there are no guarantees that
// the last item in the map is the one that was listed last
// in the attribute list, the test checks for all of them.
//
// Semantic Requirements: 12
//
//----------------------------------------------------------------------------
[Test]
public void core0013M()
{
string computedValue = "";
// string expectedValue = "domestic or street";
string expectedValue = "street";
System.Xml.XmlNode returnedNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0013M");
try
{
results.description = "Retrieve the last item in the map via the \"item(index)\" method.";
//
// Retrieve targeted data and invoke "item" attribute.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
returnedNode = testNode.Attributes.Item(1);
computedValue = returnedNode.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0013M --------------------------
//
//--------------------------- test case core-0014M ---------------------------
//
// Testing feature - The "item(index)" method returns null if the index is
// greater than the number of nodes in the map.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child.
// element by invoking the "attributes" attribute. Once
// the list is created, the "item(index)" method is
// invoked with index = 3. This index value is greater than
// the number of nodes in the map and under that condition
// the method should return null.
//
// Semantic Requirements: 13
//
//----------------------------------------------------------------------------
[Test]
public void core0014M()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0014M");
try
{
results.description = "The \"item(index)\" method returns null if the "+
"index is greater than the number of nodes in the map.";
//
// Retrieve targeted data and invoke "item" method.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
computedValue = testNode.Attributes.Item(3);
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0014M --------------------------
//
//--------------------------- test case core-0015M ---------------------------
//
// Testing feature - The "item(index)" method returns null if the index is
// equal to the number of nodes in the map.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child
// Once the list is created, the "item(index)" method is
// invoked with index = 2. This index value is equal to
// the number of nodes in the map and under that condition
// the method should return null (first item is at position
// 0).
//
// Semantic Requirements: 13
//
//----------------------------------------------------------------------------
[Test]
public void core0015M()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0015M");
try
{
results.description = "The \"item(index)\" method returns null if the index " +
"is equal to the number of nodes in the map.";
//
// Retrieve targeted data and invoke "item" method.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
computedValue = testNode.Attributes.Item(2);
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0015M --------------------------
//
//--------------------------- test case core-0016M ---------------------------
//
// Testing feature - The "length" attribute contains the total number of
// nodes in the map.
//
// Testing approach - Retrieve the second employee and create a NamedNodeMap
// object from the attributes in its last child.
// Once the list is created, the "length" attribute is
// invoked. That attribute should contain the number 2.
//
// Semantic Requirements: 14
//
//----------------------------------------------------------------------------
[Test]
public void core0016M()
{
string computedValue = "";
string expectedValue = "2";
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0016M");
try
{
results.description = "The \"length\" attribute contains the number of " +
"nodes in the map.";
//
// Retrieve targeted data and invoke "length" attribute.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
computedValue = testNode.Attributes.Count.ToString();
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0016M --------------------------
//
//--------------------------- test case core-0017M ---------------------------
//
// Testing feature - The range of valid child nodes indices is 0 to length - 1.
//
// Testing approach - Create a NamedNodeMap object from the attributes of the
// last child of the third employee and traverse the
// list from index 0 to index length - 1. All indices
// should be valid.
//
// Semantic Requirements: 15
//
//----------------------------------------------------------------------------
[Test]
public void core0017M()
{
string computedValue = "";
string expectedValue = "0 1 ";
int lastIndex = 0;
//string attributes = "";
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0017M");
try
{
results.description = "The range of valid child nodes indices is 0 to " +
"length - 1.";
//
// Retrieve targeted data and compute list length.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
lastIndex = testNode.Attributes.Count - 1;
//
// Traverse the list from 0 to length - 1. All indices should be valid.
//
for (int index = 0;index <= lastIndex; index++)
computedValue += index+" ";
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results.
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0017M --------------------------
//
//--------------------------- test case core-0018M ---------------------------
//
// Testing feature - The "setNamedItem(arg) method raises a System.ArgumentException
// Exception if "arg" was created from a different
// document than the one that created the NamedNodeMap.
//
// Testing approach - Create a NamedNodeMap object from the attributes of the
// last child of the third employee and attempt to
// add another Attr node to it that was created from a
// different DOM document. This condition should raise
// the desired exception. This method uses the
// "createAttribute(name)" method from the Document
// interface.
//
// Semantic Requirements: 16
//
//----------------------------------------------------------------------------
[Test]
[Category ("NotDotNet")] // MS DOM is buggy
public void core0018M()
{
string computedValue = "";
System.Xml.XmlAttribute newAttrNode = util.getOtherDOMDocument().CreateAttribute("newAttribute");
System.Xml.XmlNode testNode = null;
string expectedValue = "System.ArgumentException";
testResults results = new testResults("Core0018M");
results.description = "The \"setNamedItem(arg)\" method raises a "+
"System.ArgumentException Exception if \"arg\" was " +
"created from a document different from the one that created "+
"the NamedNodeList.";
//
// Retrieve targeted data and attempt to add an element that was created
// from a different document. Should raise an exception.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
try
{
testNode.Attributes.SetNamedItem(newAttrNode);
}
catch(System.Exception ex)
{
computedValue = ex.GetType().ToString();
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0018M --------------------------
//
//--------------------------- test case core-0019M ---------------------------
//
// Testing feature - The "setNamedItem(arg) method raises a
// NO_MODIFICATION_ALLOWED_ERR Exception if this
// NamedNodeMap is readonly.
//
// Testing approach - Create a NamedNodeMap object from the first child of the
// Entity named "ent4" inside the DocType node and then
// attempt to add a new item to the list. It should raise
// the desired exception as this is a readonly NamedNodeMap.
//
// Semantic Requirements: 17
//
//----------------------------------------------------------------------------
[Test]
[Category ("NotDotNet")] // MS DOM is buggy
public void core0019M()
{
string computedValue = "";
System.Xml.XmlNode testNode = null;
System.Xml.XmlNode entityDesc;
System.Xml.XmlAttribute newAttrNode = (System.Xml.XmlAttribute)util.createNode(util.ATTRIBUTE_NODE,"newAttribute");
string expectedValue = "System.ArgumentException";//util.NO_MODIFICATION_ALLOWED_ERR;
testResults results = new testResults("Core0019M");
results.description = "The \"setNamedItem(arg)\" method raises a " +
"NO_MODIFICATION_ALLOWED_ERR Exception if this "+
"NamedNodeMap is readonly.";
//
// Create a NamedNodeMap object and attempt to add a node to it.
// Should raise an exception.
//
testNode = util.getEntity("ent4");
entityDesc = testNode.FirstChild;
try
{
entityDesc.Attributes.SetNamedItem(newAttrNode);
}
catch(ArgumentException ex)
{
computedValue = ex.GetType ().FullName;
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0019M --------------------------
//
//--------------------------- test case core-0020M ---------------------------
//
// Testing feature - The "setNamedItem(arg) method raises an
// INUSE_ATTRIBUTE_ERR Exception if "arg" is an Attr
// that is already an attribute of another Element.
//
// Testing approach - Create a NamedNodeMap object from the attributes of the
// third child and attempt to add an attribute that is
// already being used by the first employee. An attempt
// to add such an attribute should raise the desired
// exception.
//
// Semantic Requirements: 18
//
//----------------------------------------------------------------------------
[Test]
[Category ("NotDotNet")]
public void core0020M()
{
string computedValue= "";
System.Xml.XmlAttribute inUseAttribute = null;
System.Xml.XmlElement firstEmployee = null;
System.Xml.XmlNode testNode = null;
string expectedValue = "System.ArgumentException";//util.INUSE_ATTRIBUTE_ERR;
testResults results = new testResults("Core0020M");
try
{
results.description = "The \"setNamedItem(arg)\" method raises an "+
"INUSE_ATTRIBUTE_ERR Exception if \"arg\" "+
"is an Attr node that is already an attribute "+
"of another Element.";
firstEmployee = (System.Xml.XmlElement)util.nodeObject(util.FIRST,util.SIXTH);
inUseAttribute = firstEmployee.GetAttributeNode("domestic");
//
// Attempt to add an attribute that is already used by another element
// should raise an exception.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
try
{
testNode.Attributes.SetNamedItem(inUseAttribute);
}
catch (System.Exception ex)
{
computedValue = ex.GetType ().FullName;
}
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0020M --------------------------
//
//--------------------------- test case core-0021M ---------------------------
//
// Testing feature - The "removeNamedItem(name) method raises an
// NOT_FOUND_ERR Exception if there is no node
// named "name" in the map.
//
// Testing approach - Create a NamedNodeMap object from the attributes of the
// last child of the third employee and attempt to
// remove the "district" attribute. There is no node named
// "district" in the list and therefore the desired
// exception should be raised.
//
// System.Xml - return null, if a matching node was not found.
//
// Semantic Requirements: 19
//
//----------------------------------------------------------------------------
[Test]
public void core0021M()
{
object computedValue = null;
System.Xml.XmlNode testNode = null;
object expectedValue = null;//util.NOT_FOUND1_ERR;
testResults results = new testResults("Core0021M");
try
{
results.description = "The \"removeNamedItem(name)\" method raises a " +
"NOT_FOUND_ERR Exception if there is no node "+
"named \"name\" in the map.";
//
// Create a NamedNodeMap object and attempt to remove an attribute that
// is not in the list should raise an exception.
//
testNode = util.nodeObject(util.THIRD,util.SIXTH);
try
{
//null if a matching node was not found
computedValue = testNode.Attributes.RemoveNamedItem("district");
}
catch(System.Exception ex)
{
computedValue = ex.Message;
}
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
util.resetData();
AssertEquals (results.expected, results.actual);
}
//------------------------ End test case core-0021M --------------------------
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Xap
{
// NOTE the documentation for this stuff in particular is VERY lacking! Several events
// have no details (do they even exist?) and some of it is just plain wrong. It's also
// often unclear whether a number is an int or a float, and at least sometimes it can
// be either depending on context.
[Serializable]
public abstract class EventBase : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
// Derived classes should attempt to SetProperty first, and call into this class if they can't
switch ( propertyName )
{
case "Event Header":
m_header = new EventHeader();
m_header.Parse( source, ref line, OwnerProject );
break;
default:
return false;
}
return true;
}
public EventHeader m_header;
}
#region Event types
[Serializable]
public class PlayWaveEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Loop Count":
m_loopCount = Parser.ParseInt( value, line );
break;
case "Break Loop":
m_breakLoop = Parser.ParseInt( value, line );
break;
case "Use Speaker Position":
m_useSpeakerPosition = Parser.ParseInt( value, line );
break;
case "Use Center Speaker":
m_useCentreSpeaker = Parser.ParseInt( value, line );
break;
case "New Speaker Position On Loop":
m_newSpeakerPositionOnLoop = Parser.ParseInt( value, line );
break;
case "Speaker Position Angle":
m_speakerPositionAngle = Parser.ParseFloat( value, line );
break;
case "Speaer Position Arc": // XACT typo, not mine!
case "Speaker Position Arc": // In case they fix the typo
m_speakerPositionArc = Parser.ParseFloat( value, line );
break;
case "Wave Entry":
WaveEntry wave = new WaveEntry();
wave.Parse( source, ref line, OwnerProject );
m_waveEntries.Add( wave );
break;
case "Pitch Variation":
m_pitchVariation = new PitchVariation();
m_pitchVariation.Parse( source, ref line, OwnerProject );
break;
case "Volume Variation":
m_volumeVariation = new VolumeVariation();
m_volumeVariation.Parse( source, ref line, OwnerProject );
break;
case "Variation":
m_variation = new Variation();
m_variation.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public int m_loopCount;
public int m_breakLoop;
public int m_useSpeakerPosition;
public int m_useCentreSpeaker;
public int m_newSpeakerPositionOnLoop;
public float m_speakerPositionAngle;
public float m_speakerPositionArc;
public PitchVariation m_pitchVariation;
public VolumeVariation m_volumeVariation;
public Variation m_variation;
public List<WaveEntry> m_waveEntries = new List<WaveEntry>();
}
[Serializable]
public class PlaySoundEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Variation":
m_variation = new Variation();
m_variation.Parse( source, ref line, OwnerProject );
break;
case "Sound Entry":
SoundEntry soundEntry = new SoundEntry();
soundEntry.Parse( source, ref line, OwnerProject );
m_soundEntries.Add( soundEntry );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public EventHeader m_eventHeader;
public Variation m_variation;
public List<SoundEntry> m_soundEntries = new List<SoundEntry>();
}
[Serializable]
public class StopEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Immediate":
m_immediate = Parser.ParseInt( value, line );
break;
case "Stop Cue":
m_stopCue = Parser.ParseInt( value, line );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public int m_immediate;
public int m_stopCue;
}
[Serializable]
public class BranchEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
// Docs say "not supported" but I'm not sure that that's true!
case "Conditional":
m_conditional = new Conditional();
m_conditional.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public Conditional m_conditional;
}
[Serializable]
public class WaitEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Pause Playback":
m_pause = Parser.ParseInt( value, line );
break;
case "Conditional":
m_conditional = new Conditional();
m_conditional.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public int m_pause;
public Conditional m_conditional;
}
[Serializable]
public class SetEffectParameterEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Name":
m_name = value;
break;
case "Minimum":
m_min = Parser.ParseIntOrFloat( value, line );
break;
case "Maximum":
m_max = Parser.ParseIntOrFloat( value, line );
break;
case "Value":
m_value = Parser.ParseIntOrFloat( value, line );
break;
case "Type":
m_type = Parser.ParseInt( value, line );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public string m_name;
public float m_min;
public float m_max;
public float m_value;
public int m_type; // 0: float, 1: integer.... nice
}
[Serializable]
public class SetVariableEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Variable Entry":
m_variable = new VariableEntry();
m_variable.Parse( source, ref line, OwnerProject );
break;
case "Equation":
m_equation = new Equation();
m_equation.Parse( source, ref line, OwnerProject );
break;
case "Recurrence":
m_recurrence = new Recurrence();
m_recurrence.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public VariableEntry m_variable;
public Equation m_equation;
public Recurrence m_recurrence;
}
[Serializable]
public class SetPitchEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Ramp":
m_ramp = new Ramp();
m_ramp.Parse( source, ref line, OwnerProject );
break;
case "Equation":
m_equation = new Equation();
m_equation.Parse( source, ref line, OwnerProject );
break;
case "Recurrence":
m_recurrence = new Recurrence();
m_recurrence.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public Ramp m_ramp;
public Equation m_equation;
public Recurrence m_recurrence;
}
[Serializable]
public class SetVolumeEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Ramp":
m_ramp = new Ramp();
m_ramp.Parse( source, ref line, OwnerProject );
break;
case "Equation":
m_equation = new Equation();
m_equation.Parse( source, ref line, OwnerProject );
break;
case "Recurrence":
m_recurrence = new Recurrence();
m_recurrence.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public Ramp m_ramp;
public Equation m_equation;
public Recurrence m_recurrence;
}
[Serializable]
public class MarkerEvent : EventBase
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Data":
m_data = Parser.ParseInt( value, line );
break;
case "Recurrence":
m_recurrence = new Recurrence();
m_recurrence.Parse( source, ref line, OwnerProject );
break;
default:
return base.SetProperty( propertyName, value, source, ref line );
}
return true;
}
public int m_data;
public Recurrence m_recurrence;
}
#endregion
#region Event attributes
[Serializable]
public class EventHeader : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Comment":
m_comment = Parser.ParseComment( value, source, ref line );
break;
case "Timestamp":
m_timestamp = Parser.ParseInt( value, line );
break;
case "Relative":
m_relative = Parser.ParseInt( value, line );
break;
case "Relative Event Index":
m_relativeEventIndex = Parser.ParseInt( value, line );
break;
case "Relative To Start":
m_relativeToStart = Parser.ParseInt( value, line );
break;
case "Random Offset":
m_randomOffset = Parser.ParseInt( value, line );
break;
case "Random Recurrence":
m_randomRecurrence = Parser.ParseInt( value, line );
break;
default:
return false;
}
return true;
}
public int m_timestamp;
public int m_relative;
public int m_relativeEventIndex;
public int m_relativeToStart;
public int m_randomOffset;
public int m_randomRecurrence;
public string m_comment;
}
[Serializable]
public class Conditional : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Type":
m_type = Parser.ParseInt( value, line );
break;
case "Operand":
Operand operand = new Operand();
operand.Parse( source, ref line, OwnerProject );
m_operands.Add( operand );
break;
case "Operator1":
m_operator1 = Parser.ParseInt( value, line );
break;
case "Operator2":
m_operator2 = Parser.ParseInt( value, line );
break;
default:
return false;
}
return true;
}
public int m_type;
public List<Operand> m_operands;
public int m_operator1;
public int m_operator2 = -1;
}
[Serializable]
public class Operand : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Variable Entry":
m_variableEntry = new VariableEntry();
m_variableEntry.Parse( source, ref line, OwnerProject );
break;
case "Constant":
m_constant = Parser.ParseFloat( value, line );
break;
case "Min Random":
m_minRandom = Parser.ParseFloat( value, line );
break;
case "Max Random":
m_maxRandom = Parser.ParseFloat( value, line );
break;
default:
return false;
}
return true;
}
// Docs say "only one of the following can exist", remember that when it comes to writing them out
public VariableEntry m_variableEntry;
public float m_constant = float.NaN;
public float m_minRandom = float.NaN;
public float m_maxRandom = float.NaN;
}
[Serializable]
public class Equation : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Operator":
m_operator = Parser.ParseInt( value, line );
break;
case "Operand":
m_operand = new Operand();
m_operand.Parse( source, ref line, OwnerProject );
break;
default:
return false;
}
return true;
}
public Operand m_operand;
public int m_operator;
}
[Serializable]
public class Recurrence : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Count":
m_count = Parser.ParseInt( value, line );
break;
case "Frequency":
m_frequency = Parser.ParseInt( value, line );
break;
case "Beats Per Minute":
m_bpm = Parser.ParseInt( value, line );
break;
case "Beats Per Minute Frequency": // Not in docs
m_bpmFrequency = Parser.ParseFloat( value, line );
break;
default:
return false;
}
return true;
}
public int m_count;
public int m_frequency;
public int m_bpm;
public float m_bpmFrequency;
}
[Serializable]
public class Ramp : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Initial Value":
m_initialValue = Parser.ParseFloat( value, line );
break;
case "Slope":
m_slope = Parser.ParseFloat( value, line );
break;
case "Slope Delta":
m_slopeDelta = Parser.ParseFloat( value, line );
break;
case "Duration":
m_duration = Parser.ParseInt( value, line );
break;
default:
return false;
}
return true;
}
public float m_initialValue;
public float m_slope;
public float m_slopeDelta;
public int m_duration;
}
#endregion
}
| |
#region BSD License
/*
Copyright (c) 2008 Matthew Holmes (matthew@wildfiregames.com), John Anderson (sontek@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
using System.CodeDom.Compiler;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
public abstract class VSGenericTarget : ITarget
{
#region Fields
readonly Dictionary<string, ToolInfo> tools = new Dictionary<string, ToolInfo>();
// NameValueCollection CopyFiles = new NameValueCollection();
Kernel kernel;
#endregion
#region Properties
/// <summary>
/// Gets or sets the solution version.
/// </summary>
/// <value>The solution version.</value>
public abstract string SolutionVersion { get; }
/// <summary>
/// Gets or sets the product version.
/// </summary>
/// <value>The product version.</value>
public abstract string ProductVersion { get; }
/// <summary>
/// Gets or sets the schema version.
/// </summary>
/// <value>The schema version.</value>
public abstract string SchemaVersion { get; }
/// <summary>
/// Gets or sets the name of the version.
/// </summary>
/// <value>The name of the version.</value>
public abstract string VersionName { get; }
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
public abstract VSVersion Version { get; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public abstract string Name { get; }
protected abstract string GetToolsVersionXml(FrameworkVersion version);
public abstract string SolutionTag { get; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="VSGenericTarget"/> class.
/// </summary>
protected VSGenericTarget()
{
tools["C#"] = new ToolInfo("C#", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "csproj", "CSHARP", "$(MSBuildBinPath)\\Microsoft.CSharp.targets");
tools["Database"] = new ToolInfo("Database", "{4F174C21-8C12-11D0-8340-0000F80270F8}", "dbp", "UNKNOWN");
tools["Boo"] = new ToolInfo("Boo", "{45CEA7DC-C2ED-48A6-ACE0-E16144C02365}", "booproj", "Boo", "$(BooBinPath)\\Boo.Microsoft.Build.targets");
tools["VisualBasic"] = new ToolInfo("VisualBasic", "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}", "vbproj", "VisualBasic", "$(MSBuildBinPath)\\Microsoft.VisualBasic.Targets");
tools["Folder"] = new ToolInfo("Folder", "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", null, null);
}
#endregion
#region Private Methods
private string MakeRefPath(ProjectNode project)
{
string ret = "";
foreach (ReferencePathNode node in project.ReferencePaths)
{
try
{
string fullPath = Helper.ResolvePath(node.Path);
if (ret.Length < 1)
{
ret = fullPath;
}
else
{
ret += ";" + fullPath;
}
}
catch (ArgumentException)
{
kernel.Log.Write(LogType.Warning, "Could not resolve reference path: {0}", node.Path);
}
}
return ret;
}
private static ProjectNode FindProjectInSolution(string name, SolutionNode solution)
{
SolutionNode node = solution;
while (node.Parent is SolutionNode)
node = node.Parent as SolutionNode;
return FindProjectInSolutionRecursively(name, node);
}
private static ProjectNode FindProjectInSolutionRecursively(string name, SolutionNode solution)
{
if (solution.ProjectsTable.ContainsKey(name))
return solution.ProjectsTable[name];
foreach (SolutionNode child in solution.Solutions)
{
ProjectNode node = FindProjectInSolutionRecursively(name, child);
if (node != null)
return node;
}
return null;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
if (!tools.ContainsKey(project.Language))
{
throw new UnknownLanguageException("Unknown .NET language: " + project.Language);
}
ToolInfo toolInfo = tools[project.Language];
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, toolInfo.FileExtension);
StreamWriter ps = new StreamWriter(projectFile);
kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projectFile));
#region Project File
using (ps)
{
string targets = "";
if(project.Files.CopyFiles > 0)
targets = "Build;CopyFiles";
else
targets = "Build";
ps.WriteLine("<Project DefaultTargets=\"{0}\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" {1}>", targets, GetToolsVersionXml(project.FrameworkVersion));
ps.WriteLine(" <PropertyGroup>");
ps.WriteLine(" <ProjectType>Local</ProjectType>");
ps.WriteLine(" <ProductVersion>{0}</ProductVersion>", ProductVersion);
ps.WriteLine(" <SchemaVersion>{0}</SchemaVersion>", SchemaVersion);
ps.WriteLine(" <ProjectGuid>{{{0}}}</ProjectGuid>", project.Guid.ToString().ToUpper());
// Visual Studio has a hard coded guid for the project type
if (project.Type == ProjectType.Web)
ps.WriteLine(" <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>");
ps.WriteLine(" <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>");
ps.WriteLine(" <ApplicationIcon>{0}</ApplicationIcon>", project.AppIcon);
ps.WriteLine(" <AssemblyKeyContainerName>");
ps.WriteLine(" </AssemblyKeyContainerName>");
ps.WriteLine(" <AssemblyName>{0}</AssemblyName>", project.AssemblyName);
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ps.WriteLine(" <AssemblyOriginatorKeyFile>{0}</AssemblyOriginatorKeyFile>", conf.Options.KeyFile);
ps.WriteLine(" <SignAssembly>true</SignAssembly>");
break;
}
}
ps.WriteLine(" <DefaultClientScript>JScript</DefaultClientScript>");
ps.WriteLine(" <DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>");
ps.WriteLine(" <DefaultTargetSchema>IE50</DefaultTargetSchema>");
ps.WriteLine(" <DelaySign>false</DelaySign>");
ps.WriteLine(" <TargetFrameworkVersion>{0}</TargetFrameworkVersion>", project.FrameworkVersion.ToString().Replace("_", "."));
ps.WriteLine(" <OutputType>{0}</OutputType>", project.Type == ProjectType.Web ? ProjectType.Library.ToString() : project.Type.ToString());
ps.WriteLine(" <AppDesignerFolder>{0}</AppDesignerFolder>", project.DesignerFolder);
ps.WriteLine(" <RootNamespace>{0}</RootNamespace>", project.RootNamespace);
ps.WriteLine(" <StartupObject>{0}</StartupObject>", project.StartupObject);
if (string.IsNullOrEmpty(project.DebugStartParameters))
{
ps.WriteLine(" <StartArguments>{0}</StartArguments>", project.DebugStartParameters);
}
ps.WriteLine(" <FileUpgradeFlags>");
ps.WriteLine(" </FileUpgradeFlags>");
ps.WriteLine(" </PropertyGroup>");
if (!string.IsNullOrEmpty(project.ApplicationManifest))
{
ps.WriteLine(" <PropertyGroup>");
ps.WriteLine(" <ApplicationManifest>" + project.ApplicationManifest + "</ApplicationManifest>");
ps.WriteLine(" </PropertyGroup>");
}
foreach (ConfigurationNode conf in project.Configurations)
{
ps.Write(" <PropertyGroup ");
ps.WriteLine("Condition=\" '$(Configuration)|$(Platform)' == '{0}|{1}' \">", conf.Name, conf.Platform);
ps.WriteLine(" <AllowUnsafeBlocks>{0}</AllowUnsafeBlocks>", conf.Options["AllowUnsafe"]);
ps.WriteLine(" <BaseAddress>{0}</BaseAddress>", conf.Options["BaseAddress"]);
ps.WriteLine(" <CheckForOverflowUnderflow>{0}</CheckForOverflowUnderflow>", conf.Options["CheckUnderflowOverflow"]);
ps.WriteLine(" <ConfigurationOverrideFile>");
ps.WriteLine(" </ConfigurationOverrideFile>");
ps.WriteLine(" <DefineConstants>{0}</DefineConstants>",
conf.Options["CompilerDefines"].ToString() == "" ? this.kernel.ForcedConditionals : conf.Options["CompilerDefines"] + ";" + kernel.ForcedConditionals);
ps.WriteLine(" <DocumentationFile>{0}</DocumentationFile>", Helper.NormalizePath(conf.Options["XmlDocFile"].ToString()));
ps.WriteLine(" <DebugSymbols>{0}</DebugSymbols>", conf.Options["DebugInformation"]);
ps.WriteLine(" <FileAlignment>{0}</FileAlignment>", conf.Options["FileAlignment"]);
ps.WriteLine(" <Optimize>{0}</Optimize>", conf.Options["OptimizeCode"]);
if (project.Type != ProjectType.Web)
ps.WriteLine(" <OutputPath>{0}</OutputPath>",
Helper.EndPath(Helper.NormalizePath(conf.Options["OutputPath"].ToString())));
else
ps.WriteLine(" <OutputPath>{0}</OutputPath>",
Helper.EndPath(Helper.NormalizePath("bin\\")));
ps.WriteLine(" <RegisterForComInterop>{0}</RegisterForComInterop>", conf.Options["RegisterComInterop"]);
ps.WriteLine(" <RemoveIntegerChecks>{0}</RemoveIntegerChecks>", conf.Options["RemoveIntegerChecks"]);
ps.WriteLine(" <TreatWarningsAsErrors>{0}</TreatWarningsAsErrors>", conf.Options["WarningsAsErrors"]);
ps.WriteLine(" <WarningLevel>{0}</WarningLevel>", conf.Options["WarningLevel"]);
ps.WriteLine(" <NoStdLib>{0}</NoStdLib>", conf.Options["NoStdLib"]);
ps.WriteLine(" <NoWarn>{0}</NoWarn>", conf.Options["SuppressWarnings"]);
ps.WriteLine(" <PlatformTarget>{0}</PlatformTarget>", conf.Platform);
ps.WriteLine(" <Prefer32Bit>{0}</Prefer32Bit>",conf.Options["Prefer32Bit"]);
ps.WriteLine(" </PropertyGroup>");
}
//ps.WriteLine(" </Settings>");
Dictionary<ReferenceNode, ProjectNode> projectReferences = new Dictionary<ReferenceNode, ProjectNode>();
List<ReferenceNode> otherReferences = new List<ReferenceNode>();
foreach (ReferenceNode refr in project.References)
{
ProjectNode projectNode = FindProjectInSolution(refr.Name, solution);
if (projectNode == null)
otherReferences.Add(refr);
else
projectReferences.Add(refr, projectNode);
}
// Assembly References
ps.WriteLine(" <ItemGroup>");
foreach (ReferenceNode refr in otherReferences)
{
ps.Write(" <Reference");
ps.Write(" Include=\"");
ps.Write(refr.Name);
ps.WriteLine("\" >");
ps.Write(" <Name>");
ps.Write(refr.Name);
ps.WriteLine("</Name>");
if(!String.IsNullOrEmpty(refr.Path))
{
// Use absolute path to assembly (for determining assembly type)
string absolutePath = Path.Combine(project.FullPath, refr.Path);
if(File.Exists(Helper.MakeFilePath(absolutePath, refr.Name, "exe"))) {
// Assembly is an executable (exe)
ps.WriteLine(" <HintPath>{0}</HintPath>", Helper.MakeFilePath(refr.Path, refr.Name, "exe"));
} else if(File.Exists(Helper.MakeFilePath(absolutePath, refr.Name, "dll"))) {
// Assembly is an library (dll)
ps.WriteLine(" <HintPath>{0}</HintPath>", Helper.MakeFilePath(refr.Path, refr.Name, "dll"));
} else {
string referencePath = Helper.MakeFilePath(refr.Path, refr.Name, "dll");
kernel.Log.Write(LogType.Warning, "Reference \"{0}\": The specified file doesn't exist.", referencePath);
ps.WriteLine(" <HintPath>{0}</HintPath>", Helper.MakeFilePath(refr.Path, refr.Name, "dll"));
}
}
ps.WriteLine(" <Private>{0}</Private>", refr.LocalCopy);
ps.WriteLine(" </Reference>");
}
ps.WriteLine(" </ItemGroup>");
//Project References
ps.WriteLine(" <ItemGroup>");
foreach (KeyValuePair<ReferenceNode, ProjectNode> pair in projectReferences)
{
ToolInfo tool = tools[pair.Value.Language];
if (tools == null)
throw new UnknownLanguageException();
string path =
Helper.MakePathRelativeTo(project.FullPath,
Helper.MakeFilePath(pair.Value.FullPath, pair.Value.Name, tool.FileExtension));
ps.WriteLine(" <ProjectReference Include=\"{0}\">", path);
// TODO: Allow reference to visual basic projects
ps.WriteLine(" <Name>{0}</Name>", pair.Value.Name);
ps.WriteLine(" <Project>{0}</Project>", pair.Value.Guid.ToString("B").ToUpper());
ps.WriteLine(" <Package>{0}</Package>", tool.Guid.ToUpper());
//This is the Copy Local flag in VS
ps.WriteLine(" <Private>{0}</Private>", pair.Key.LocalCopy);
ps.WriteLine(" </ProjectReference>");
}
ps.WriteLine(" </ItemGroup>");
// ps.WriteLine(" </Build>");
ps.WriteLine(" <ItemGroup>");
// ps.WriteLine(" <Include>");
List<string> list = new List<string>();
foreach (string path in project.Files)
{
string lower = path.ToLower();
if (lower.EndsWith(".resx"))
{
string codebehind = String.Format("{0}.Designer{1}", path.Substring(0, path.LastIndexOf('.')), toolInfo.LanguageExtension);
if (!list.Contains(codebehind))
list.Add(codebehind);
}
}
foreach (string filePath in project.Files)
{
// Add the filePath with the destination as the key
// will use it later to form the copy parameters with Include lists
// for each destination
if (project.Files.GetBuildAction(filePath) == BuildAction.Copy)
continue;
// if (file == "Properties\\Bind.Designer.cs")
// {
// Console.WriteLine("Wait a minute!");
// Console.WriteLine(project.Files.GetSubType(file).ToString());
// }
SubType subType = project.Files.GetSubType(filePath);
// Visual Studio chokes on file names if forward slash is used as a path separator
// instead of backslash. So we must make sure that all file paths written to the
// project file use \ as a path separator.
string file = filePath.Replace(@"/", @"\");
if (subType != SubType.Code && subType != SubType.Settings && subType != SubType.Designer
&& subType != SubType.CodeBehind)
{
ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx");
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(file));
ps.WriteLine(" <SubType>Designer</SubType>");
ps.WriteLine(" </EmbeddedResource>");
//
}
if (subType == SubType.Designer)
{
ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file);
string autogen_name = file.Substring(0, file.LastIndexOf('.')) + ".Designer.cs";
string dependent_name = filePath.Substring(0, file.LastIndexOf('.')) + ".cs";
// Check for a parent .cs file with the same name as this designer file
if (File.Exists(Helper.NormalizePath(dependent_name)))
{
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(dependent_name));
}
else
{
ps.WriteLine(" <Generator>ResXFileCodeGenerator</Generator>");
ps.WriteLine(" <LastGenOutput>{0}</LastGenOutput>", Path.GetFileName(autogen_name));
ps.WriteLine(" <SubType>" + subType + "</SubType>");
}
ps.WriteLine(" </EmbeddedResource>");
if (File.Exists(Helper.NormalizePath(autogen_name)))
{
ps.WriteLine(" <Compile Include=\"{0}\">", autogen_name);
//ps.WriteLine(" <DesignTime>True</DesignTime>");
// If a parent .cs file exists, link this autogen file to it. Otherwise link
// to the designer file
if (File.Exists(dependent_name))
{
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(dependent_name));
}
else
{
ps.WriteLine(" <AutoGen>True</AutoGen>");
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(filePath));
}
ps.WriteLine(" </Compile>");
}
list.Add(autogen_name);
}
if (subType == SubType.Settings)
{
ps.Write(" <{0} ", project.Files.GetBuildAction(filePath));
ps.WriteLine("Include=\"{0}\">", file);
string fileName = Path.GetFileName(filePath);
if (project.Files.GetBuildAction(filePath) == BuildAction.None)
{
ps.WriteLine(" <Generator>SettingsSingleFileGenerator</Generator>");
ps.WriteLine(" <LastGenOutput>{0}</LastGenOutput>", fileName.Substring(0, fileName.LastIndexOf('.')) + ".Designer.cs");
}
else
{
ps.WriteLine(" <SubType>Code</SubType>");
ps.WriteLine(" <AutoGen>True</AutoGen>");
ps.WriteLine(" <DesignTimeSharedInput>True</DesignTimeSharedInput>");
string fileNameShort = fileName.Substring(0, fileName.LastIndexOf('.'));
string fileNameShorter = fileNameShort.Substring(0, fileNameShort.LastIndexOf('.'));
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(fileNameShorter + ".settings"));
}
ps.WriteLine(" </{0}>", project.Files.GetBuildAction(filePath));
}
else if (subType != SubType.Designer)
{
string path = Helper.NormalizePath(file);
string path_lower = path.ToLower();
if (!list.Contains(filePath))
{
ps.Write(" <{0} ", project.Files.GetBuildAction(filePath));
int startPos = 0;
if (project.Files.GetPreservePath(filePath))
{
while ((@"./\").IndexOf(file.Substring(startPos, 1)) != -1)
startPos++;
}
else
{
startPos = file.LastIndexOf(Path.GetFileName(path));
}
// be sure to write out the path with backslashes so VS recognizes
// the file properly.
ps.WriteLine("Include=\"{0}\">", file);
int last_period_index = file.LastIndexOf('.');
string short_file_name = (last_period_index >= 0)
? file.Substring(0, last_period_index)
: file;
string extension = Path.GetExtension(path);
// make this upper case, so that when File.Exists tests for the
// existence of a designer file on a case-sensitive platform,
// it is correctly identified.
string designer_format = string.Format(".Designer{0}", extension);
if (path_lower.EndsWith(designer_format.ToLowerInvariant()))
{
int designer_index = path.IndexOf(designer_format);
string file_name = path.Substring(0, designer_index);
// There are two corrections to the next lines:
// 1. Fix the connection between a designer file and a form
// or usercontrol that don't have an associated resx file.
// 2. Connect settings files to associated designer files.
if (File.Exists(file_name + extension))
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(file_name + extension));
else if (File.Exists(file_name + ".resx"))
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(file_name + ".resx"));
else if (File.Exists(file_name + ".settings"))
{
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(file_name + ".settings"));
ps.WriteLine(" <AutoGen>True</AutoGen>");
ps.WriteLine(" <DesignTimeSharedInput>True</DesignTimeSharedInput>");
}
}
else if (subType == SubType.CodeBehind)
{
ps.WriteLine(" <DependentUpon>{0}</DependentUpon>", Path.GetFileName(short_file_name));
}
if (project.Files.GetIsLink(filePath))
{
string alias = project.Files.GetLinkPath(filePath);
alias += file.Substring(startPos);
alias = Helper.NormalizePath(alias);
ps.WriteLine(" <Link>{0}</Link>", alias);
}
else if (project.Files.GetBuildAction(filePath) != BuildAction.None)
{
if (project.Files.GetBuildAction(filePath) != BuildAction.EmbeddedResource)
{
ps.WriteLine(" <SubType>{0}</SubType>", subType);
}
}
if (project.Files.GetCopyToOutput(filePath) != CopyToOutput.Never)
{
ps.WriteLine(" <CopyToOutputDirectory>{0}</CopyToOutputDirectory>", project.Files.GetCopyToOutput(filePath));
}
ps.WriteLine(" </{0}>", project.Files.GetBuildAction(filePath));
}
}
}
ps.WriteLine(" </ItemGroup>");
/*
* Copy Task
*
*/
if ( project.Files.CopyFiles > 0 ) {
Dictionary<string, string> IncludeTags = new Dictionary<string, string>();
int TagCount = 0;
// Handle Copy tasks
ps.WriteLine(" <ItemGroup>");
foreach (string destPath in project.Files.Destinations)
{
string tag = "FilesToCopy_" + TagCount.ToString("0000");
ps.WriteLine(" <{0} Include=\"{1}\" />", tag, String.Join(";", project.Files.SourceFiles(destPath)));
IncludeTags.Add(destPath, tag);
TagCount++;
}
ps.WriteLine(" </ItemGroup>");
ps.WriteLine(" <Target Name=\"CopyFiles\">");
foreach (string destPath in project.Files.Destinations)
{
ps.WriteLine(" <Copy SourceFiles=\"@({0})\" DestinationFolder=\"{1}\" />",
IncludeTags[destPath], destPath);
}
ps.WriteLine(" </Target>");
}
ps.WriteLine(" <Import Project=\"" + toolInfo.ImportProject + "\" />");
ps.WriteLine(" <PropertyGroup>");
ps.WriteLine(" <PreBuildEvent>");
ps.WriteLine(" </PreBuildEvent>");
ps.WriteLine(" <PostBuildEvent>");
ps.WriteLine(" </PostBuildEvent>");
ps.WriteLine(" </PropertyGroup>");
ps.WriteLine("</Project>");
}
#endregion
#region User File
ps = new StreamWriter(projectFile + ".user");
using (ps)
{
// Get the first configuration from the project.
ConfigurationNode firstConfiguration = null;
if (project.Configurations.Count > 0)
{
firstConfiguration = project.Configurations[0];
}
ps.WriteLine("<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">");
//ps.WriteLine( "<VisualStudioProject>" );
//ps.WriteLine(" <{0}>", toolInfo.XMLTag);
//ps.WriteLine(" <Build>");
ps.WriteLine(" <PropertyGroup>");
//ps.WriteLine(" <Settings ReferencePath=\"{0}\">", MakeRefPath(project));
if (firstConfiguration != null)
{
ps.WriteLine(" <Configuration Condition=\" '$(Configuration)' == '' \">{0}</Configuration>", firstConfiguration.Name);
ps.WriteLine(" <Platform Condition=\" '$(Platform)' == '' \">{0}</Platform>", firstConfiguration.Platform);
}
ps.WriteLine(" <ReferencePath>{0}</ReferencePath>", MakeRefPath(project));
ps.WriteLine(" <LastOpenVersion>{0}</LastOpenVersion>", ProductVersion);
ps.WriteLine(" <ProjectView>ProjectFiles</ProjectView>");
ps.WriteLine(" <ProjectTrust>0</ProjectTrust>");
ps.WriteLine(" </PropertyGroup>");
foreach (ConfigurationNode conf in project.Configurations)
{
ps.Write(" <PropertyGroup");
ps.Write(" Condition = \" '$(Configuration)|$(Platform)' == '{0}|{1}' \"", conf.Name, conf.Platform);
ps.WriteLine(" />");
}
ps.WriteLine("</Project>");
}
#endregion
kernel.CurrentWorkingDirectory.Pop();
}
private void WriteSolution(SolutionNode solution, bool writeSolutionToDisk)
{
kernel.Log.Write("Creating {0} solution and project files", VersionName);
foreach (SolutionNode child in solution.Solutions)
{
kernel.Log.Write("...Creating folder: {0}", child.Name);
WriteSolution(child, false);
}
foreach (ProjectNode project in solution.Projects)
{
kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
foreach (DatabaseProjectNode project in solution.DatabaseProjects)
{
kernel.Log.Write("...Creating database project: {0}", project.Name);
WriteDatabaseProject(solution, project);
}
if (writeSolutionToDisk) // only write main solution
{
kernel.Log.Write("");
string solutionFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "sln");
using (StreamWriter ss = new StreamWriter(solutionFile))
{
kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(solutionFile));
ss.WriteLine("Microsoft Visual Studio Solution File, Format Version {0}", SolutionVersion);
ss.WriteLine(SolutionTag);
WriteProjectDeclarations(ss, solution, solution);
ss.WriteLine("Global");
ss.WriteLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
foreach (ConfigurationNode conf in solution.Configurations)
{
ss.WriteLine("\t\t{0} = {0}", conf.NameAndPlatform);
}
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
WriteConfigurationLines(solution.Configurations, solution, ss);
ss.WriteLine("\tEndGlobalSection");
if (solution.Solutions.Count > 0)
{
ss.WriteLine("\tGlobalSection(NestedProjects) = preSolution");
foreach (SolutionNode embeddedSolution in solution.Solutions)
{
WriteNestedProjectMap(ss, embeddedSolution);
}
ss.WriteLine("\tEndGlobalSection");
}
ss.WriteLine("EndGlobal");
}
kernel.CurrentWorkingDirectory.Pop();
}
}
private void WriteProjectDeclarations(TextWriter writer, SolutionNode actualSolution, SolutionNode embeddedSolution)
{
foreach (SolutionNode childSolution in embeddedSolution.Solutions)
{
WriteEmbeddedSolution(writer, childSolution);
WriteProjectDeclarations(writer, actualSolution, childSolution);
}
foreach (ProjectNode project in embeddedSolution.Projects)
{
WriteProject(actualSolution, writer, project);
}
foreach (DatabaseProjectNode dbProject in embeddedSolution.DatabaseProjects)
{
WriteProject(actualSolution, writer, dbProject);
}
if (actualSolution.Guid == embeddedSolution.Guid)
{
WriteSolutionFiles(actualSolution, writer);
}
}
private static void WriteNestedProjectMap(TextWriter writer, SolutionNode embeddedSolution)
{
foreach (ProjectNode project in embeddedSolution.Projects)
{
WriteNestedProject(writer, embeddedSolution, project.Guid);
}
foreach (DatabaseProjectNode dbProject in embeddedSolution.DatabaseProjects)
{
WriteNestedProject(writer, embeddedSolution, dbProject.Guid);
}
foreach (SolutionNode child in embeddedSolution.Solutions)
{
WriteNestedProject(writer, embeddedSolution, child.Guid);
WriteNestedProjectMap(writer, child);
}
}
private static void WriteNestedProject(TextWriter writer, SolutionNode solution, Guid projectGuid)
{
WriteNestedFolder(writer, solution.Guid, projectGuid);
}
private static void WriteNestedFolder(TextWriter writer, Guid parentGuid, Guid childGuid)
{
writer.WriteLine("\t\t{0} = {1}",
childGuid.ToString("B").ToUpper(),
parentGuid.ToString("B").ToUpper());
}
private static void WriteConfigurationLines(IEnumerable<ConfigurationNode> configurations, SolutionNode solution, TextWriter ss)
{
foreach (ProjectNode project in solution.Projects)
{
foreach (ConfigurationNode conf in configurations)
{
ss.WriteLine("\t\t{0}.{1}.ActiveCfg = {1}",
project.Guid.ToString("B").ToUpper(),
conf.NameAndPlatform);
ss.WriteLine("\t\t{0}.{1}.Build.0 = {1}",
project.Guid.ToString("B").ToUpper(),
conf.NameAndPlatform);
}
}
foreach (SolutionNode child in solution.Solutions)
{
WriteConfigurationLines(configurations, child, ss);
}
}
private void WriteSolutionFiles(SolutionNode solution, TextWriter ss)
{
if(solution.Files != null && solution.Files.Count > 0)
WriteProject(ss, "Folder", solution.Guid, "Solution Files", "Solution Files", solution.Files);
}
private void WriteEmbeddedSolution(TextWriter writer, SolutionNode embeddedSolution)
{
WriteProject(writer, "Folder", embeddedSolution.Guid, embeddedSolution.Name, embeddedSolution.Name, embeddedSolution.Files);
}
private void WriteProject(SolutionNode solution, TextWriter ss, ProjectNode project)
{
WriteProject(ss, solution, project.Language, project.Guid, project.Name, project.FullPath);
}
private void WriteProject(SolutionNode solution, TextWriter ss, DatabaseProjectNode dbProject)
{
if (solution.Files != null && solution.Files.Count > 0)
WriteProject(ss, solution, "Database", dbProject.Guid, dbProject.Name, dbProject.FullPath);
}
const string ProjectDeclarationBeginFormat = "Project(\"{0}\") = \"{1}\", \"{2}\", \"{3}\"";
const string ProjectDeclarationEndFormat = "EndProject";
private void WriteProject(TextWriter ss, SolutionNode solution, string language, Guid guid, string name, string projectFullPath)
{
if (!tools.ContainsKey(language))
throw new UnknownLanguageException("Unknown .NET language: " + language);
ToolInfo toolInfo = tools[language];
string path = Helper.MakePathRelativeTo(solution.FullPath, projectFullPath);
path = Helper.MakeFilePath(path, name, toolInfo.FileExtension);
WriteProject(ss, language, guid, name, path);
}
private void WriteProject(TextWriter writer, string language, Guid projectGuid, string name, string location)
{
WriteProject(writer, language, projectGuid, name, location, null);
}
private void WriteProject(TextWriter writer, string language, Guid projectGuid, string name, string location, FilesNode files)
{
if (!tools.ContainsKey(language))
throw new UnknownLanguageException("Unknown .NET language: " + language);
ToolInfo toolInfo = tools[language];
writer.WriteLine(ProjectDeclarationBeginFormat,
toolInfo.Guid,
name,
location,
projectGuid.ToString("B").ToUpper());
if (files != null)
{
writer.WriteLine("\tProjectSection(SolutionItems) = preProject");
foreach (string file in files)
writer.WriteLine("\t\t{0} = {0}", file);
writer.WriteLine("\tEndProjectSection");
}
writer.WriteLine(ProjectDeclarationEndFormat);
}
private void WriteDatabaseProject(SolutionNode solution, DatabaseProjectNode project)
{
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, "dbp");
IndentedTextWriter ps = new IndentedTextWriter(new StreamWriter(projectFile), " ");
kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projectFile));
using (ps)
{
ps.WriteLine("# Microsoft Developer Studio Project File - Database Project");
ps.WriteLine("Begin DataProject = \"{0}\"", project.Name);
ps.Indent++;
ps.WriteLine("MSDTVersion = \"80\"");
// TODO: Use the project.Files property
if (ContainsSqlFiles(Path.GetDirectoryName(projectFile)))
WriteDatabaseFoldersAndFiles(ps, Path.GetDirectoryName(projectFile));
ps.WriteLine("Begin DBRefFolder = \"Database References\"");
ps.Indent++;
foreach (DatabaseReferenceNode reference in project.References)
{
ps.WriteLine("Begin DBRefNode = \"{0}\"", reference.Name);
ps.Indent++;
ps.WriteLine("ConnectStr = \"{0}\"", reference.ConnectionString);
ps.WriteLine("Provider = \"{0}\"", reference.ProviderId.ToString("B").ToUpper());
//ps.WriteLine("Colorizer = 5");
ps.Indent--;
ps.WriteLine("End");
}
ps.Indent--;
ps.WriteLine("End");
ps.Indent--;
ps.WriteLine("End");
ps.Flush();
}
kernel.CurrentWorkingDirectory.Pop();
}
private static bool ContainsSqlFiles(string folder)
{
if(Directory.GetFiles(folder, "*.sql").Length > 0)
return true; // if the folder contains 1 .sql file, that's good enough
foreach (string child in Directory.GetDirectories(folder))
{
if (ContainsSqlFiles(child))
return true; // if 1 child folder contains a .sql file, still good enough
}
return false;
}
private static void WriteDatabaseFoldersAndFiles(IndentedTextWriter writer, string folder)
{
foreach (string child in Directory.GetDirectories(folder))
{
if (ContainsSqlFiles(child))
{
writer.WriteLine("Begin Folder = \"{0}\"", Path.GetFileName(child));
writer.Indent++;
WriteDatabaseFoldersAndFiles(writer, child);
writer.Indent--;
writer.WriteLine("End");
}
}
foreach (string file in Directory.GetFiles(folder, "*.sql"))
{
writer.WriteLine("Script = \"{0}\"", Path.GetFileName(file));
}
}
private void CleanProject(ProjectNode project)
{
kernel.Log.Write("...Cleaning project: {0}", project.Name);
ToolInfo toolInfo = tools[project.Language];
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, toolInfo.FileExtension);
string userFile = projectFile + ".user";
Helper.DeleteIfExists(projectFile);
Helper.DeleteIfExists(userFile);
}
private void CleanSolution(SolutionNode solution)
{
kernel.Log.Write("Cleaning {0} solution and project files", VersionName, solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "sln");
string suoFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "suo");
Helper.DeleteIfExists(slnFile);
Helper.DeleteIfExists(suoFile);
foreach (ProjectNode project in solution.Projects)
{
CleanProject(project);
}
kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Write(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
kernel = kern;
foreach (SolutionNode sol in kernel.Solutions)
{
WriteSolution(sol, true);
}
kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
kernel = kern;
foreach (SolutionNode sol in kernel.Solutions)
{
CleanSolution(sol);
}
kernel = null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace TWS.RestApi.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;
}
}
}
| |
// fMainSendText.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Word = NetOffice.WordApi;
//using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
/*
* Intended as a command-line program invoked to take a body of text written in "WIKI-format"
* and convert it to Word Doc
*
* Stages
* 1. Basic text writing
* 2. Selecting a style sheeting in the opening
* 3. Converting wiki tags (= header 1 =, et cetera) into translated foramtting
* 4. Allow the user to override what formatting does? (or should that just be purely based on the style selected?)
*
*/
namespace SendTextAway
{
public partial class fMain : Form
{
public fMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
/// <summary>
/// Other Control MEthods TO Implement
/// - control over paragraph spacing
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (filename == "")
{
MessageBox.Show("You must open a control file first");
return;
}
SaveCurrentControlFile();
string sFile = Path.GetTempFileName();
StreamWriter writer = new StreamWriter(sFile);
for (int i = 0; i < richTextBox1.Text.Length; i++)
{
writer.Write(richTextBox1.Text[i]);
}
writer.Flush();
writer.Close();
Convert(filename, sFile, 0);
}
/// <summary>
/// wrapper for doing an actual converter
/// </summary>
public string Convert(string sControlFile, string sFile, int stopat)
{
ControlFile zcontrolFile = (ControlFile)CoreUtilities.FileUtils.DeSerialize(sControlFile, typeof(ControlFile));
// may 2010 adding ablity to do epub files too
string sError = "";
if (null != zcontrolFile)
{
sendBase s = null;
if (zcontrolFile.ConverterType == ControlFile.convertertype.word)
{
s = new sendWord();
}
else if (zcontrolFile.ConverterType == ControlFile.convertertype.epub)
{
s = new sendePub2();
}
sError = s.WriteText(sFile, zcontrolFile, stopat);
textBoxErrors.Text = sError;
}
return sError;
}
private string filename = "";
private string Filename
{
get { return filename; }
set { filename = value;
this.Text = filename;
}
}
private void saveAsControlFileToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = MyPath;
save.DefaultExt = "xml";
save.Filter = "Control Files|*.xml";
if (save.ShowDialog() == DialogResult.OK)
{
/* ControlFile controlFile = new ControlFile();
controlFile.Template = "ORA.dot";
controlFile.BodyText = "Body Text,b";
controlFile.ChapterTitle = "ChapterTitle,ct";
controlFile.Heading1 = "Heading 1";
controlFile.Heading2 = "Heading 2";*/
Filename = save.FileName;
SaveCurrentControlFile();
}
}
/// <summary>
/// path to look for control files
/// </summary>
public string MyPath
{
get
{
string path = @"C:\Users\BrentK\Documents\Keeper\SendTextAwayControlFiles";
if (Directory.Exists(path) != true)
{
path = Application.StartupPath;
}
return path;
}
}
private void openControlFileToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = MyPath;
open.DefaultExt = "xml";
open.Filter = "Control Files|*.xml";
if (open.ShowDialog() == DialogResult.OK)
{
Filename = open.FileName;
propertyGrid1.SelectedObject = (ControlFile)CoreUtilities.FileUtils.DeSerialize(
open.FileName, typeof(ControlFile));
}
}
private void SaveCurrentControlFile()
{
if (Filename != "")
{
CoreUtilities.FileUtils.Serialize(propertyGrid1.SelectedObject, Filename,"");
}
}
private void saveControlFileToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveCurrentControlFile();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
propertyGrid1.SelectedObject = new ControlFile();
}
private void fMain_Load(object sender, EventArgs e)
{
}
private void onlyToChapter2ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (filename == "")
{
MessageBox.Show("You must open a control file first");
return;
}
SaveCurrentControlFile();
string sFile = Path.GetTempFileName();
StreamWriter writer = new StreamWriter(sFile);
for (int i = 0; i < richTextBox1.Text.Length; i++)
{
writer.Write(richTextBox1.Text[i]);
}
writer.Flush();
writer.Close();
Convert(filename, sFile, 2);
}
private void tasksToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
}
| |
namespace android.location
{
[global::MonoJavaBridge.JavaClass()]
public partial class Address : java.lang.Object, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Address()
{
InitJNI();
}
protected Address(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _toString4649;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._toString4649)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._toString4649)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getLocality4650;
public virtual global::java.lang.String getLocality()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getLocality4650)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getLocality4650)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _writeToParcel4651;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._writeToParcel4651, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._writeToParcel4651, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents4652;
public virtual int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.location.Address._describeContents4652);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._describeContents4652);
}
internal static global::MonoJavaBridge.MethodId _getExtras4653;
public virtual global::android.os.Bundle getExtras()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getExtras4653)) as android.os.Bundle;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getExtras4653)) as android.os.Bundle;
}
internal static global::MonoJavaBridge.MethodId _getLocale4654;
public virtual global::java.util.Locale getLocale()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getLocale4654)) as java.util.Locale;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getLocale4654)) as java.util.Locale;
}
internal static global::MonoJavaBridge.MethodId _getMaxAddressLineIndex4655;
public virtual int getMaxAddressLineIndex()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.location.Address._getMaxAddressLineIndex4655);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getMaxAddressLineIndex4655);
}
internal static global::MonoJavaBridge.MethodId _getAddressLine4656;
public virtual global::java.lang.String getAddressLine(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getAddressLine4656, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getAddressLine4656, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setAddressLine4657;
public virtual void setAddressLine(int arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setAddressLine4657, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setAddressLine4657, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getFeatureName4658;
public virtual global::java.lang.String getFeatureName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getFeatureName4658)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getFeatureName4658)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setFeatureName4659;
public virtual void setFeatureName(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setFeatureName4659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setFeatureName4659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getAdminArea4660;
public virtual global::java.lang.String getAdminArea()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getAdminArea4660)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getAdminArea4660)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setAdminArea4661;
public virtual void setAdminArea(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setAdminArea4661, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setAdminArea4661, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSubAdminArea4662;
public virtual global::java.lang.String getSubAdminArea()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getSubAdminArea4662)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getSubAdminArea4662)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setSubAdminArea4663;
public virtual void setSubAdminArea(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setSubAdminArea4663, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setSubAdminArea4663, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setLocality4664;
public virtual void setLocality(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setLocality4664, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setLocality4664, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSubLocality4665;
public virtual global::java.lang.String getSubLocality()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getSubLocality4665)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getSubLocality4665)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setSubLocality4666;
public virtual void setSubLocality(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setSubLocality4666, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setSubLocality4666, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getThoroughfare4667;
public virtual global::java.lang.String getThoroughfare()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getThoroughfare4667)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getThoroughfare4667)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setThoroughfare4668;
public virtual void setThoroughfare(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setThoroughfare4668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setThoroughfare4668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSubThoroughfare4669;
public virtual global::java.lang.String getSubThoroughfare()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getSubThoroughfare4669)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getSubThoroughfare4669)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setSubThoroughfare4670;
public virtual void setSubThoroughfare(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setSubThoroughfare4670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setSubThoroughfare4670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getPremises4671;
public virtual global::java.lang.String getPremises()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getPremises4671)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getPremises4671)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setPremises4672;
public virtual void setPremises(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setPremises4672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setPremises4672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getPostalCode4673;
public virtual global::java.lang.String getPostalCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getPostalCode4673)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getPostalCode4673)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setPostalCode4674;
public virtual void setPostalCode(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setPostalCode4674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setPostalCode4674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCountryCode4675;
public virtual global::java.lang.String getCountryCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getCountryCode4675)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getCountryCode4675)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setCountryCode4676;
public virtual void setCountryCode(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setCountryCode4676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setCountryCode4676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCountryName4677;
public virtual global::java.lang.String getCountryName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getCountryName4677)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getCountryName4677)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setCountryName4678;
public virtual void setCountryName(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setCountryName4678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setCountryName4678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _hasLatitude4679;
public virtual bool hasLatitude()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.location.Address._hasLatitude4679);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._hasLatitude4679);
}
internal static global::MonoJavaBridge.MethodId _getLatitude4680;
public virtual double getLatitude()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallDoubleMethod(this.JvmHandle, global::android.location.Address._getLatitude4680);
else
return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getLatitude4680);
}
internal static global::MonoJavaBridge.MethodId _setLatitude4681;
public virtual void setLatitude(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setLatitude4681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setLatitude4681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _clearLatitude4682;
public virtual void clearLatitude()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._clearLatitude4682);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._clearLatitude4682);
}
internal static global::MonoJavaBridge.MethodId _hasLongitude4683;
public virtual bool hasLongitude()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.location.Address._hasLongitude4683);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._hasLongitude4683);
}
internal static global::MonoJavaBridge.MethodId _getLongitude4684;
public virtual double getLongitude()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallDoubleMethod(this.JvmHandle, global::android.location.Address._getLongitude4684);
else
return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getLongitude4684);
}
internal static global::MonoJavaBridge.MethodId _setLongitude4685;
public virtual void setLongitude(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setLongitude4685, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setLongitude4685, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _clearLongitude4686;
public virtual void clearLongitude()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._clearLongitude4686);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._clearLongitude4686);
}
internal static global::MonoJavaBridge.MethodId _getPhone4687;
public virtual global::java.lang.String getPhone()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getPhone4687)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getPhone4687)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setPhone4688;
public virtual void setPhone(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setPhone4688, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setPhone4688, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getUrl4689;
public virtual global::java.lang.String getUrl()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.Address._getUrl4689)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._getUrl4689)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setUrl4690;
public virtual void setUrl(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setUrl4690, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setUrl4690, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setExtras4691;
public virtual void setExtras(android.os.Bundle arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.Address._setExtras4691, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.Address.staticClass, global::android.location.Address._setExtras4691, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _Address4692;
public Address(java.util.Locale arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.location.Address.staticClass, global::android.location.Address._Address4692, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _CREATOR4693;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.location.Address.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/Address"));
global::android.location.Address._toString4649 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "toString", "()Ljava/lang/String;");
global::android.location.Address._getLocality4650 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getLocality", "()Ljava/lang/String;");
global::android.location.Address._writeToParcel4651 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.location.Address._describeContents4652 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "describeContents", "()I");
global::android.location.Address._getExtras4653 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getExtras", "()Landroid/os/Bundle;");
global::android.location.Address._getLocale4654 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getLocale", "()Ljava/util/Locale;");
global::android.location.Address._getMaxAddressLineIndex4655 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getMaxAddressLineIndex", "()I");
global::android.location.Address._getAddressLine4656 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getAddressLine", "(I)Ljava/lang/String;");
global::android.location.Address._setAddressLine4657 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setAddressLine", "(ILjava/lang/String;)V");
global::android.location.Address._getFeatureName4658 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getFeatureName", "()Ljava/lang/String;");
global::android.location.Address._setFeatureName4659 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setFeatureName", "(Ljava/lang/String;)V");
global::android.location.Address._getAdminArea4660 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getAdminArea", "()Ljava/lang/String;");
global::android.location.Address._setAdminArea4661 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setAdminArea", "(Ljava/lang/String;)V");
global::android.location.Address._getSubAdminArea4662 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getSubAdminArea", "()Ljava/lang/String;");
global::android.location.Address._setSubAdminArea4663 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setSubAdminArea", "(Ljava/lang/String;)V");
global::android.location.Address._setLocality4664 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setLocality", "(Ljava/lang/String;)V");
global::android.location.Address._getSubLocality4665 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getSubLocality", "()Ljava/lang/String;");
global::android.location.Address._setSubLocality4666 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setSubLocality", "(Ljava/lang/String;)V");
global::android.location.Address._getThoroughfare4667 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getThoroughfare", "()Ljava/lang/String;");
global::android.location.Address._setThoroughfare4668 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setThoroughfare", "(Ljava/lang/String;)V");
global::android.location.Address._getSubThoroughfare4669 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getSubThoroughfare", "()Ljava/lang/String;");
global::android.location.Address._setSubThoroughfare4670 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setSubThoroughfare", "(Ljava/lang/String;)V");
global::android.location.Address._getPremises4671 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getPremises", "()Ljava/lang/String;");
global::android.location.Address._setPremises4672 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setPremises", "(Ljava/lang/String;)V");
global::android.location.Address._getPostalCode4673 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getPostalCode", "()Ljava/lang/String;");
global::android.location.Address._setPostalCode4674 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setPostalCode", "(Ljava/lang/String;)V");
global::android.location.Address._getCountryCode4675 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getCountryCode", "()Ljava/lang/String;");
global::android.location.Address._setCountryCode4676 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setCountryCode", "(Ljava/lang/String;)V");
global::android.location.Address._getCountryName4677 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getCountryName", "()Ljava/lang/String;");
global::android.location.Address._setCountryName4678 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setCountryName", "(Ljava/lang/String;)V");
global::android.location.Address._hasLatitude4679 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "hasLatitude", "()Z");
global::android.location.Address._getLatitude4680 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getLatitude", "()D");
global::android.location.Address._setLatitude4681 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setLatitude", "(D)V");
global::android.location.Address._clearLatitude4682 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "clearLatitude", "()V");
global::android.location.Address._hasLongitude4683 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "hasLongitude", "()Z");
global::android.location.Address._getLongitude4684 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getLongitude", "()D");
global::android.location.Address._setLongitude4685 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setLongitude", "(D)V");
global::android.location.Address._clearLongitude4686 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "clearLongitude", "()V");
global::android.location.Address._getPhone4687 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getPhone", "()Ljava/lang/String;");
global::android.location.Address._setPhone4688 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setPhone", "(Ljava/lang/String;)V");
global::android.location.Address._getUrl4689 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "getUrl", "()Ljava/lang/String;");
global::android.location.Address._setUrl4690 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setUrl", "(Ljava/lang/String;)V");
global::android.location.Address._setExtras4691 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "setExtras", "(Landroid/os/Bundle;)V");
global::android.location.Address._Address4692 = @__env.GetMethodIDNoThrow(global::android.location.Address.staticClass, "<init>", "(Ljava/util/Locale;)V");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
namespace System.ServiceModel
{
public class ClientCredentialsSecurityTokenManager : SecurityTokenManager
{
private ClientCredentials _parent;
public ClientCredentialsSecurityTokenManager(ClientCredentials clientCredentials)
{
if (clientCredentials == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientCredentials");
}
_parent = clientCredentials;
}
public ClientCredentials ClientCredentials
{
get { return _parent; }
}
private bool IsDigestAuthenticationScheme(SecurityTokenRequirement requirement)
{
if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty))
{
AuthenticationSchemes authScheme = (AuthenticationSchemes)requirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty];
if (!authScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authScheme", string.Format(SR.HttpRequiresSingleAuthScheme, authScheme));
}
return (authScheme == AuthenticationSchemes.Digest);
}
else
{
return false;
}
}
internal protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
if (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty))
{
// handle all issued token requirements except for spnego, tlsnego and secure conversation
if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation || requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego)
{
return false;
}
else
{
return true;
}
}
return false;
}
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
SecurityTokenProvider result = null;
if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
// this is the uncorrelated duplex case
if (_parent.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials)));
}
result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate);
}
else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement)
{
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider (IsIssuedSecurityTokenRequirement(initiatorRequirement)");
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider X509Certificate - SecurityKeyUsage.Exchange");
}
else
{
if (_parent.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials)));
}
result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate);
}
}
else if (tokenType == SecurityTokenTypes.UserName)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider SecurityTokenTypes.Username");
}
}
if ((result == null) && !tokenRequirement.IsOptionalToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement)));
}
return result;
}
public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
{
// not referenced anywhere in current code, but must implement abstract.
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenSerializer(SecurityTokenVersion version) not supported");
}
private X509SecurityTokenAuthenticator CreateServerX509TokenAuthenticator()
{
return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.Authentication.GetCertificateValidator(), false);
}
private X509SecurityTokenAuthenticator CreateServerSslX509TokenAuthenticator()
{
if (_parent.ServiceCertificate.SslCertificateAuthentication != null)
{
return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator(), false);
}
return CreateServerX509TokenAuthenticator();
}
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
outOfBandTokenResolver = null;
SecurityTokenAuthenticator result = null;
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
if (initiatorRequirement != null)
{
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator");
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.IsOutOfBandToken)
{
// when the client side soap security asks for a token authenticator, its for doing
// identity checks on the out of band server certificate
result = new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
}
else if (initiatorRequirement.PreferSslCertificateAuthenticator)
{
result = CreateServerSslX509TokenAuthenticator();
}
else
{
result = CreateServerX509TokenAuthenticator();
}
}
else if (tokenType == SecurityTokenTypes.Rsa)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Rsa");
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Kerberos");
}
else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation
|| tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
|| tokenType == ServiceModelSecurityTokenTypes.Spnego)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator");
}
}
else if ((tokenRequirement is RecipientServiceModelSecurityTokenRequirement) && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate)
{
// uncorrelated duplex case
result = CreateServerX509TokenAuthenticator();
}
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement)));
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Composition.Hosting;
using System.Composition.Hosting.Core;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OmniSharp.Eventing;
using OmniSharp.FileWatching;
using OmniSharp.Mef;
using OmniSharp.MSBuild.Discovery;
using OmniSharp.Options;
using OmniSharp.Roslyn;
using OmniSharp.Services;
namespace OmniSharp
{
public class CompositionHostBuilder
{
private readonly IServiceProvider _serviceProvider;
private readonly IEnumerable<Assembly> _assemblies;
private readonly IEnumerable<ExportDescriptorProvider> _exportDescriptorProviders;
public CompositionHostBuilder(
IServiceProvider serviceProvider,
IEnumerable<Assembly> assemblies = null,
IEnumerable<ExportDescriptorProvider> exportDescriptorProviders = null)
{
_serviceProvider = serviceProvider;
_assemblies = assemblies ?? Array.Empty<Assembly>();
_exportDescriptorProviders = exportDescriptorProviders ?? Array.Empty<ExportDescriptorProvider>();
}
public CompositionHost Build()
{
var options = _serviceProvider.GetRequiredService<IOptionsMonitor<OmniSharpOptions>>();
var memoryCache = _serviceProvider.GetRequiredService<IMemoryCache>();
var loggerFactory = _serviceProvider.GetRequiredService<ILoggerFactory>();
var assemblyLoader = _serviceProvider.GetRequiredService<IAssemblyLoader>();
var environment = _serviceProvider.GetRequiredService<IOmniSharpEnvironment>();
var eventEmitter = _serviceProvider.GetRequiredService<IEventEmitter>();
var dotNetCliService = _serviceProvider.GetRequiredService<IDotNetCliService>();
var config = new ContainerConfiguration();
var fileSystemWatcher = new ManualFileSystemWatcher();
var metadataHelper = new MetadataHelper(assemblyLoader);
var logger = loggerFactory.CreateLogger<CompositionHostBuilder>();
// We must register an MSBuild instance before composing MEF to ensure that
// our AssemblyResolve event is hooked up first.
var msbuildLocator = _serviceProvider.GetRequiredService<IMSBuildLocator>();
// Don't register the default instance if an instance is already registered!
// This is for tests, where the MSBuild instance may be registered early.
if (msbuildLocator.RegisteredInstance == null)
{
msbuildLocator.RegisterDefaultInstance(logger);
}
config = config
.WithProvider(MefValueProvider.From(_serviceProvider))
.WithProvider(MefValueProvider.From<IFileSystemNotifier>(fileSystemWatcher))
.WithProvider(MefValueProvider.From<IFileSystemWatcher>(fileSystemWatcher))
.WithProvider(MefValueProvider.From(memoryCache))
.WithProvider(MefValueProvider.From(loggerFactory))
.WithProvider(MefValueProvider.From(environment))
.WithProvider(MefValueProvider.From(options.CurrentValue))
.WithProvider(MefValueProvider.From(options.CurrentValue.FormattingOptions))
.WithProvider(MefValueProvider.From(assemblyLoader))
.WithProvider(MefValueProvider.From(dotNetCliService))
.WithProvider(MefValueProvider.From(metadataHelper))
.WithProvider(MefValueProvider.From(msbuildLocator))
.WithProvider(MefValueProvider.From(eventEmitter));
foreach (var exportDescriptorProvider in _exportDescriptorProviders)
{
config = config.WithProvider(exportDescriptorProvider);
}
var parts = _assemblies
.Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
.Distinct()
.SelectMany(a => SafeGetTypes(a))
.ToArray();
config = config.WithParts(parts);
return config.CreateContainer();
}
private static IEnumerable<Type> SafeGetTypes(Assembly a)
{
try
{
return a.DefinedTypes.Select(t => t.AsType()).ToArray();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null).ToArray();
}
}
public static IServiceProvider CreateDefaultServiceProvider(
IOmniSharpEnvironment environment,
IConfigurationRoot configuration,
IEventEmitter eventEmitter,
IServiceCollection services = null,
Action<ILoggingBuilder> configureLogging = null)
{
services = services ?? new ServiceCollection();
services.AddSingleton(environment);
services.AddSingleton(eventEmitter);
// Caching
services.AddSingleton<IMemoryCache, MemoryCache>();
services.AddSingleton<IAssemblyLoader, AssemblyLoader>();
services.AddOptions();
services.AddSingleton<IDotNetCliService, DotNetCliService>();
// MSBuild
services.AddSingleton<IMSBuildLocator>(sp =>
MSBuildLocator.CreateDefault(
loggerFactory: sp.GetService<ILoggerFactory>(),
assemblyLoader: sp.GetService<IAssemblyLoader>()));
// Setup the options from configuration
services.Configure<OmniSharpOptions>(configuration);
services.AddSingleton(configuration);
services.AddLogging(builder =>
{
var workspaceInformationServiceName = typeof(WorkspaceInformationService).FullName;
var projectEventForwarder = typeof(ProjectEventForwarder).FullName;
builder.AddFilter(
(category, logLevel) =>
environment.LogLevel <= logLevel &&
category.StartsWith("OmniSharp", StringComparison.OrdinalIgnoreCase) &&
!category.Equals(workspaceInformationServiceName, StringComparison.OrdinalIgnoreCase) &&
!category.Equals(projectEventForwarder, StringComparison.OrdinalIgnoreCase));
configureLogging?.Invoke(builder);
});
return services.BuildServiceProvider();
}
public CompositionHostBuilder WithOmniSharpAssemblies()
{
var assemblies = DiscoverOmniSharpAssemblies();
return new CompositionHostBuilder(
_serviceProvider,
_assemblies.Concat(assemblies).Distinct()
);
}
public CompositionHostBuilder WithAssemblies(params Assembly[] assemblies)
{
return new CompositionHostBuilder(
_serviceProvider,
_assemblies.Concat(assemblies).Distinct()
);
}
private List<Assembly> DiscoverOmniSharpAssemblies()
{
var assemblyLoader = _serviceProvider.GetRequiredService<IAssemblyLoader>();
var logger = _serviceProvider
.GetRequiredService<ILoggerFactory>()
.CreateLogger<CompositionHostBuilder>();
// Iterate through all runtime libraries in the dependency context and
// load them if they depend on OmniSharp.
var assemblies = new List<Assembly>();
var dependencyContext = DependencyContext.Default;
foreach (var runtimeLibrary in dependencyContext.RuntimeLibraries)
{
if (DependsOnOmniSharp(runtimeLibrary))
{
foreach (var name in runtimeLibrary.GetDefaultAssemblyNames(dependencyContext))
{
var assembly = assemblyLoader.Load(name);
if (assembly != null)
{
assemblies.Add(assembly);
logger.LogDebug($"Loaded {assembly.FullName}");
}
}
}
}
return assemblies;
}
private static bool DependsOnOmniSharp(RuntimeLibrary runtimeLibrary)
{
foreach (var dependency in runtimeLibrary.Dependencies)
{
if (dependency.Name == "OmniSharp.Abstractions" ||
dependency.Name == "OmniSharp.Roslyn")
{
return true;
}
}
return false;
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeImportTests : AbstractFileCodeElementTests
{
public FileCodeImportTests()
: base(@"using System;
using Foo = System.Data;")
{
}
private async Task<CodeImport> GetCodeImportAsync(object path)
{
return (CodeImport)await GetCodeElementAsync(path);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Name()
{
CodeImport import = await GetCodeImportAsync(1);
AssertEx.Throws<COMException>(() => { var value = import.Name; });
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task FullName()
{
CodeImport import = await GetCodeImportAsync(1);
AssertEx.Throws<COMException>(() => { var value = import.FullName; });
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Kind()
{
CodeImport import = await GetCodeImportAsync(1);
Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Namespace()
{
CodeImport import = await GetCodeImportAsync(1);
Assert.Equal("System", import.Namespace);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Alias()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Equal("Foo", import.Alias);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Attributes()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_AttributesWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Body()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_BodyWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Header()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_HeaderWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Name()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Navigate()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, startPoint.Line);
Assert.Equal(13, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Whole()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_WholeWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Attributes()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_AttributesWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Body()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_BodyWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Header()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_HeaderWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Name()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Navigate()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, endPoint.Line);
Assert.Equal(24, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Whole()
{
CodeImport import = await GetCodeImportAsync(2);
AssertEx.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_WholeWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task StartPoint()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint startPoint = import.StartPoint;
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task EndPoint()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint endPoint = import.EndPoint;
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
}
}
| |
/***************************************************************************
* PodcastFeedPropertiesDialog.cs
*
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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 Mono.Unix;
using Gtk;
using Pango;
using Migo.Syndication;
using Banshee.Base;
using Banshee.Podcasting.Data;
namespace Banshee.Podcasting.Gui
{
internal class PodcastFeedPropertiesDialog : Dialog
{
private Feed feed;
private SyncPreferenceComboBox new_episode_option_combo;
private Entry name_entry;
public PodcastFeedPropertiesDialog (Feed feed)
{
this.feed = feed;
Title = feed.Title;
//IconThemeUtils.SetWindowIcon (this);
BuildWindow ();
}
private void BuildWindow()
{
BorderWidth = 6;
VBox.Spacing = 12;
HasSeparator = false;
HBox box = new HBox();
box.BorderWidth = 6;
box.Spacing = 12;
Button save_button = new Button("gtk-save");
save_button.CanDefault = true;
save_button.Show();
// For later additions to the dialog. (I.E. Feed art)
HBox content_box = new HBox();
content_box.Spacing = 12;
Table table = new Table (2, 4, false);
table.RowSpacing = 6;
table.ColumnSpacing = 12;
Label description_label = new Label (Catalog.GetString ("Description:"));
description_label.SetAlignment (0f, 0f);
description_label.Justify = Justification.Left;
Label last_updated_label = new Label (Catalog.GetString ("Last updated:"));
last_updated_label.SetAlignment (0f, 0f);
last_updated_label.Justify = Justification.Left;
Label name_label = new Label (Catalog.GetString ("Podcast Name:"));
name_label.SetAlignment (0f, 0f);
name_label.Justify = Justification.Left;
name_entry = new Entry ();
name_entry.Text = feed.Title;
name_entry.Changed += delegate {
save_button.Sensitive = !String.IsNullOrEmpty (name_entry.Text);
};
Label feed_url_label = new Label (Catalog.GetString ("URL:"));
feed_url_label.SetAlignment (0f, 0f);
feed_url_label.Justify = Justification.Left;
Label new_episode_option_label = new Label (Catalog.GetString ("When feed is updated:"));
new_episode_option_label.SetAlignment (0f, 0.5f);
new_episode_option_label.Justify = Justification.Left;
Label last_updated_text = new Label (feed.LastDownloadTime.ToString ("f"));
last_updated_text.Justify = Justification.Left;
last_updated_text.SetAlignment (0f, 0f);
Label feed_url_text = new Label (feed.Url.ToString ());
feed_url_text.Wrap = false;
feed_url_text.Selectable = true;
feed_url_text.SetAlignment (0f, 0f);
feed_url_text.Justify = Justification.Left;
feed_url_text.Ellipsize = Pango.EllipsizeMode.End;
string description_string = String.IsNullOrEmpty (feed.Description) ?
Catalog.GetString ("No description available") :
feed.Description;
Label descrition_text = new Label (description_string);
descrition_text.Justify = Justification.Left;
descrition_text.SetAlignment (0f, 0f);
descrition_text.Wrap = true;
descrition_text.Selectable = true;
Viewport description_viewport = new Viewport();
description_viewport.SetSizeRequest(-1, 150);
description_viewport.ShadowType = ShadowType.None;
ScrolledWindow description_scroller = new ScrolledWindow ();
description_scroller.HscrollbarPolicy = PolicyType.Never;
description_scroller.VscrollbarPolicy = PolicyType.Automatic;
description_viewport.Add (descrition_text);
description_scroller.Add (description_viewport);
new_episode_option_combo = new SyncPreferenceComboBox (feed.AutoDownload);
// First column
uint i = 0;
table.Attach (
name_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
feed_url_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
last_updated_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
new_episode_option_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
description_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
// Second column
i = 0;
table.Attach (
name_entry, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
feed_url_text, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
last_updated_text, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
new_episode_option_combo, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (description_scroller, 1, 2, i, ++i,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0
);
content_box.PackStart (table, true, true, 0);
box.PackStart (content_box, true, true, 0);
Button cancel_button = new Button("gtk-cancel");
cancel_button.CanDefault = true;
cancel_button.Show();
AddActionWidget (cancel_button, ResponseType.Cancel);
AddActionWidget (save_button, ResponseType.Ok);
DefaultResponse = Gtk.ResponseType.Cancel;
ActionArea.Layout = Gtk.ButtonBoxStyle.End;
box.ShowAll ();
VBox.Add (box);
Response += OnResponse;
}
private void OnResponse (object sender, ResponseArgs args)
{
Destroy ();
if (args.ResponseId == Gtk.ResponseType.Ok) {
FeedAutoDownload new_sync_pref = new_episode_option_combo.ActiveSyncPreference;
if (feed.AutoDownload != new_sync_pref || feed.Title != name_entry.Text) {
feed.AutoDownload = new_sync_pref;
feed.Title = name_entry.Text;
feed.Save ();
}
}
(sender as Dialog).Response -= OnResponse;
(sender as Dialog).Destroy();
}
}
}
| |
// 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: Pointer Type to a EEType in the runtime.
**
**
===========================================================*/
using System.Runtime;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using EEType = Internal.Runtime.EEType;
using EETypeRef = Internal.Runtime.EETypeRef;
namespace System
{
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct EETypePtr : IEquatable<EETypePtr>
{
private EEType* _value;
public EETypePtr(IntPtr value)
{
_value = (EEType*)value;
}
internal EETypePtr(EEType* value)
{
_value = value;
}
internal EEType* ToPointer()
{
return _value;
}
public override bool Equals(object obj)
{
if (obj is EETypePtr)
{
return this == (EETypePtr)obj;
}
return false;
}
public bool Equals(EETypePtr p)
{
return this == p;
}
public static bool operator ==(EETypePtr value1, EETypePtr value2)
{
if (value1.IsNull)
return value2.IsNull;
else if (value2.IsNull)
return false;
else
return RuntimeImports.AreTypesEquivalent(value1, value2);
}
public static bool operator !=(EETypePtr value1, EETypePtr value2)
{
return !(value1 == value2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return (int)_value->HashCode;
}
//
// Faster version of Equals for use on EETypes that are known not to be null and where the "match" case is the hot path.
//
public bool FastEquals(EETypePtr other)
{
Debug.Assert(!this.IsNull);
Debug.Assert(!other.IsNull);
// Fast check for raw equality before making call to helper.
if (this.RawValue == other.RawValue)
return true;
return RuntimeImports.AreTypesEquivalent(this, other);
}
//
// An even faster version of FastEquals that only checks if two EEType pointers are identical.
// Note: this method might return false for cases where FastEquals would return true.
// Only use if you know what you're doing.
//
internal bool FastEqualsUnreliable(EETypePtr other)
{
Debug.Assert(!this.IsNull);
Debug.Assert(!other.IsNull);
return this.RawValue == other.RawValue;
}
// Caution: You cannot safely compare RawValue's as RH does NOT unify EETypes. Use the == or Equals() methods exposed by EETypePtr itself.
internal IntPtr RawValue
{
get
{
return (IntPtr)_value;
}
}
internal bool IsNull
{
get
{
return _value == null;
}
}
internal bool IsArray
{
get
{
return _value->IsArray;
}
}
internal bool IsSzArray
{
get
{
return _value->IsSzArray;
}
}
internal bool IsPointer
{
get
{
return _value->IsPointerType;
}
}
internal bool IsByRef
{
get
{
return _value->IsByRefType;
}
}
internal bool IsValueType
{
get
{
return _value->IsValueType;
}
}
internal bool IsString
{
get
{
return _value->IsString;
}
}
/// <summary>
/// Warning! UNLIKE the similarly named Reflection api, this method also returns "true" for Enums.
/// </summary>
internal bool IsPrimitive
{
get
{
RuntimeImports.RhCorElementType et = CorElementType;
return ((et >= RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN) && (et <= RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)) ||
(et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_I) ||
(et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_U);
}
}
/// <summary>
/// WARNING: Never call unless the EEType came from an instanced object. Nested enums can be open generics (typeof(Outer<>).NestedEnum)
/// and this helper has undefined behavior when passed such as a enum.
/// </summary>
internal bool IsEnum
{
get
{
// Q: When is an enum type a constructed generic type?
// A: When it's nested inside a generic type.
if (!(IsDefType))
return false;
EETypePtr baseType = this.BaseType;
return baseType == EETypePtr.EETypePtrOf<Enum>();
}
}
/// <summary>
/// Gets a value indicating whether this is a generic type definition (an uninstantiated generic type).
/// </summary>
internal bool IsGenericTypeDefinition
{
get
{
return _value->IsGenericTypeDefinition;
}
}
/// <summary>
/// Gets a value indicating whether this is an instantiated generic type.
/// </summary>
internal bool IsGeneric
{
get
{
return _value->IsGeneric;
}
}
internal GenericArgumentCollection Instantiation
{
get
{
return new GenericArgumentCollection(_value->GenericArity, _value->GenericArguments);
}
}
internal EETypePtr GenericDefinition
{
get
{
return new EETypePtr(_value->GenericDefinition);
}
}
/// <summary>
/// Gets a value indicating whether this is a class, a struct, an enum, or an interface.
/// </summary>
internal bool IsDefType
{
get
{
return !_value->IsParameterizedType;
}
}
internal bool IsDynamicType
{
get
{
return _value->IsDynamicType;
}
}
internal bool IsInterface
{
get
{
return _value->IsInterface;
}
}
internal bool IsAbstract
{
get
{
return _value->IsAbstract;
}
}
internal bool IsByRefLike
{
get
{
return _value->IsByRefLike;
}
}
internal bool IsNullable
{
get
{
return _value->IsNullable;
}
}
internal bool HasCctor
{
get
{
return _value->HasCctor;
}
}
internal EETypePtr NullableType
{
get
{
return new EETypePtr(_value->NullableType);
}
}
internal EETypePtr ArrayElementType
{
get
{
return new EETypePtr(_value->RelatedParameterType);
}
}
internal int ArrayRank
{
get
{
return _value->ArrayRank;
}
}
internal InterfaceCollection Interfaces
{
get
{
return new InterfaceCollection(_value);
}
}
internal EETypePtr BaseType
{
get
{
if (IsArray)
return EETypePtr.EETypePtrOf<Array>();
if (IsPointer || IsByRef)
return new EETypePtr(default(IntPtr));
EETypePtr baseEEType = new EETypePtr(_value->NonArrayBaseType);
return baseEEType;
}
}
internal ushort ComponentSize
{
get
{
return _value->ComponentSize;
}
}
internal uint BaseSize
{
get
{
return _value->BaseSize;
}
}
// Has internal gc pointers.
internal bool HasPointers
{
get
{
return _value->HasGCPointers;
}
}
internal uint ValueTypeSize
{
get
{
return _value->ValueTypeSize;
}
}
internal RuntimeImports.RhCorElementType CorElementType
{
get
{
Debug.Assert((int)Internal.Runtime.CorElementType.ELEMENT_TYPE_I1 == (int)RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1);
Debug.Assert((int)Internal.Runtime.CorElementType.ELEMENT_TYPE_R8 == (int)RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8);
return (RuntimeImports.RhCorElementType)_value->CorElementType;
}
}
internal RuntimeImports.RhCorElementTypeInfo CorElementTypeInfo
{
get
{
RuntimeImports.RhCorElementType corElementType = this.CorElementType;
return RuntimeImports.GetRhCorElementTypeInfo(corElementType);
}
}
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static EETypePtr EETypePtrOf<T>()
{
// Compilers are required to provide a low level implementation of this method.
// This can be achieved by optimizing away the reflection part of this implementation
// by optimizing typeof(!!0).TypeHandle into "ldtoken !!0", or by
// completely replacing the body of this method.
return typeof(T).TypeHandle.ToEETypePtr();
}
public struct InterfaceCollection
{
private EEType* _value;
internal InterfaceCollection(EEType* value)
{
_value = value;
}
public int Count
{
get
{
return _value->NumInterfaces;
}
}
public EETypePtr this[int index]
{
get
{
Debug.Assert((uint)index < _value->NumInterfaces);
return new EETypePtr(_value->InterfaceMap[index].InterfaceType);
}
}
}
public struct GenericArgumentCollection
{
private EETypeRef* _arguments;
private uint _argumentCount;
internal GenericArgumentCollection(uint argumentCount, EETypeRef* arguments)
{
_argumentCount = argumentCount;
_arguments = arguments;
}
public int Length
{
get
{
return (int)_argumentCount;
}
}
public EETypePtr this[int index]
{
get
{
Debug.Assert((uint)index < _argumentCount);
return new EETypePtr(_arguments[index].Value);
}
}
}
}
}
| |
using System;
using MonoBrick.EV3;
namespace MonoBrick.EV3
{
/// <summary>
/// Class for creating a EV3 brick
/// </summary>
public class Brick<TSensor1,TSensor2,TSensor3,TSensor4>
where TSensor1 : Sensor, new()
where TSensor2 : Sensor, new()
where TSensor3 : Sensor, new()
where TSensor4 : Sensor, new()
{
#region wrapper for connection, filesystem, sensor and motor
private Connection<Command,Reply> connection = null;
private TSensor1 sensor1;
private TSensor2 sensor2;
private TSensor3 sensor3;
private TSensor4 sensor4;
private FilSystem fileSystem = new FilSystem();
private Motor motorA = new Motor();
private Motor motorB = new Motor();
private Motor motorC = new Motor();
private Motor motorD = new Motor();
private Memory memory = new Memory();
private MotorSync motorSync = new MotorSync();
private Vehicle vehicle = new Vehicle(MotorPort.OutA,MotorPort.OutC);
private Mailbox mailbox = new Mailbox();
private void Init(){
Sensor1 = new TSensor1();
Sensor2 = new TSensor2();
Sensor3 = new TSensor3();
Sensor4 = new TSensor4();
fileSystem.Connection = connection;
motorA.Connection = connection;
motorA.BitField = OutputBitfield.OutA;
motorB.Connection = connection;
motorB.BitField = OutputBitfield.OutB;
motorC.Connection = connection;
motorC.BitField = OutputBitfield.OutC;
motorD.Connection = connection;
motorD.BitField = OutputBitfield.OutD;
motorSync.Connection = connection;
motorSync.BitField = OutputBitfield.OutA | OutputBitfield.OutD;
memory.Connection = connection;
mailbox.Connection = connection;
vehicle.Connection = connection;
}
/// <summary>
/// Manipulate memory on the EV3
/// </summary>
/// <value>The memory.</value>
/*public Memory Memory {
get{return memory;}
}
*/
/// <summary>
/// Message system used to write and read data to/from the brick
/// </summary>
/// <value>
/// The message system
/// </value>
public Mailbox Mailbox{
get{ return mailbox;}
}
/// <summary>
/// Motor A
/// </summary>
/// <value>
/// The motor connected to port A
/// </value>
public Motor MotorA{
get{ return motorA;}
}
/// <summary>
/// Motor B
/// </summary>
/// <value>
/// The motor connected to port B
/// </value>
public Motor MotorB{
get{ return motorB;}
}
/// <summary>
/// Motor C
/// </summary>
/// <value>
/// The motor connected to port C
/// </value>
public Motor MotorC{
get{ return motorC;}
}
/// <summary>
/// Motor D
/// </summary>
/// <value>
/// The motor connected to port D
/// </value>
public Motor MotorD{
get{ return motorD;}
}
/// <summary>
/// Synchronise two motors
/// </summary>
/// <value>The motor sync.</value>
public MotorSync MotorSync{
get{ return motorSync;}
}
/// <summary>
/// Use the brick as a vehicle
/// </summary>
/// <value>
/// The vehicle
/// </value>
public Vehicle Vehicle{
get{ return vehicle;}
}
/// <summary>
/// Gets or sets the sensor connected to port 1
/// </summary>
/// <value>
/// The sensor connected to port 1
/// </value>
public TSensor1 Sensor1{
get{ return sensor1;}
set{
sensor1 = value;
sensor1.Port = SensorPort.In1;
sensor1.Connection = connection;
}
}
/// <summary>
/// Gets or sets the sensor connected to port 2
/// </summary>
/// <value>
/// The sensor connected to port 2
/// </value>
public TSensor2 Sensor2{
get{ return sensor2;}
set{
sensor2 = value;
sensor2.Port = SensorPort.In2;
sensor2.Connection = connection;
}
}
/// <summary>
/// Gets or sets the sensor connected to port 3
/// </summary>
/// <value>
/// The sensor connected to port 3
/// </value>
public TSensor3 Sensor3{
get{ return sensor3;}
set{
sensor3 = value;
sensor3.Port = SensorPort.In3;
sensor3.Connection = connection;
}
}
/// <summary>
/// Gets or sets the sensor connected to port 4
/// </summary>
/// <value>
/// The sensor connected to port 4
/// </value>
public TSensor4 Sensor4{
get{ return sensor4;}
set{
sensor4 = value;
sensor4.Port = SensorPort.In4;
sensor4.Connection = connection;
}
}
/// <summary>
/// The file system
/// </summary>
/// <value>
/// The file system
/// </value>
public FilSystem FileSystem{
get{return fileSystem;}
}
/// <summary>
/// Gets the connection that the brick uses
/// </summary>
/// <value>
/// The connection
/// </value>
public Connection<Command,Reply> Connection{
get{return connection;}
}
/// <summary>
/// Initializes a new instance of the Brick class.
/// </summary>
/// <param name='connection'>
/// Connection to use
/// </param>
public Brick(Connection<Command,Reply> connection){
this.connection = connection;
Init();
}
/// <summary>
/// Initializes a new instance of the Brick class with bluetooth, usb or WiFi connection
/// </summary>
/// <param name='connection'>
/// Can either be a serial port name for bluetooth connection or "usb" for usb connection and finally "wiFi" for WiFi connection
/// </param>
public Brick(string connection)
{
switch(connection.ToLower()){
case "usb":
this.connection = new USB<Command,Reply>();
break;
case "wifi":
this.connection = new WiFiConnection<Command,Reply>(10000); //10 seconds timeout when connecting
break;
case "loopback":
throw new NotImplementedException("Loopback connection has not been implemented for EV3");
default:
this.connection = new Bluetooth<Command,Reply>(connection);
break;
}
Init();
}
/// <summary>
/// Initializes a new instance of the Brick class with a tunnel connection
/// </summary>
/// <param name='ipAddress'>
/// The IP address to use
/// </param>
/// <param name='port'>
/// The port number to use
/// </param>
public Brick(string ipAddress, ushort port){
connection = new TunnelConnection<Command, Reply>(ipAddress, port);
Init();
}
#endregion
#region brick functions
/// <summary>
/// Start a program on the brick
/// </summary>
/// <param name="file">File to start</param>
public void StartProgram (BrickFile file)
{
StartProgram(file,false);
}
/// <summary>
/// Start a program on the brick
/// </summary>
/// <param name="file">File to stat.</param>
/// <param name="reply">If set to <c>true</c> reply from brick will be send</param>
public void StartProgram (BrickFile file, bool reply)
{
StartProgram(file.FullName,reply);
}
/// <summary>
/// Start a program on the brick
/// </summary>
/// <param name='name'>
/// The name of the program to start
/// </param>
public void StartProgram(string name){
StartProgram(name, false);
}
/// <summary>
/// Starts a program on the brick
/// </summary>
/// <param name='name'>
/// The of the program to start
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void StartProgram(string name, bool reply){
var command = new Command(0,8, 400,reply);
command.Append(ByteCodes.File);
command.Append(FileSubCodes.LoadImage);
command.Append((byte)ProgramSlots.User,ConstantParameterType.Value);
command.Append(name, ConstantParameterType.Value);
command.Append(0, VariableScope.Local);
command.Append(4, VariableScope.Local);
command.Append(ByteCodes.ProgramStart);
command.Append((byte)ProgramSlots.User);
command.Append(0, VariableScope.Local);
command.Append(4, VariableScope.Local);
command.Append(0,ParameterFormat.Short);
connection.Send(command);
System.Threading.Thread.Sleep(5000);
if(reply){
var brickReply = connection.Receive();
Error.CheckForError(brickReply,400);
}
}
/// <summary>
/// Stops all running programs
/// </summary>
public void StopProgram(){
StopProgram(false);
}
/// <summary>
/// Stops all running programs
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> reply the brick will send a reply
/// </param>
public void StopProgram(bool reply){
var command = new Command(0,0, 401,reply);
command.Append(ByteCodes.ProgramStop);
command.Append((byte)ProgramSlots.User, ConstantParameterType.Value);
connection.Send(command);
if(reply){
var brickReply = connection.Receive();
Error.CheckForError(brickReply,401);
}
}
/// <summary>
/// Get the name of the program that is curently running
/// </summary>
/// <returns>
/// The running program.
/// </returns>
public string GetRunningProgram(){
return "";
}
/// <summary>
/// Play a tone.
/// </summary>
/// <param name="volume">Volume.</param>
/// <param name="frequency">Frequency of the tone</param>
/// <param name="durationMs">Duration in ms.</param>
public void PlayTone(byte volume,UInt16 frequency, UInt16 durationMs){
PlayTone(volume, frequency,durationMs,false);
}
/// <summary>
/// Play a tone.
/// </summary>
/// <param name="volume">Volume.</param>
/// <param name="frequency">Frequency of the tone</param>
/// <param name="durationMs">Duration in ms.</param>
/// <param name="reply">If set to <c>true</c> reply from brick will be send</param>
public void PlayTone(byte volume,UInt16 frequency, UInt16 durationMs, bool reply){
var command = new Command(0,0,123,reply);
command.Append(ByteCodes.Sound);
command.Append(SoundSubCodes.Tone);
command.Append(volume, ParameterFormat.Short);
command.Append(frequency, ConstantParameterType.Value);
command.Append(durationMs, ConstantParameterType.Value);
connection.Send(command);
if(reply){
var brickReply = connection.Receive();
Error.CheckForError(brickReply,123);
}
}
/// <summary>
/// Make the brick say beep
/// </summary>
/// <param name="volume">Volume of the beep</param>
/// <param name="durationMs">Duration in ms.</param>
public void Beep(byte volume, UInt16 durationMs){
Beep(volume,durationMs,false);
}
/// <summary>
/// Make the brick say beep
/// </summary>
/// <param name="volume">Volume of the beep</param>
/// <param name="durationMs">Duration in ms.</param>
/// <param name="reply">If set to <c>true</c> reply from the brick will be send</param>
public void Beep(byte volume, UInt16 durationMs, bool reply){
PlayTone(volume,1000, durationMs,reply);
}
/// <summary>
/// Play a sound file.
/// </summary>
/// <param name="name">Name the name of the file to play</param>
/// <param name="volume">Volume.</param>
/// <param name="repeat">If set to <c>true</c> the file will play in a loop</param>
public void PlaySoundFile(string name, byte volume, bool repeat){
PlaySoundFile(name, volume, repeat, false);
}
/// <summary>
/// Play a sound file.
/// </summary>
/// <param name="name">Name the name of the file to play</param>
/// <param name="volume">Volume.</param>
/// <param name="repeat">If set to <c>true</c> the file will play in a loop</param>
/// <param name="reply">If set to <c>true</c> a reply from the brick will be send</param>
public void PlaySoundFile(string name, byte volume, bool repeat ,bool reply){
Command command = null;
if(repeat){
command = new Command(0,0,200,reply);
command.Append(ByteCodes.Sound);
command.Append(SoundSubCodes.Repeat);
command.Append(volume, ConstantParameterType.Value);
command.Append(name, ConstantParameterType.Value);
command.Append(ByteCodes.SoundReady);//should this be here?
}
else{
command = new Command(0,0,200,reply);
command.Append(ByteCodes.Sound);
command.Append(SoundSubCodes.Play);
command.Append(volume, ConstantParameterType.Value);
command.Append(name, ConstantParameterType.Value);
command.Append(ByteCodes.SoundReady);//should this be here?
}
connection.Send(command);
if(reply){
var brickReply = connection.Receive();
Error.CheckForError(brickReply,200);
}
}
/// <summary>
/// Stops all sound playback.
/// </summary>
/// <param name="reply">If set to <c>true</c> reply from brick will be send</param>
public void StopSoundPlayback(bool reply = false){
var command = new Command(0,0,123,reply);
command.Append(ByteCodes.Sound);
command.Append(SoundSubCodes.Break);
connection.Send(command);
if(reply){
var brickReply = connection.Receive();
Error.CheckForError(brickReply,123);
}
}
/// <summary>
/// Gets the sensor types of all four sensors
/// </summary>
/// <returns>The sensor types.</returns>
public SensorType[] GetSensorTypes ()
{
var command = new Command(5,0,200,true);
command.Append(ByteCodes.InputDeviceList);
command.Append((byte)4,ParameterFormat.Short);
command.Append((byte)0, VariableScope.Global);
command.Append((byte)4, VariableScope.Global);
var reply = Connection.SendAndReceive(command);
SensorType[] type = new SensorType[4];
for(int i = 0; i < 4; i++){
if(Enum.IsDefined(typeof(SensorType), (int) reply[i + 3])){
type[i] = (SensorType)reply[i + 3];
}
else{
type[i] = SensorType.Unknown;
}
}
return type;
}
#endregion
}
}
| |
using System;
using FastCgiNet;
using Fos.Owin;
using Fos.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using FastCgiNet.Streams;
using System.Net.Sockets;
namespace Fos.Listener
{
internal delegate void SocketClosed();
internal class FosRequest : FastCgiNet.Requests.ApplicationSocketRequest
{
private Fos.Streams.FosStdoutStream stdout;
public override FastCgiStream Stdout
{
get
{
return stdout;
}
}
/// <summary>
/// Some applications need to control when flushing the response to the visitor is done; if that is the case, set this to <c>false</c>.
/// If the application does not require that, then Fos will flush the response itself periodically to avoid keeping too
/// many buffers around and to avoid an idle connection.
/// </summary>
public bool FlushPeriodically;
/// <summary>
/// The Owin Context dictionary. This is never null.
/// </summary>
public OwinContext OwinContext { get; private set; }
/// <summary>
/// Sets the application's entry point. This must be set before receiving Stdin records.
/// </summary>
public Func<IDictionary<string, object>, Task> ApplicationPipelineEntry;
private IServerLogger Logger;
private CancellationTokenSource CancellationSource;
/// <summary>
/// This method should (and is) automatically called whenever any part of the body is to be sent. It sends the response's status code
/// and the response headers.
/// </summary>
private void SendHeaders()
{
var headers = (IDictionary<string, string[]>)OwinContext["owin.ResponseHeaders"];
using (var headerStream = new Fos.Streams.NonEndingStdoutSocketStream(Socket))
{
headerStream.RequestId = RequestId;
using (var writer = new Fos.Streams.HeaderWriter(headerStream))
{
// Response status code with special CGI header "Status"
writer.Write("Status", OwinContext.ResponseStatusCodeAndReason);
foreach (var header in headers)
{
writer.Write(header.Key, header.Value);
}
// That last newline
writer.WriteLine();
}
}
}
private void SendErrorPage(Exception applicationEx)
{
var errorPage = new Fos.CustomPages.ApplicationErrorPage(applicationEx);
OwinContext.SetResponseHeader("Content-Type", "text/html");
OwinContext.ResponseStatusCodeAndReason = "500 Internal Server Error";
using (var sw = new StreamWriter(Stdout))
{
sw.Write(errorPage.Contents);
}
Stdout.Flush();
}
private void SendEmptyResponsePage()
{
var emptyResponsePage = new Fos.CustomPages.EmptyResponsePage();
OwinContext.SetResponseHeader("Content-Type", "text/html");
OwinContext.ResponseStatusCodeAndReason = "500 Internal Server Error";
using (var sw = new StreamWriter(Stdout))
{
sw.Write(emptyResponsePage.Contents);
}
Stdout.Flush();
}
protected override void AddReceivedRecord(RecordBase rec)
{
base.AddReceivedRecord(rec);
switch (rec.RecordType)
{
case RecordType.FCGIParams:
if (Params.IsComplete)
OwinContext.AddParams(Params);
break;
case RecordType.FCGIStdin:
// Only respond if the last empty stdin was received
if (!Stdin.IsComplete)
break;
var onApplicationDone = ProcessRequest();
onApplicationDone.ContinueWith(t => {
// This task _CANNOT_ fail
if (ApplicationMustCloseConnection)
{
this.Dispose();
}
});
break;
}
}
/// <summary>
/// Receives an Stdin record, passes it to the Owin Pipeline and returns a Task that when completed, indicates this FastCGI Request has been answered to and is ended.
/// The task's result indicates if the connection needs to be closed from the application's side.
/// </summary>
/// <remarks>This method can return null if there are more Stdin records yet to be received. In fact, the request is only passed to the Owin pipeline after all stdin records have been received.</remarks>
public Task ProcessRequest()
{
// Sign up for the first write, because we need to send the headers when that happens (Owin spec)
// Also sign up to flush buffers for the application if we can
stdout.OnFirstWrite += SendHeaders;
if (FlushPeriodically)
stdout.OnStreamFill += () => stdout.Flush();
// Now pass it to the Owin pipeline
Task applicationResponse;
try
{
applicationResponse = ApplicationPipelineEntry(OwinContext);
}
catch (Exception e)
{
if (Logger != null)
Logger.LogApplicationError(e, new RequestInfo(this));
// Show the exception to the visitor
SendErrorPage(e);
// End the FastCgi connection with an error code
SendEndRequest(-1, ProtocolStatus.RequestComplete);
// Return a task that indicates completion..
return Task.Factory.StartNew(() => {});
}
// Now set the actions to do when the response is ready
return applicationResponse.ContinueWith(applicationTask =>
{
if (applicationTask.IsFaulted)
{
Exception e = applicationTask.Exception;
if (Logger != null)
Logger.LogApplicationError(e, new RequestInfo(this));
// Show the exception to the visitor
SendErrorPage(e);
SendEndRequest(-1, ProtocolStatus.RequestComplete);
}
else if (!OwinContext.SomeResponseExists)
{
// If we are here, then no response was set by the application, i.e. not a single header or response body
SendEmptyResponsePage();
SendEndRequest(-1, ProtocolStatus.RequestComplete);
}
else
{
// Signal successful return status
SendEndRequest(0, ProtocolStatus.RequestComplete);
}
});
}
protected override void Send(RecordBase rec)
{
try
{
base.Send(rec);
}
catch (ObjectDisposedException)
{
}
catch (SocketException e)
{
if (!SocketHelper.IsConnectionAbortedByTheOtherSide(e))
throw;
CancellationSource.Cancel();
}
}
/// <summary>
/// Warns when the socket for this request was closed by our side because <see cref="CloseSocket()"/> was called.
/// </summary>
public event SocketClosed OnSocketClose = delegate {};
protected override void CloseSocket()
{
try
{
if (!CancellationSource.IsCancellationRequested)
CancellationSource.Cancel();
base.CloseSocket();
OnSocketClose();
}
catch (ObjectDisposedException)
{
}
catch (SocketException e)
{
if (!SocketHelper.IsConnectionAbortedByTheOtherSide(e))
throw;
}
}
public FosRequest(Socket sock, Fos.Logging.IServerLogger logger)
: base(sock)
{
Logger = logger;
CancellationSource = new CancellationTokenSource();
OwinContext = new OwinContext("1.0", CancellationSource.Token);
// Streams
stdout = new Fos.Streams.FosStdoutStream(sock);
OwinContext.ResponseBody = Stdout;
OwinContext.RequestBody = Stdin;
}
}
}
| |
namespace QuickGraph.Serialization.GraphML {
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
/// <summary />
/// <remarks />
[XmlType(IncludeInSchema=true, TypeName="edge.type")]
[XmlRoot(ElementName="edge", IsNullable=false, DataType="")]
public class EdgeType {
/// <summary />
/// <remarks />
private bool _directed;
/// <summary />
/// <remarks />
private DataCollection _data = new DataCollection();
/// <summary />
/// <remarks />
private string _source;
/// <summary />
/// <remarks />
private string id;
/// <summary />
/// <remarks />
private string _sourceport;
/// <summary />
/// <remarks />
private string _targetport;
/// <summary />
/// <remarks />
private bool _directedspecified;
/// <summary />
/// <remarks />
private string _target;
/// <summary />
/// <remarks />
private GraphType _graph;
/// <summary />
/// <remarks />
private string _desc;
/// <summary />
/// <remarks />
[XmlElement(ElementName="desc")]
public virtual string Desc {
get {
return this._desc;
}
set {
this._desc = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="data", Type=typeof(DataType))]
public virtual DataCollection Data {
get {
return this._data;
}
set {
this._data = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="graph")]
public virtual GraphType Graph {
get {
return this._graph;
}
set {
this._graph = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="id")]
public virtual string ID {
get {
return this.id;
}
set {
this.id = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="directed")]
public virtual bool Directed {
get {
return this._directed;
}
set {
this._directed = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="directedSpecified")]
public virtual bool Directedspecified {
get {
return this._directedspecified;
}
set {
this._directedspecified = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="source")]
public virtual string Source {
get {
return this._source;
}
set {
this._source = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="target")]
public virtual string Target {
get {
return this._target;
}
set {
this._target = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="sourceport")]
public virtual string Sourceport {
get {
return this._sourceport;
}
set {
this._sourceport = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="targetport")]
public virtual string Targetport {
get {
return this._targetport;
}
set {
this._targetport = value;
}
}
public class DataCollection : System.Collections.CollectionBase {
/// <summary />
/// <remarks />
public DataCollection() {
}
/// <summary />
/// <remarks />
public virtual object this[int index] {
get {
return this.List[index];
}
set {
this.List[index] = value;
}
}
/// <summary />
/// <remarks />
public virtual void Add(object o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public virtual void AddDataType(DataType o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public virtual bool ContainsDataType(DataType o) {
return this.List.Contains(o);
}
/// <summary />
/// <remarks />
public virtual void RemoveDataType(DataType o) {
this.List.Remove(o);
}
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents the automation object for the equivalent ReferenceContainerNode object
/// </summary>
[ComVisible(true)]
public class OAReferences : ConnectionPointContainer,
IEventSource<_dispReferencesEvents>,
References,
ReferencesEvents
{
private readonly ProjectNode _project;
private ReferenceContainerNode _container;
/// <summary>
/// Creates a new automation references object. If the project type doesn't
/// support references containerNode is null.
/// </summary>
/// <param name="containerNode"></param>
/// <param name="project"></param>
internal OAReferences(ReferenceContainerNode containerNode, ProjectNode project)
{
_container = containerNode;
_project = project;
AddEventSource<_dispReferencesEvents>(this as IEventSource<_dispReferencesEvents>);
if (_container != null) {
_container.OnChildAdded += new EventHandler<HierarchyNodeEventArgs>(OnReferenceAdded);
_container.OnChildRemoved += new EventHandler<HierarchyNodeEventArgs>(OnReferenceRemoved);
}
}
#region Private Members
private Reference AddFromSelectorData(VSCOMPONENTSELECTORDATA selector)
{
if (_container == null) {
return null;
}
ReferenceNode refNode = _container.AddReferenceFromSelectorData(selector);
if (null == refNode)
{
return null;
}
return refNode.Object as Reference;
}
private Reference FindByName(string stringIndex)
{
foreach (Reference refNode in this)
{
if (0 == string.Compare(refNode.Name, stringIndex, StringComparison.Ordinal))
{
return refNode;
}
}
return null;
}
#endregion
#region References Members
public Reference Add(string bstrPath)
{
// ignore requests from the designer which are framework assemblies and start w/ a *.
if (string.IsNullOrEmpty(bstrPath) || bstrPath.StartsWith("*"))
{
return null;
}
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_File;
selector.bstrFile = bstrPath;
return AddFromSelectorData(selector);
}
public Reference AddActiveX(string bstrTypeLibGuid, int lMajorVer, int lMinorVer, int lLocaleId, string bstrWrapperTool)
{
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2;
selector.guidTypeLibrary = new Guid(bstrTypeLibGuid);
selector.lcidTypeLibrary = (uint)lLocaleId;
selector.wTypeLibraryMajorVersion = (ushort)lMajorVer;
selector.wTypeLibraryMinorVersion = (ushort)lMinorVer;
return AddFromSelectorData(selector);
}
public Reference AddProject(EnvDTE.Project project)
{
if (null == project || _container == null)
{
return null;
}
// Get the soulution.
IVsSolution solution = _container.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution;
if (null == solution)
{
return null;
}
// Get the hierarchy for this project.
IVsHierarchy projectHierarchy;
ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy));
// Create the selector data.
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project;
// Get the project reference string.
ErrorHandler.ThrowOnFailure(solution.GetProjrefOfProject(projectHierarchy, out selector.bstrProjRef));
selector.bstrTitle = project.Name;
selector.bstrFile = System.IO.Path.GetDirectoryName(project.FullName);
return AddFromSelectorData(selector);
}
public EnvDTE.Project ContainingProject
{
get
{
return _project.GetAutomationObject() as EnvDTE.Project;
}
}
public int Count
{
get
{
if (_container == null)
{
return 0;
}
return _container.EnumReferences().Count;
}
}
public EnvDTE.DTE DTE
{
get
{
return _project.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
public Reference Find(string bstrIdentity)
{
if (string.IsNullOrEmpty(bstrIdentity))
{
return null;
}
foreach (Reference refNode in this)
{
if (null != refNode)
{
if (0 == string.Compare(bstrIdentity, refNode.Identity, StringComparison.Ordinal))
{
return refNode;
}
}
}
return null;
}
public IEnumerator GetEnumerator()
{
if (_container == null) {
return new List<Reference>().GetEnumerator();
}
List<Reference> references = new List<Reference>();
IEnumerator baseEnum = _container.EnumReferences().GetEnumerator();
if (null == baseEnum)
{
return references.GetEnumerator();
}
while (baseEnum.MoveNext())
{
ReferenceNode refNode = baseEnum.Current as ReferenceNode;
if (null == refNode)
{
continue;
}
Reference reference = refNode.Object as Reference;
if (null != reference)
{
references.Add(reference);
}
}
return references.GetEnumerator();
}
public Reference Item(object index)
{
if (_container == null)
{
throw new ArgumentOutOfRangeException("index");
}
string stringIndex = index as string;
if (null != stringIndex)
{
return FindByName(stringIndex);
}
// Note that this cast will throw if the index is not convertible to int.
int intIndex = (int)index;
IList<ReferenceNode> refs = _container.EnumReferences();
if (null == refs)
{
throw new ArgumentOutOfRangeException("index");
}
if ((intIndex <= 0) || (intIndex > refs.Count))
{
throw new ArgumentOutOfRangeException("index");
}
// Let the implementation of IList<> throw in case of index not correct.
return refs[intIndex - 1].Object as Reference;
}
public object Parent
{
get
{
if (_container == null)
{
return _project.Object;
}
return _container.Parent.Object;
}
}
#endregion
#region _dispReferencesEvents_Event Members
public event _dispReferencesEvents_ReferenceAddedEventHandler ReferenceAdded;
public event _dispReferencesEvents_ReferenceChangedEventHandler ReferenceChanged {
add { }
remove { }
}
public event _dispReferencesEvents_ReferenceRemovedEventHandler ReferenceRemoved;
#endregion
#region Callbacks for the HierarchyNode events
private void OnReferenceAdded(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((_container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceAdded)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceAdded(reference);
}
}
private void OnReferenceRemoved(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((_container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceRemoved)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceRemoved(reference);
}
}
#endregion
#region IEventSource<_dispReferencesEvents> Members
void IEventSource<_dispReferencesEvents>.OnSinkAdded(_dispReferencesEvents sink)
{
ReferenceAdded += new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged += new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved += new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
void IEventSource<_dispReferencesEvents>.OnSinkRemoved(_dispReferencesEvents sink)
{
ReferenceAdded -= new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged -= new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved -= new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
#endregion
}
}
| |
/*
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.
*/
#define ON_IMAGE_CHANGED_ALWAYS_CREATE_IMAGE
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.RenderOpenGl.OpenGl;
using MatterHackers.VectorMath;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace MatterHackers.RenderOpenGl
{
public class ImageGlPlugin
{
private static ConditionalWeakTable<Byte[], ImageGlPlugin> imagesWithCacheData = new ConditionalWeakTable<Byte[], ImageGlPlugin>();
internal struct glAllocatedData
{
internal int glTextureHandle;
internal int refreshCountCreatedOn;
public float[] textureUVs;
public float[] positions;
}
private static List<glAllocatedData> glDataNeedingToBeDeleted = new List<glAllocatedData>();
private glAllocatedData glData;
private int imageUpdateCount;
private bool createdWithMipMaps;
private static int currentGlobalRefreshCount = 0;
static public void MarkAllImagesNeedRefresh()
{
currentGlobalRefreshCount++;
}
static public ImageGlPlugin GetImageGlPlugin(ImageBuffer imageToGetDisplayListFor, bool createAndUseMipMaps, bool TextureMagFilterLinear = true)
{
ImageGlPlugin plugin;
imagesWithCacheData.TryGetValue(imageToGetDisplayListFor.GetBuffer(), out plugin);
using (TimedLock.Lock(glDataNeedingToBeDeleted, "GetImageGlPlugin"))
{
// We run this in here to ensure that we are on the correct thread and have the correct
// glcontext realized.
for (int i = glDataNeedingToBeDeleted.Count - 1; i >= 0; i--)
{
int textureToDelete = glDataNeedingToBeDeleted[i].glTextureHandle;
if (glDataNeedingToBeDeleted[i].refreshCountCreatedOn == currentGlobalRefreshCount)
{
GL.DeleteTextures(1, ref textureToDelete);
}
glDataNeedingToBeDeleted.RemoveAt(i);
}
}
#if ON_IMAGE_CHANGED_ALWAYS_CREATE_IMAGE
if (plugin != null
&& (imageToGetDisplayListFor.ChangedCount != plugin.imageUpdateCount
|| plugin.glData.refreshCountCreatedOn != currentGlobalRefreshCount))
{
int textureToDelete = plugin.GLTextureHandle;
if (plugin.glData.refreshCountCreatedOn == currentGlobalRefreshCount)
{
GL.DeleteTextures(1, ref textureToDelete);
}
plugin.glData.glTextureHandle = 0;
imagesWithCacheData.Remove(imageToGetDisplayListFor.GetBuffer());
plugin = null;
}
if (plugin == null)
{
ImageGlPlugin newPlugin = new ImageGlPlugin();
imagesWithCacheData.Add(imageToGetDisplayListFor.GetBuffer(), newPlugin);
newPlugin.createdWithMipMaps = createAndUseMipMaps;
newPlugin.CreateGlDataForImage(imageToGetDisplayListFor, TextureMagFilterLinear);
newPlugin.imageUpdateCount = imageToGetDisplayListFor.ChangedCount;
newPlugin.glData.refreshCountCreatedOn = currentGlobalRefreshCount;
return newPlugin;
}
#else
if (plugin == null)
{
ImageGlPlugin newPlugin = new ImageGlPlugin();
imagesWithCacheData.Add(imageToGetDisplayListFor.GetBuffer(), newPlugin);
newPlugin.createdWithMipMaps = createAndUseMipMaps;
newPlugin.CreateGlDataForImage(imageToGetDisplayListFor, TextureMagFilterLinear);
newPlugin.imageUpdateCount = imageToGetDisplayListFor.ChangedCount;
newPlugin.refreshCountCreatedOn = currentGlobalRefreshCount;
return newPlugin;
}
if(imageToGetDisplayListFor.ChangedCount != plugin.imageUpdateCount
|| plugin.refreshCountCreatedOn != currentGlobalRefreshCount)
{
plugin.imageUpdateCount = imageToGetDisplayListFor.ChangedCount;
plugin.refreshCountCreatedOn = currentGlobalRefreshCount;
GL.BindTexture(TextureTarget.Texture2D, plugin.GLTextureHandle);
// Create the texture
switch (imageToGetDisplayListFor.BitDepth)
{
case 8:
GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, imageToGetDisplayListFor.Width, imageToGetDisplayListFor.Height,
PixelFormat.Luminance, PixelType.UnsignedByte, imageToGetDisplayListFor.GetBuffer());
break;
case 24:
// our bitmaps are not padded and GL is having a problem with them so don't use 24 bit unless you fix this.
GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, imageToGetDisplayListFor.Width, imageToGetDisplayListFor.Height,
PixelFormat.Bgr, PixelType.UnsignedByte, imageToGetDisplayListFor.GetBuffer());
break;
case 32:
GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, imageToGetDisplayListFor.Width, imageToGetDisplayListFor.Height,
PixelFormat.Bgra, PixelType.UnsignedByte, imageToGetDisplayListFor.GetBuffer());
break;
default:
throw new NotImplementedException();
}
if (plugin.createdWithMipMaps)
{
if (GLMajorVersion < 3)
{
switch (imageToGetDisplayListFor.BitDepth)
{
case 32:
{
ImageBuffer sourceImage = new ImageBuffer(imageToGetDisplayListFor);
ImageBuffer tempImage = new ImageBuffer(sourceImage.Width / 2, sourceImage.Height / 2, 32, new BlenderBGRA());
tempImage.NewGraphics2D().Render(sourceImage, 0, 0, 0, .5, .5);
int mipLevel = 1;
while (sourceImage.Width > 1 && sourceImage.Height > 1)
{
GL.TexSubImage2D(TextureTarget.Texture2D, mipLevel++, 0, 0, tempImage.Width, tempImage.Height,
PixelFormat.Bgra, PixelType.UnsignedByte, tempImage.GetBuffer());
sourceImage = new ImageBuffer(tempImage);
tempImage = new ImageBuffer(Math.Max(1, sourceImage.Width / 2), Math.Max(1, sourceImage.Height / 2), 32, new BlenderBGRA());
tempImage.NewGraphics2D().Render(sourceImage, 0, 0,
0,
(double)tempImage.Width / (double)sourceImage.Width,
(double)tempImage.Height / (double)sourceImage.Height);
}
}
break;
default:
throw new NotImplementedException();
}
}
else
{
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
}
}
}
#endif
return plugin;
}
public int GLTextureHandle
{
get
{
return glData.glTextureHandle;
}
}
private ImageGlPlugin()
{
// This is private as you can't build one of these. You have to call GetImageGlPlugin.
}
~ImageGlPlugin()
{
using (TimedLock.Lock(glDataNeedingToBeDeleted, "~ImageGlPlugin()"))
{
glDataNeedingToBeDeleted.Add(glData);
}
}
private bool hwSupportsOnlyPowerOfTwoTextures = true;
private bool checkedForHwSupportsOnlyPowerOfTwoTextures = false;
private int SmallestHardwareCompatibleTextureSize(int size)
{
if (!checkedForHwSupportsOnlyPowerOfTwoTextures)
{
{
// Compatible context (GL 1.0-2.1)
string extensions = GL.GetString(StringName.Extensions);
if (extensions.Contains("ARB_texture_non_power_of_two"))
{
hwSupportsOnlyPowerOfTwoTextures = false;
}
}
checkedForHwSupportsOnlyPowerOfTwoTextures = true;
}
if (hwSupportsOnlyPowerOfTwoTextures)
{
return MathHelper.FirstPowerTowGreaterThanOrEqualTo(size);
}
else
{
return size;
}
}
private void CreateGlDataForImage(ImageBuffer bufferedImage, bool TextureMagFilterLinear)
{
//Next we expand the image into an openGL texture
int imageWidth = bufferedImage.Width;
int imageHeight = bufferedImage.Height;
int bufferOffset;
byte[] imageBuffer = bufferedImage.GetBuffer(out bufferOffset);
int hardwareWidth = SmallestHardwareCompatibleTextureSize(imageWidth);
int hardwareHeight = SmallestHardwareCompatibleTextureSize(imageHeight);
byte[] hardwareExpandedPixelBuffer = imageBuffer;
if (hardwareWidth != imageWidth || hardwareHeight != imageHeight)
{
// we have to put the data on a buffer that GL can handle.
hardwareExpandedPixelBuffer = new byte[4 * hardwareWidth * hardwareHeight];
switch (bufferedImage.BitDepth)
{
case 32:
for (int y = 0; y < hardwareHeight; y++)
{
for (int x = 0; x < hardwareWidth; x++)
{
int pixelIndex = 4 * (x + y * hardwareWidth);
if (x >= imageWidth || y >= imageHeight)
{
hardwareExpandedPixelBuffer[pixelIndex + 0] = 0;
hardwareExpandedPixelBuffer[pixelIndex + 1] = 0;
hardwareExpandedPixelBuffer[pixelIndex + 2] = 0;
hardwareExpandedPixelBuffer[pixelIndex + 3] = 0;
}
else
{
hardwareExpandedPixelBuffer[pixelIndex + 0] = imageBuffer[4 * (x + y * imageWidth) + 2];
hardwareExpandedPixelBuffer[pixelIndex + 1] = imageBuffer[4 * (x + y * imageWidth) + 1];
hardwareExpandedPixelBuffer[pixelIndex + 2] = imageBuffer[4 * (x + y * imageWidth) + 0];
hardwareExpandedPixelBuffer[pixelIndex + 3] = imageBuffer[4 * (x + y * imageWidth) + 3];
}
}
}
break;
default:
throw new NotImplementedException();
}
}
GL.Enable(EnableCap.Texture2D);
// Create the texture handle
GL.GenTextures(1, out glData.glTextureHandle);
// Set up some texture parameters for openGL
GL.BindTexture(TextureTarget.Texture2D, glData.glTextureHandle);
if (TextureMagFilterLinear)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
}
else
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
}
if (createdWithMipMaps)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
}
else
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
}
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
// Create the texture
switch (bufferedImage.BitDepth)
{
#if false // not implemented in our gl wrapper and never used in our current code
case 8:
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Luminance, hardwareWidth, hardwareHeight,
0, PixelFormat.Luminance, PixelType.UnsignedByte, hardwareExpandedPixelBuffer);
break;
case 24:
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, hardwareWidth, hardwareHeight,
0, PixelFormat.Rgb, PixelType.UnsignedByte, hardwareExpandedPixelBuffer);
break;
#endif
case 32:
#if __ANDROID__
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, hardwareWidth, hardwareHeight,
0, PixelFormat.Rgba, PixelType.UnsignedByte, hardwareExpandedPixelBuffer);
#else
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, hardwareWidth, hardwareHeight,
0, PixelFormat.Bgra, PixelType.UnsignedByte, hardwareExpandedPixelBuffer);
#endif
break;
default:
throw new NotImplementedException();
}
hardwareExpandedPixelBuffer = null;
if (createdWithMipMaps)
{
switch (bufferedImage.BitDepth)
{
case 32:
{
ImageBuffer sourceImage = new ImageBuffer(bufferedImage);
ImageBuffer tempImage = new ImageBuffer(sourceImage.Width / 2, sourceImage.Height / 2, 32, new BlenderBGRA());
tempImage.NewGraphics2D().Render(sourceImage, 0, 0, 0, .5, .5);
int mipLevel = 1;
while (sourceImage.Width > 1 && sourceImage.Height > 1)
{
#if __ANDROID__
GL.TexImage2D(TextureTarget.Texture2D, mipLevel++, PixelInternalFormat.Rgba, tempImage.Width, tempImage.Height,
0, PixelFormat.Rgba, PixelType.UnsignedByte, tempImage.GetBuffer());
#else
GL.TexImage2D(TextureTarget.Texture2D, mipLevel++, PixelInternalFormat.Rgba, tempImage.Width, tempImage.Height,
0, PixelFormat.Bgra, PixelType.UnsignedByte, tempImage.GetBuffer());
#endif
sourceImage = new ImageBuffer(tempImage);
tempImage = new ImageBuffer(Math.Max(1, sourceImage.Width / 2), Math.Max(1, sourceImage.Height / 2), 32, new BlenderBGRA());
tempImage.NewGraphics2D().Render(sourceImage, 0, 0,
0,
(double)tempImage.Width / (double)sourceImage.Width,
(double)tempImage.Height / (double)sourceImage.Height);
}
}
break;
default:
throw new NotImplementedException();
}
}
float texCoordX = imageWidth / (float)hardwareWidth;
float texCoordY = imageHeight / (float)hardwareHeight;
float OffsetX = (float)bufferedImage.OriginOffset.x;
float OffsetY = (float)bufferedImage.OriginOffset.y;
glData.textureUVs = new float[8];
glData.positions = new float[8];
glData.textureUVs[0] = 0; glData.textureUVs[1] = 0; glData.positions[0] = 0 - OffsetX; glData.positions[1] = 0 - OffsetY;
glData.textureUVs[2] = 0; glData.textureUVs[3] = texCoordY; glData.positions[2] = 0 - OffsetX; glData.positions[3] = imageHeight - OffsetY;
glData.textureUVs[4] = texCoordX; glData.textureUVs[5] = texCoordY; glData.positions[4] = imageWidth - OffsetX; glData.positions[5] = imageHeight - OffsetY;
glData.textureUVs[6] = texCoordX; glData.textureUVs[7] = 0; glData.positions[6] = imageWidth - OffsetX; glData.positions[7] = 0 - OffsetY;
}
public void DrawToGL()
{
GL.BindTexture(TextureTarget.Texture2D, GLTextureHandle);
#if true
GL.Begin(BeginMode.TriangleFan);
GL.TexCoord2(glData.textureUVs[0], glData.textureUVs[1]); GL.Vertex2(glData.positions[0], glData.positions[1]);
GL.TexCoord2(glData.textureUVs[2], glData.textureUVs[3]); GL.Vertex2(glData.positions[2], glData.positions[3]);
GL.TexCoord2(glData.textureUVs[4], glData.textureUVs[5]); GL.Vertex2(glData.positions[4], glData.positions[5]);
GL.TexCoord2(glData.textureUVs[6], glData.textureUVs[7]); GL.Vertex2(glData.positions[6], glData.positions[7]);
GL.End();
#else
GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, glData.textureUVs);
GL.EnableClientState(ArrayCap.TextureCoordArray);
GL.VertexPointer(2, VertexPointerType.Float, 0, glData.positions);
GL.EnableClientState(ArrayCap.VertexArray);
GL.DrawArrays(PrimitiveType.TriangleFan, 0, 4);
GL.Disable(EnableCap.Texture2D);
GL.DisableClientState(ArrayCap.TextureCoordArray);
GL.DisableClientState(ArrayCap.VertexArray);
#endif
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Apache.Ignite.Core.Binary;
/// <summary>
/// Resolves types by name.
/// </summary>
internal class TypeResolver
{
/** Assemblies loaded in ReflectionOnly mode. */
private readonly Dictionary<string, Assembly> _reflectionOnlyAssemblies = new Dictionary<string, Assembly>();
/// <summary>
/// Resolve type by name.
/// </summary>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblyName">Optional, name of the assembly.</param>
/// <param name="nameMapper">The name mapper.</param>
/// <returns>
/// Resolved type.
/// </returns>
public Type ResolveType(string typeName, string assemblyName = null, IBinaryNameMapper nameMapper = null)
{
Debug.Assert(!string.IsNullOrEmpty(typeName));
// Fully-qualified name can be resolved with system mechanism.
var type = Type.GetType(typeName, false);
if (type != null)
{
return type;
}
var parsedType = TypeNameParser.Parse(typeName);
// Partial names should be resolved by scanning assemblies.
return ResolveType(assemblyName, parsedType, AppDomain.CurrentDomain.GetAssemblies(), nameMapper)
?? ResolveTypeInReferencedAssemblies(assemblyName, parsedType, nameMapper);
}
/// <summary>
/// Resolve type by name in specified assembly set.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">Assemblies to look in.</param>
/// <param name="nameMapper">The name mapper.</param>
/// <returns>
/// Resolved type.
/// </returns>
private static Type ResolveType(string assemblyName, TypeNameParser typeName, ICollection<Assembly> assemblies,
IBinaryNameMapper nameMapper)
{
var type = ResolveNonGenericType(assemblyName, typeName.GetNameWithNamespace(), assemblies, nameMapper);
if (type == null)
{
return null;
}
if (type.IsGenericTypeDefinition && typeName.Generics != null)
{
var genArgs = typeName.Generics
.Select(x => ResolveType(assemblyName, x, assemblies, nameMapper)).ToArray();
if (genArgs.Any(x => x == null))
{
return null;
}
type = type.MakeGenericType(genArgs);
}
return MakeArrayType(type, typeName.GetArray());
}
/// <summary>
/// Makes the array type according to spec, e.g. "[,][]".
/// </summary>
private static Type MakeArrayType(Type type, string arraySpec)
{
if (arraySpec == null)
{
return type;
}
int? rank = null;
foreach (var c in arraySpec)
{
switch (c)
{
case '[':
rank = null;
break;
case ',':
rank = rank == null ? 2 : rank + 1;
break;
case '*':
rank = 1;
break;
case ']':
type = rank == null
? type.MakeArrayType()
: type.MakeArrayType(rank.Value);
break;
}
}
return type;
}
/// <summary>
/// Resolves non-generic type by searching provided assemblies.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">The assemblies.</param>
/// <param name="nameMapper">The name mapper.</param>
/// <returns>Resolved type, or null.</returns>
private static Type ResolveNonGenericType(string assemblyName, string typeName,
ICollection<Assembly> assemblies, IBinaryNameMapper nameMapper)
{
// Fully-qualified name can be resolved with system mechanism.
var type = Type.GetType(typeName, false);
if (type != null)
{
return type;
}
if (!string.IsNullOrEmpty(assemblyName))
{
assemblies = assemblies
.Where(x => x.FullName == assemblyName || x.GetName().Name == assemblyName).ToArray();
}
if (!assemblies.Any())
{
return null;
}
return assemblies.Select(a => FindType(a, typeName, nameMapper)).FirstOrDefault(x => x != null);
}
/// <summary>
/// Resolve type by name in non-loaded referenced assemblies.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="nameMapper">The name mapper.</param>
/// <returns>
/// Resolved type.
/// </returns>
private Type ResolveTypeInReferencedAssemblies(string assemblyName, TypeNameParser typeName,
IBinaryNameMapper nameMapper)
{
ResolveEventHandler resolver = (sender, args) => GetReflectionOnlyAssembly(args.Name);
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolver;
try
{
var result = ResolveType(assemblyName, typeName, GetNotLoadedReferencedAssemblies().ToArray(),
nameMapper);
if (result == null)
return null;
// result is from ReflectionOnly assembly, load it properly into current domain
var asm = AppDomain.CurrentDomain.Load(result.Assembly.GetName());
return FindType(asm, result.FullName, nameMapper);
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver;
}
}
/// <summary>
/// Gets the reflection only assembly.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Assembly GetReflectionOnlyAssembly(string fullName)
{
Assembly result;
if (!_reflectionOnlyAssemblies.TryGetValue(fullName, out result))
{
try
{
result = Assembly.ReflectionOnlyLoad(fullName);
}
catch (Exception)
{
// Some assemblies may fail to load
result = null;
}
_reflectionOnlyAssemblies[fullName] = result;
}
return result;
}
/// <summary>
/// Recursively gets all referenced assemblies for current app domain, excluding those that are loaded.
/// </summary>
private IEnumerable<Assembly> GetNotLoadedReferencedAssemblies()
{
var roots = new Stack<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
var visited = new HashSet<string>();
var loaded = new HashSet<string>(roots.Select(x => x.FullName));
while (roots.Any())
{
var asm = roots.Pop();
if (visited.Contains(asm.FullName))
continue;
if (!loaded.Contains(asm.FullName))
yield return asm;
visited.Add(asm.FullName);
foreach (var refAsm in asm.GetReferencedAssemblies()
.Where(x => !visited.Contains(x.FullName))
.Where(x => !loaded.Contains(x.FullName))
.Select(x => GetReflectionOnlyAssembly(x.FullName))
.Where(x => x != null))
roots.Push(refAsm);
}
}
/// <summary>
/// Finds the type within assembly.
/// </summary>
private static Type FindType(Assembly asm, string typeName, IBinaryNameMapper mapper)
{
if (asm.IsDynamic)
{
return null;
}
if (mapper == null)
{
return asm.GetType(typeName);
}
return GetAssemblyTypesSafe(asm).FirstOrDefault(x => mapper.GetTypeName(x.FullName) == typeName);
}
/// <summary>
/// Safely gets all assembly types.
/// </summary>
public static IEnumerable<Type> GetAssemblyTypesSafe(Assembly asm)
{
try
{
return asm.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
// Handle the situation where some assembly dependencies are not available.
return ex.Types.Where(x => x != null);
}
}
}
}
| |
//
// LunarConsoleActionEditor.cs
//
// Lunar Unity Mobile Console
// https://github.com/SpaceMadness/lunar-unity-console
//
// Copyright 2015-2021 Alex Lementuev, SpaceMadness.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using LunarConsolePlugin;
using LunarConsolePluginInternal;
using System.Text;
namespace LunarConsoleEditorInternal
{
[CustomEditor(typeof(LunarConsoleAction))]
class LunarConsoleActionEditor : Editor
{
private const string kPropCalls = "m_calls";
private const string kPropMode = "m_mode";
private const string kPropTarget = "m_target";
private const string kPropMethod = "m_methodName";
private const string kPropArguments = "m_arguments";
private const string kPropObjectArgumentAssemblyTypeName = "m_objectArgumentAssemblyTypeName";
ReorderableList list;
struct Function
{
public readonly UnityEngine.Object target;
public readonly MethodInfo method;
public Function(UnityEngine.Object target, MethodInfo method)
{
this.target = target;
this.method = method;
}
public bool isProperty
{
get { return method.IsSpecialName && method.Name.StartsWith("set_"); }
}
public string simpleName
{
get { return isProperty ? method.Name.Substring("set_".Length) : method.Name; }
}
public Type paramType
{
get
{
var methodParams = method.GetParameters();
return methodParams.Length > 0 ? methodParams[0].ParameterType : null;
}
}
public string displayName
{
get
{
var functionParamType = paramType;
if (functionParamType != null)
{
var typeName = ClassUtils.TypeShortName(functionParamType);
return isProperty ?
string.Format("{0} {1}", typeName, simpleName) :
string.Format("{0} ({1})", simpleName, typeName);
}
return string.Format("{0} ()", simpleName);
}
}
}
private void OnEnable()
{
list = new ReorderableList(serializedObject, serializedObject.FindProperty(kPropCalls), false, true, true, true);
list.drawHeaderCallback = DrawListHeader;
list.drawElementCallback = DrawListElement;
list.elementHeight = 43;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
list.DoLayoutList();
serializedObject.ApplyModifiedProperties();
}
void DrawListHeader(Rect rect)
{
EditorGUI.LabelField(rect, "On Click ()");
}
void DrawListElement(Rect rect, int index, bool isActive, bool isFocused)
{
SerializedProperty arrayElementAtIndex = list.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 1f;
Rect[] rowRects = GetRowRects(rect);
Rect runtimeModeRect = rowRects[0];
Rect targetRect = rowRects[1];
Rect methodRect = rowRects[2];
Rect argumentRect = rowRects[3];
SerializedProperty modeProperty = arrayElementAtIndex.FindPropertyRelative(kPropMode);
SerializedProperty targetProperty = arrayElementAtIndex.FindPropertyRelative(kPropTarget);
SerializedProperty methodProperty = arrayElementAtIndex.FindPropertyRelative(kPropMethod);
SerializedProperty argumentsProperty = arrayElementAtIndex.FindPropertyRelative(kPropArguments);
Color backgroundColor = GUI.backgroundColor;
GUI.backgroundColor = Color.white;
var oldFlag = GUI.enabled;
GUI.enabled = false;
GUI.Box(runtimeModeRect, "Runtime Only", EditorStyles.popup);
GUI.enabled = oldFlag;
EditorGUI.BeginChangeCheck();
GUI.Box(targetRect, GUIContent.none);
EditorGUI.PropertyField(targetRect, targetProperty, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
methodProperty.stringValue = null;
}
LunarPersistentListenerMode persistentListenerMode = (LunarPersistentListenerMode) modeProperty.enumValueIndex;
if (targetProperty.objectReferenceValue == null || string.IsNullOrEmpty(methodProperty.stringValue))
{
persistentListenerMode = LunarPersistentListenerMode.Void;
}
SerializedProperty argumentProperty;
switch (persistentListenerMode)
{
case LunarPersistentListenerMode.Object:
argumentProperty = argumentsProperty.FindPropertyRelative("m_objectArgument");
break;
case LunarPersistentListenerMode.Int:
argumentProperty = argumentsProperty.FindPropertyRelative("m_intArgument");
break;
case LunarPersistentListenerMode.Float:
argumentProperty = argumentsProperty.FindPropertyRelative("m_floatArgument");
break;
case LunarPersistentListenerMode.String:
argumentProperty = argumentsProperty.FindPropertyRelative("m_stringArgument");
break;
case LunarPersistentListenerMode.Bool:
argumentProperty = argumentsProperty.FindPropertyRelative("m_boolArgument");
break;
default:
argumentProperty = argumentsProperty.FindPropertyRelative("m_intArgument");
break;
}
string argumentAssemblyTypeName = argumentsProperty.FindPropertyRelative(kPropObjectArgumentAssemblyTypeName).stringValue;
Type argumentType = typeof(UnityEngine.Object);
if (!string.IsNullOrEmpty(argumentAssemblyTypeName))
{
argumentType = (Type.GetType(argumentAssemblyTypeName, false) ?? typeof(UnityEngine.Object));
}
if (persistentListenerMode == LunarPersistentListenerMode.Object)
{
EditorGUI.BeginChangeCheck();
UnityEngine.Object objectReferenceValue = EditorGUI.ObjectField(argumentRect, GUIContent.none, argumentProperty.objectReferenceValue, argumentType, true);
if (EditorGUI.EndChangeCheck())
{
argumentProperty.objectReferenceValue = objectReferenceValue;
}
}
else if (persistentListenerMode != LunarPersistentListenerMode.Void)
{
EditorGUI.PropertyField(argumentRect, argumentProperty, GUIContent.none);
}
using (new DisabledScopeCompat(targetProperty.objectReferenceValue == null))
{
EditorGUI.BeginProperty(methodRect, GUIContent.none, methodProperty);
GUIContent content;
{
StringBuilder stringBuilder = new StringBuilder();
if (targetProperty.objectReferenceValue == null || string.IsNullOrEmpty(methodProperty.stringValue))
{
stringBuilder.Append("No Function");
}
else if (!LunarConsoleActionCall.IsPersistantListenerValid(targetProperty.objectReferenceValue, methodProperty.stringValue, persistentListenerMode))
{
string componentName = "UnknownComponent";
UnityEngine.Object target = targetProperty.objectReferenceValue;
if (target != null)
{
componentName = target.GetType().Name;
}
stringBuilder.Append(string.Format("<Missing {0}.{1}>", componentName, methodProperty.stringValue));
}
else
{
stringBuilder.Append(targetProperty.objectReferenceValue.GetType().Name);
if (!string.IsNullOrEmpty(methodProperty.stringValue))
{
stringBuilder.Append(".");
if (methodProperty.stringValue.StartsWith("set_"))
{
stringBuilder.Append(methodProperty.stringValue.Substring(4));
}
else
{
stringBuilder.Append(methodProperty.stringValue);
}
}
}
content = new GUIContent(stringBuilder.ToString());
}
if (GUI.Button(methodRect, content, EditorStyles.popup))
{
BuildPopupList(arrayElementAtIndex).DropDown(methodRect);
}
EditorGUI.EndProperty();
}
GUI.backgroundColor = backgroundColor;
}
private GenericMenu BuildPopupList(SerializedProperty serializedProperty)
{
SerializedProperty targetProperty = serializedProperty.FindPropertyRelative(kPropTarget);
SerializedProperty methodProperty = serializedProperty.FindPropertyRelative(kPropMethod);
var menu = new GenericMenu();
menu.AddItem(new GUIContent("No Function"), methodProperty.stringValue == null, delegate() {
methodProperty.stringValue = null;
serializedObject.ApplyModifiedProperties();
});
var target = targetProperty.objectReferenceValue;
if (target != null)
{
menu.AddSeparator("/");
var functions = ListFunctions(target);
foreach (var function in functions)
{
var selected = target == function.target && methodProperty.stringValue == function.method.Name;
menu.AddItem(new GUIContent(function.target.GetType().Name + "/" + function.displayName), selected, delegate () {
targetProperty.objectReferenceValue = function.target;
methodProperty.stringValue = function.method.Name;
UpdateParamProperty(serializedProperty, function.paramType);
serializedObject.ApplyModifiedProperties();
});
}
}
return menu;
}
void UpdateParamProperty(SerializedProperty serializedProperty, Type paramType)
{
SerializedProperty modeProperty = serializedProperty.FindPropertyRelative(kPropMode);
SerializedProperty argumentsProperty = serializedProperty.FindPropertyRelative(kPropArguments);
SerializedProperty typeAssemblyProperty = argumentsProperty.FindPropertyRelative(kPropObjectArgumentAssemblyTypeName);
LunarPersistentListenerMode mode = LunarPersistentListenerMode.Void;
if (paramType != null)
{
if (paramType.IsSubclassOf(typeof(UnityEngine.Object)))
{
mode = LunarPersistentListenerMode.Object;
}
else if (paramType == typeof(int))
{
mode = LunarPersistentListenerMode.Int;
}
else if (paramType == typeof(float))
{
mode = LunarPersistentListenerMode.Float;
}
else if (paramType == typeof(string))
{
mode = LunarPersistentListenerMode.String;
}
else if (paramType == typeof(bool))
{
mode = LunarPersistentListenerMode.Bool;
}
else
{
Log.e("Unexpected param type: {0}", paramType);
}
}
modeProperty.enumValueIndex = (int)mode;
typeAssemblyProperty.stringValue = paramType != null ? paramType.AssemblyQualifiedName : null;
}
private Rect[] GetRowRects(Rect rect)
{
Rect[] array = new Rect[4];
rect.height = 16f;
rect.y += 2f;
Rect rect2 = rect;
rect2.width *= 0.3f;
Rect rect3 = rect2;
rect3.y += EditorGUIUtility.singleLineHeight + 2f;
Rect rect4 = rect;
rect4.xMin = rect3.xMax + 5f;
Rect rect5 = rect4;
rect5.y += EditorGUIUtility.singleLineHeight + 2f;
array[0] = rect2;
array[1] = rect3;
array[2] = rect4;
array[3] = rect5;
return array;
}
Function[] ListFunctions(UnityEngine.Object obj)
{
if (obj is Component)
{
obj = ((Component)obj).gameObject;
}
List<Function> functions = new List<Function>();
if (obj != null)
{
List<UnityEngine.Object> targets = new List<UnityEngine.Object>();
targets.Add(obj);
if (obj is GameObject)
{
var gameObject = obj as GameObject;
foreach (var component in gameObject.GetComponents<Component>())
{
targets.Add(component);
}
}
foreach (var target in targets)
{
List<MethodInfo> methods = LunarConsoleActionCall.ListActionMethods(target);
methods.Sort(delegate (MethodInfo a, MethodInfo b) {
return a.IsSpecialName == b.IsSpecialName ? a.Name.CompareTo(b.Name) : (a.IsSpecialName ? -1 : 1);
});
foreach (var method in methods)
{
functions.Add(new Function(target, method));
}
}
}
return functions.ToArray();
}
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the ParserME.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpEntropy;
using System.Text;
namespace OpenNLP.Tools.Parser
{
/// <summary>
/// Class for a shift reduce style parser based on Adwait Ratnaparki's 1998 thesis.
/// </summary>
public class MaximumEntropyParser
{
/// <summary>
/// The maximum number of parses advanced from all preceding parses at each derivation step.
/// </summary>
private readonly int m;
///<summary>
///The maximum number of parses to advance from a single preceding parse.
///</summary>
private readonly int k;
///<summary>
///The minimum total probability mass of advanced outcomes.
///</summary>
private readonly double q;
///<summary>
///The default beam size used if no beam size is given.
///</summary>
public const int DefaultBeamSize = 20;
///<summary>
///The default amount of probability mass required of advanced outcomes.
///</summary>
public const double DefaultAdvancePercentage = 0.95;
private readonly IParserTagger posTagger;
private readonly IParserChunker basalChunker;
private readonly SharpEntropy.IMaximumEntropyModel buildModel;
private readonly SharpEntropy.IMaximumEntropyModel checkModel;
private readonly BuildContextGenerator buildContextGenerator;
private readonly CheckContextGenerator checkContextGenerator;
private readonly IHeadRules headRules;
public const string TopNode = "TOP";
public const string TokenNode = "TK";
public const int Zero = 0;
/// <summary>
/// Prefix for outcomes starting a constituent.
/// </summary>
public const string StartPrefix = "S-";
/// <summary>
/// Prefix for outcomes continuing a constituent.
/// </summary>
public const string ContinuePrefix = "C-";
/// <summary>
/// Outcome for token which is not contained in a basal constituent.
/// </summary>
public const string OtherOutcome = "O";
/// <summary>
/// Outcome used when a constituent is complete.
/// </summary>
public const string CompleteOutcome = "c";
/// <summary>
/// Outcome used when a constituent is incomplete.
/// </summary>
public const string IncompleteOutcome = "i";
private const string MTopStart = StartPrefix + TopNode;
private readonly int topStartIndex;
private readonly Dictionary<string, string> startTypeMap;
private readonly Dictionary<string, string> continueTypeMap;
private readonly int completeIndex;
private readonly int incompleteIndex;
private const bool CreateDerivationString = false;
// Constructors -------------------------
///<summary>
///Creates a new parser using the specified models and head rules.
///</summary>
///<param name="buildModel">
///The model to assign constituent labels.
///</param>
///<param name="checkModel">
///The model to determine a constituent is complete.
///</param>
///<param name="tagger">
///The model to assign pos-tags.
///</param>
///<param name="chunker">
///The model to assign flat constituent labels.
///</param>
///<param name="headRules">
///The head rules for head word perculation.
///</param>
public MaximumEntropyParser(SharpEntropy.IMaximumEntropyModel buildModel, SharpEntropy.IMaximumEntropyModel checkModel, IParserTagger tagger, IParserChunker chunker, IHeadRules headRules) : this(buildModel, checkModel, tagger, chunker, headRules, DefaultBeamSize, DefaultAdvancePercentage)
{}
///<summary>
///Creates a new parser using the specified models and head rules using the specified beam size and advance percentage.
///</summary>
///<param name="buildModel">
///The model to assign constituent labels.
///</param>
///<param name="checkModel">
///The model to determine a constituent is complete.
///</param>
///<param name="tagger">
///The model to assign pos-tags.
///</param>
///<param name="chunker">
///The model to assign flat constituent labels.
///</param>
///<param name="headRules">
///The head rules for head word perculation.
///</param>
///<param name="beamSize">
///The number of different parses kept during parsing.
///</param>
///<param name="advancePercentage">
///The minimal amount of probability mass which advanced outcomes must represent.
///Only outcomes which contribute to the top "advancePercentage" will be explored.
///</param>
public MaximumEntropyParser(SharpEntropy.IMaximumEntropyModel buildModel, SharpEntropy.IMaximumEntropyModel checkModel, IParserTagger tagger, IParserChunker chunker, IHeadRules headRules, int beamSize, double advancePercentage)
{
posTagger = tagger;
basalChunker = chunker;
this.buildModel = buildModel;
this.checkModel = checkModel;
m = beamSize;
k = beamSize;
q = advancePercentage;
buildContextGenerator = new BuildContextGenerator();
checkContextGenerator = new CheckContextGenerator();
this.headRules = headRules;
startTypeMap = new Dictionary<string, string>();
continueTypeMap = new Dictionary<string, string>();
for (int buildOutcomeIndex = 0, buildOutcomeCount = buildModel.OutcomeCount; buildOutcomeIndex < buildOutcomeCount; buildOutcomeIndex++)
{
string outcome = buildModel.GetOutcomeName(buildOutcomeIndex);
if (outcome.StartsWith(StartPrefix))
{
//System.Console.Error.WriteLine("startMap " + outcome + "->" + outcome.Substring(StartPrefix.Length));
startTypeMap.Add(outcome, outcome.Substring(StartPrefix.Length));
}
else if (outcome.StartsWith(ContinuePrefix))
{
//System.Console.Error.WriteLine("contMap " + outcome + "->" + outcome.Substring(ContinuePrefix.Length));
continueTypeMap.Add(outcome, outcome.Substring(ContinuePrefix.Length));
}
}
topStartIndex = buildModel.GetOutcomeIndex(MTopStart);
completeIndex = checkModel.GetOutcomeIndex(CompleteOutcome);
incompleteIndex = checkModel.GetOutcomeIndex(IncompleteOutcome);
}
// Methods ------------------------------
/// <summary>
/// Returns a parse for the specified parse of tokens.
/// </summary>
/// <param name="flatParse">
/// A flat parse containing only tokens and a root node, p.
/// </param>
/// <param name="parseCount">
/// the number of parses required
/// </param>
/// <returns>
/// A full parse of the specified tokens or the flat chunks of the tokens if a full parse could not be found.
/// </returns>
public virtual Parse[] FullParse(Parse flatParse, int parseCount)
{
if (CreateDerivationString)
{
flatParse.InitializeDerivationBuffer();
}
var oldDerivationsHeap = new Util.SortedSet<Parse>();
var parses = new Util.SortedSet<Parse>();
int derivationLength = 0;
int maxDerivationLength = 2 * flatParse.ChildCount + 3;
oldDerivationsHeap.Add(flatParse);
Parse guessParse = null;
double bestComplete = - 100000; //approximating -infinity/0 in ln domain
var buildProbabilities = new double[this.buildModel.OutcomeCount];
var checkProbabilities = new double[this.checkModel.OutcomeCount];
while (parses.Count < m && derivationLength < maxDerivationLength)
{
var newDerivationsHeap = new Util.TreeSet<Parse>();
if (oldDerivationsHeap.Count > 0)
{
int derivationsProcessed = 0;
foreach (Parse currentParse in oldDerivationsHeap)
{
derivationsProcessed++;
if (derivationsProcessed >= k)
{
break;
}
// for each derivation
//Parse currentParse = (Parse) pi.Current;
if (currentParse.Probability < bestComplete) //this parse and the ones which follow will never win, stop advancing.
{
break;
}
if (guessParse == null && derivationLength == 2)
{
guessParse = currentParse;
}
Parse[] newDerivations = null;
if (0 == derivationLength)
{
newDerivations = AdvanceTags(currentParse);
}
else if (derivationLength == 1)
{
if (newDerivationsHeap.Count < k)
{
newDerivations = AdvanceChunks(currentParse, bestComplete);
}
else
{
newDerivations = AdvanceChunks(currentParse, newDerivationsHeap.Last().Probability);
}
}
else
{ // derivationLength > 1
newDerivations = AdvanceParses(currentParse, q, buildProbabilities, checkProbabilities);
}
if (newDerivations != null)
{
for (int currentDerivation = 0, derivationCount = newDerivations.Length; currentDerivation < derivationCount; currentDerivation++)
{
if (newDerivations[currentDerivation].IsComplete)
{
AdvanceTop(newDerivations[currentDerivation], buildProbabilities, checkProbabilities);
if (newDerivations[currentDerivation].Probability > bestComplete)
{
bestComplete = newDerivations[currentDerivation].Probability;
}
parses.Add(newDerivations[currentDerivation]);
}
else
{
newDerivationsHeap.Add(newDerivations[currentDerivation]);
}
}
//RN added sort
newDerivationsHeap.Sort();
}
else
{
//Console.Error.WriteLine("Couldn't advance parse " + derivationLength + " stage " + derivationsProcessed + "!\n");
}
}
derivationLength++;
oldDerivationsHeap = newDerivationsHeap;
}
else
{
break;
}
}
//RN added sort
parses.Sort();
if (parses.Count == 0)
{
//Console.Error.WriteLine("Couldn't find parse for: " + flatParse);
//oFullParse = (Parse) mOldDerivationsHeap.First();
return new Parse[] {guessParse};
}
else if (parseCount == 1)
{
//RN added parent adjustment
Parse topParse = parses.First();
topParse.UpdateChildParents();
return new Parse[] {topParse};
}
else
{
var topParses = new List<Parse>(parseCount);
while(!parses.IsEmpty() && topParses.Count < parseCount)
{
Parse topParse = parses.First();
//RN added parent adjustment
topParse.UpdateChildParents();
topParses.Add(topParse);
parses.Remove(topParse);
}
return topParses.ToArray();
}
}
private void AdvanceTop(Parse inputParse, double[] buildProbabilities, double[] checkProbabilities)
{
buildModel.Evaluate(buildContextGenerator.GetContext(inputParse.GetChildren(), 0), buildProbabilities);
inputParse.AddProbability(Math.Log(buildProbabilities[topStartIndex]));
checkModel.Evaluate(checkContextGenerator.GetContext(inputParse.GetChildren(), TopNode, 0, 0), checkProbabilities);
inputParse.AddProbability(Math.Log(checkProbabilities[completeIndex]));
inputParse.Type = TopNode;
}
///<summary>
///Advances the specified parse and returns the an array advanced parses whose probability accounts for
///more than the speicficed amount of probability mass, Q.
///</summary>
///<param name="inputParse">
///The parse to advance.
///</param>
///<param name="qParam">
///The amount of probability mass that should be accounted for by the advanced parses.
///</param>
private Parse[] AdvanceParses(Parse inputParse, double qParam, double[] buildProbabilities, double[] checkProbabilities)
{
double qOpp = 1 - qParam;
Parse lastStartNode = null; // The closest previous node which has been labeled as a start node.
int lastStartIndex = -1; // The index of the closest previous node which has been labeled as a start node.
string lastStartType = null; // The type of the closest previous node which has been labeled as a start node.
int advanceNodeIndex; // The index of the node which will be labeled in this iteration of advancing the parse.
Parse advanceNode = null; // The node which will be labeled in this iteration of advancing the parse.
Parse[] children = inputParse.GetChildren();
int nodeCount = children.Length;
//determines which node needs to be labeled and prior labels.
for (advanceNodeIndex = 0; advanceNodeIndex < nodeCount; advanceNodeIndex++)
{
advanceNode = children[advanceNodeIndex];
if (advanceNode.Label == null)
{
break;
}
else if (startTypeMap.ContainsKey(advanceNode.Label))
{
lastStartType = startTypeMap[advanceNode.Label];
lastStartNode = advanceNode;
lastStartIndex = advanceNodeIndex;
}
}
var newParsesList = new List<Parse>(buildModel.OutcomeCount);
//call build
buildModel.Evaluate(buildContextGenerator.GetContext(children, advanceNodeIndex), buildProbabilities);
double buildProbabilitiesSum = 0;
while (buildProbabilitiesSum < qParam)
{
// The largest unadvanced labeling.
int highestBuildProbabilityIndex = 0;
for (int probabilityIndex = 1; probabilityIndex < buildProbabilities.Length; probabilityIndex++)
{ //for each build outcome
if (buildProbabilities[probabilityIndex] > buildProbabilities[highestBuildProbabilityIndex])
{
highestBuildProbabilityIndex = probabilityIndex;
}
}
if (buildProbabilities[highestBuildProbabilityIndex] == 0)
{
break;
}
double highestBuildProbability = buildProbabilities[highestBuildProbabilityIndex];
buildProbabilities[highestBuildProbabilityIndex] = 0; //zero out so new max can be found
buildProbabilitiesSum += highestBuildProbability;
string tag = buildModel.GetOutcomeName(highestBuildProbabilityIndex);
//System.Console.Out.WriteLine("trying " + tag + " " + buildProbabilitiesSum + " lst=" + lst);
if (highestBuildProbabilityIndex == topStartIndex)
{ // can't have top until complete
continue;
}
//System.Console.Error.WriteLine(probabilityIndex + " " + tag + " " + highestBuildProbability);
if (startTypeMap.ContainsKey(tag))
{ //update last start
lastStartIndex = advanceNodeIndex;
lastStartNode = advanceNode;
lastStartType = startTypeMap[tag];
}
else if (continueTypeMap.ContainsKey(tag))
{
if (lastStartNode == null || lastStartType != continueTypeMap[tag])
{
continue; //Cont must match previous start or continue
}
}
var newParse1 = (Parse) inputParse.Clone(); //clone parse
if (CreateDerivationString)
{
newParse1.AppendDerivationBuffer(highestBuildProbabilityIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
newParse1.AppendDerivationBuffer("-");
}
newParse1.SetChild(advanceNodeIndex, tag); //replace constituent labeled
newParse1.AddProbability(Math.Log(highestBuildProbability));
//check
checkModel.Evaluate(checkContextGenerator.GetContext(newParse1.GetChildren(), lastStartType, lastStartIndex, advanceNodeIndex), checkProbabilities);
//System.Console.Out.WriteLine("check " + mCheckProbabilities[mCompleteIndex] + " " + mCheckProbabilities[mIncompleteIndex]);
Parse newParse2 = newParse1;
if (checkProbabilities[completeIndex] > qOpp)
{ //make sure a reduce is likely
newParse2 = (Parse) newParse1.Clone();
if (CreateDerivationString)
{
newParse2.AppendDerivationBuffer("1");
newParse2.AppendDerivationBuffer(".");
}
newParse2.AddProbability(System.Math.Log(checkProbabilities[1]));
var constituent = new Parse[advanceNodeIndex - lastStartIndex + 1];
bool isFlat = true;
//first
constituent[0] = lastStartNode;
if (constituent[0].Type != constituent[0].Head.Type)
{
isFlat = false;
}
//last
constituent[advanceNodeIndex - lastStartIndex] = advanceNode;
if (isFlat && constituent[advanceNodeIndex - lastStartIndex].Type != constituent[advanceNodeIndex - lastStartIndex].Head.Type)
{
isFlat = false;
}
//middle
for (int constituentIndex = 1; constituentIndex < advanceNodeIndex - lastStartIndex; constituentIndex++)
{
constituent[constituentIndex] = children[constituentIndex + lastStartIndex];
if (isFlat && constituent[constituentIndex].Type != constituent[constituentIndex].Head.Type)
{
isFlat = false;
}
}
if (!isFlat)
{ //flat chunks are done by chunker
newParse2.Insert(new Parse(inputParse.Text, new Util.Span(lastStartNode.Span.Start, advanceNode.Span.End), lastStartType, checkProbabilities[1], headRules.GetHead(constituent, lastStartType)));
newParsesList.Add(newParse2);
}
}
if (checkProbabilities[incompleteIndex] > qOpp)
{ //make sure a shift is likely
if (CreateDerivationString)
{
newParse1.AppendDerivationBuffer("0");
newParse1.AppendDerivationBuffer(".");
}
if (advanceNodeIndex != nodeCount - 1)
{ //can't shift last element
newParse1.AddProbability(Math.Log(checkProbabilities[0]));
newParsesList.Add(newParse1);
}
}
}
Parse[] newParses = newParsesList.ToArray();
return newParses;
}
///<summary>
///Returns the top chunk sequences for the specified parse.
///</summary>
///<param name="inputParse">
///A pos-tag assigned parse.
///</param>
/// <param name="minChunkScore">
/// the minimum probability for an allowed chunk sequence.
/// </param>
///<returns>
///The top chunk assignments to the specified parse.
///</returns>
private Parse[] AdvanceChunks(Parse inputParse, double minChunkScore)
{
// chunk
Parse[] children = inputParse.GetChildren();
var words = new string[children.Length];
var parseTags = new string[words.Length];
var probabilities = new double[words.Length];
for (int childParseIndex = 0, childParseCount = children.Length; childParseIndex < childParseCount; childParseIndex++)
{
Parse currentChildParse = children[childParseIndex];
words[childParseIndex] = currentChildParse.Head.ToString();
parseTags[childParseIndex] = currentChildParse.Type;
}
//System.Console.Error.WriteLine("adjusted min chunk score = " + (minChunkScore - inputParse.Probability));
Util.Sequence[] chunkerSequences = basalChunker.TopKSequences(words, parseTags, minChunkScore - inputParse.Probability);
var newParses = new Parse[chunkerSequences.Length];
for (int sequenceIndex = 0, sequenceCount = chunkerSequences.Length; sequenceIndex < sequenceCount; sequenceIndex++)
{
newParses[sequenceIndex] = (Parse) inputParse.Clone(); //copies top level
if (CreateDerivationString)
{
newParses[sequenceIndex].AppendDerivationBuffer(sequenceIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
newParses[sequenceIndex].AppendDerivationBuffer(".");
}
string[] tags = chunkerSequences[sequenceIndex].Outcomes.ToArray();
chunkerSequences[sequenceIndex].GetProbabilities(probabilities);
int start = -1;
int end = 0;
string type = null;
//System.Console.Error.Write("sequence " + sequenceIndex + " ");
for (int tagIndex = 0; tagIndex <= tags.Length; tagIndex++)
{
//if (tagIndex != tags.Length)
//{
// System.Console.Error.WriteLine(words[tagIndex] + " " + parseTags[tagIndex] + " " + tags[tagIndex] + " " + probabilities[tagIndex]);
//}
if (tagIndex != tags.Length)
{
newParses[sequenceIndex].AddProbability(Math.Log(probabilities[tagIndex]));
}
if (tagIndex != tags.Length && tags[tagIndex].StartsWith(ContinuePrefix))
{ // if continue just update end chunking tag don't use mContinueTypeMap
end = tagIndex;
}
else
{ //make previous constituent if it exists
if (type != null)
{
//System.Console.Error.WriteLine("inserting tag " + tags[tagIndex]);
Parse startParse = children[start];
Parse endParse = children[end];
//System.Console.Error.WriteLine("Putting " + type + " at " + start + "," + end + " " + newParses[sequenceIndex].Probability);
var consitituents = new Parse[end - start + 1];
consitituents[0] = startParse;
//consitituents[0].Label = "Start-" + type;
if (end - start != 0)
{
consitituents[end - start] = endParse;
//consitituents[end - start].Label = "Cont-" + type;
for (int constituentIndex = 1; constituentIndex < end - start; constituentIndex++)
{
consitituents[constituentIndex] = children[constituentIndex + start];
//consitituents[constituentIndex].Label = "Cont-" + type;
}
}
newParses[sequenceIndex].Insert(new Parse(startParse.Text, new Util.Span(startParse.Span.Start, endParse.Span.End), type, 1, headRules.GetHead(consitituents, type)));
}
if (tagIndex != tags.Length)
{ //update for new constituent
if (tags[tagIndex].StartsWith(StartPrefix))
{ // don't use mStartTypeMap these are chunk tags
type = tags[tagIndex].Substring(StartPrefix.Length);
start = tagIndex;
end = tagIndex;
}
else
{ // other
type = null;
}
}
}
}
//newParses[sequenceIndex].Show();
//System.Console.Out.WriteLine();
}
return newParses;
}
///<summary>
///Advances the parse by assigning it POS tags and returns multiple tag sequences.
///</summary>
///<param name="inputParse">
///The parse to be tagged.
///</param>
///<returns>
///Parses with different pos-tag sequence assignments.
///</returns>
private Parse[] AdvanceTags(Parse inputParse)
{
Parse[] children = inputParse.GetChildren();
var words = children.Select(ch => ch.ToString()).ToArray();
var probabilities = new double[words.Length];
Util.Sequence[] tagSequences = posTagger.TopKSequences(words);
if (tagSequences.Length == 0)
{
Console.Error.WriteLine("no tag sequence");
}
var newParses = new Parse[tagSequences.Length];
for (int tagSequenceIndex = 0; tagSequenceIndex < tagSequences.Length; tagSequenceIndex++)
{
string[] tags = tagSequences[tagSequenceIndex].Outcomes.ToArray();
tagSequences[tagSequenceIndex].GetProbabilities(probabilities);
newParses[tagSequenceIndex] = (Parse) inputParse.Clone(); //copies top level
if (CreateDerivationString)
{
newParses[tagSequenceIndex].AppendDerivationBuffer(tagSequenceIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
newParses[tagSequenceIndex].AppendDerivationBuffer(".");
}
for (int wordIndex = 0; wordIndex < words.Length; wordIndex++)
{
Parse wordParse = children[wordIndex];
//System.Console.Error.WriteLine("inserting tag " + tags[wordIndex]);
double wordProbability = probabilities[wordIndex];
newParses[tagSequenceIndex].Insert(new Parse(wordParse.Text, wordParse.Span, tags[wordIndex], wordProbability));
newParses[tagSequenceIndex].AddProbability(Math.Log(wordProbability));
//newParses[tagSequenceIndex].Show();
}
}
return newParses;
}
// Utilities -----------------------
private static SharpEntropy.GisModel Train(SharpEntropy.ITrainingEventReader eventStream, int iterations, int cut)
{
var trainer = new SharpEntropy.GisTrainer();
trainer.TrainModel(iterations, new SharpEntropy.TwoPassDataIndexer(eventStream, cut));
return new SharpEntropy.GisModel(trainer);
}
public static SharpEntropy.GisModel TrainModel(string trainingFile, EventType modelType, string headRulesFile)
{
return TrainModel(trainingFile, modelType, headRulesFile, 100, 5);
}
public static SharpEntropy.GisModel TrainModel(string trainingFile, EventType modelType, string headRulesFile, int iterations, int cutoff)
{
var rules = new EnglishHeadRules(headRulesFile);
using (var fileStream = new FileStream(trainingFile, FileMode.Open)){
using (var reader = new StreamReader(fileStream, Encoding.UTF7)){
var dataReader = new PlainTextByLineDataReader(reader);
var eventReader = new ParserEventReader(dataReader, rules, modelType);
return Train(eventReader, iterations, cutoff);
}
}
}
}
}
| |
/*
* DeliveryHub
*
* DeliveryHub API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace IO.Swagger.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration
{
/// <summary>
/// Initializes a new instance of the Configuration class with different settings
/// </summary>
/// <param name="apiClient">Api client</param>
/// <param name="defaultHeader">Dictionary of default HTTP header</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="accessToken">accessToken</param>
/// <param name="apiKey">Dictionary of API key</param>
/// <param name="apiKeyPrefix">Dictionary of API key prefix</param>
/// <param name="tempFolderPath">Temp folder path</param>
/// <param name="dateTimeFormat">DateTime format string</param>
/// <param name="timeout">HTTP connection timeout (in milliseconds)</param>
/// <param name="userAgent">HTTP user agent</param>
public Configuration(ApiClient apiClient = null,
Dictionary<String, String> defaultHeader = null,
string username = null,
string password = null,
string accessToken = null,
Dictionary<String, String> apiKey = null,
Dictionary<String, String> apiKeyPrefix = null,
string tempFolderPath = null,
string dateTimeFormat = null,
int timeout = 100000,
string userAgent = "Swagger-Codegen/1.0.0/csharp"
)
{
setApiClientUsingDefault(apiClient);
Username = username;
Password = password;
AccessToken = accessToken;
UserAgent = userAgent;
if (defaultHeader != null)
DefaultHeader = defaultHeader;
if (apiKey != null)
ApiKey = apiKey;
if (apiKeyPrefix != null)
ApiKeyPrefix = apiKeyPrefix;
TempFolderPath = tempFolderPath;
DateTimeFormat = dateTimeFormat;
Timeout = timeout;
}
/// <summary>
/// Initializes a new instance of the Configuration class.
/// </summary>
/// <param name="apiClient">Api client.</param>
public Configuration(ApiClient apiClient)
{
setApiClientUsingDefault(apiClient);
}
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0.0";
/// <summary>
/// Gets or sets the default Configuration.
/// </summary>
/// <value>Configuration.</value>
public static Configuration Default = new Configuration();
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
int status = (int) response.StatusCode;
if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content);
if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage);
return null;
};
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
/// <value>Timeout.</value>
public int Timeout
{
get { return ApiClient.RestClient.Timeout; }
set
{
if (ApiClient != null)
ApiClient.RestClient.Timeout = value;
}
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance.
/// </summary>
/// <param name="apiClient">An instance of ApiClient.</param>
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{
if (apiClient == null)
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = new ApiClient();
ApiClient = Default != null ? Default.ApiClient : new ApiClient();
}
else
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = apiClient;
ApiClient = apiClient;
}
}
private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the default header.
/// </summary>
public Dictionary<String, String> DefaultHeader
{
get { return _defaultHeaderMap; }
set
{
_defaultHeaderMap = value;
}
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value)
{
_defaultHeaderMap[key] = value;
}
/// <summary>
/// Add Api Key Header.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
/// <returns></returns>
public void AddApiKey(string key, string value)
{
ApiKey[key] = value;
}
/// <summary>
/// Sets the API key prefix.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
public void AddApiKeyPrefix(string key, string value)
{
ApiKeyPrefix[key] = value;
}
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public String UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public String Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public String Password { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
/// </summary>
/// <value>The access token.</value>
public String AccessToken { get; set; }
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public Dictionary<String, String> ApiKey = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>();
/// <summary>
/// Get the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
return apiKeyPrefix + " " + apiKeyValue;
else
return apiKeyValue;
}
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public String TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (String.IsNullOrEmpty(value))
{
_tempFolderPath = value;
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
Directory.CreateDirectory(value);
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
_tempFolderPath = value;
else
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
private const string ISO8601_DATETIME_FORMAT = "o";
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
/// <summary>
/// Gets or sets the the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public String DateTimeFormat
{
get
{
return _dateTimeFormat;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static String ToDebugReport()
{
String report = "C# SDK (IO.Swagger) Debug Report:\n";
report += " OS: " + Environment.OSVersion + "\n";
report += " .NET Framework Version: " + Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString() + "\n";
report += " Version of the API: 1.0.0\n";
report += " SDK Package Version: 1.0.0\n";
return report;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects user account data (creating new users, looking up existing
/// users) to the SimianGrid backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianUserAccountServiceConnector")]
public class SimianUserAccountServiceConnector : IUserAccountService, ISharedRegionModule
{
private const double CACHE_EXPIRATION_SECONDS = 120.0;
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_serverUrl = String.Empty;
private ExpiringCache<UUID, UserAccount> m_accountCache = new ExpiringCache<UUID,UserAccount>();
private bool m_Enabled;
#region ISharedRegionModule
public Type ReplaceableInterface { get { return null; } }
public void RegionLoaded(Scene scene) { }
public void PostInitialise() { }
public void Close() { }
public SimianUserAccountServiceConnector() { }
public string Name { get { return "SimianUserAccountServiceConnector"; } }
public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IUserAccountService>(this); } }
public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserAccountService>(this); } }
#endregion ISharedRegionModule
public SimianUserAccountServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("UserAccountServices", "");
if (name == Name)
CommonInit(source);
}
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["UserAccountService"];
if (gridConfig != null)
{
string serviceUrl = gridConfig.GetString("UserAccountServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl;
m_Enabled = true;
}
}
if (String.IsNullOrEmpty(m_serverUrl))
m_log.Info("[SIMIAN ACCOUNT CONNECTOR]: No UserAccountServerURI specified, disabling connector");
}
public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "Name", firstName + ' ' + lastName }
};
return GetUser(requestArgs);
}
public UserAccount GetUserAccount(UUID scopeID, string email)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "Email", email }
};
return GetUser(requestArgs);
}
public UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
// Cache check
UserAccount account;
if (m_accountCache.TryGetValue(userID, out account))
return account;
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
account = GetUser(requestArgs);
if (account == null)
{
// Store null responses too, to avoid repeated lookups for missing accounts
m_accountCache.AddOrUpdate(userID, null, CACHE_EXPIRATION_SECONDS);
}
return account;
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
List<UserAccount> accounts = new List<UserAccount>();
// m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Searching for user accounts with name query " + query);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUsers" },
{ "NameQuery", query }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDArray array = response["Users"] as OSDArray;
if (array != null && array.Count > 0)
{
for (int i = 0; i < array.Count; i++)
{
UserAccount account = ResponseToUserAccount(array[i] as OSDMap);
if (account != null)
accounts.Add(account);
}
}
else
{
m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
}
}
else
{
m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to search for account data by name " + query);
}
return accounts;
}
public bool StoreUserAccount(UserAccount data)
{
// m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUser" },
{ "UserID", data.PrincipalID.ToString() },
{ "Name", data.Name },
{ "Email", data.Email },
{ "AccessLevel", data.UserLevel.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name);
requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", data.PrincipalID.ToString() },
{ "CreationDate", data.Created.ToString() },
{ "UserFlags", data.UserFlags.ToString() },
{ "UserTitle", data.UserTitle }
};
response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (success)
{
// Cache the user account info
m_accountCache.AddOrUpdate(data.PrincipalID, data, CACHE_EXPIRATION_SECONDS);
}
else
{
m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString());
}
return success;
}
else
{
m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString());
}
return false;
}
/// <summary>
/// Helper method for the various ways of retrieving a user account
/// </summary>
/// <param name="requestArgs">Service query parameters</param>
/// <returns>A UserAccount object on success, null on failure</returns>
private UserAccount GetUser(NameValueCollection requestArgs)
{
string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)";
// m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue);
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap user = response["User"] as OSDMap;
if (user != null)
return ResponseToUserAccount(user);
else
m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
}
else
{
m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue);
}
return null;
}
/// <summary>
/// Convert a User object in LLSD format to a UserAccount
/// </summary>
/// <param name="response">LLSD containing user account data</param>
/// <returns>A UserAccount object on success, null on failure</returns>
private UserAccount ResponseToUserAccount(OSDMap response)
{
if (response == null)
return null;
UserAccount account = new UserAccount();
account.PrincipalID = response["UserID"].AsUUID();
account.Created = response["CreationDate"].AsInteger();
account.Email = response["Email"].AsString();
account.ServiceURLs = new Dictionary<string, object>(0);
account.UserFlags = response["UserFlags"].AsInteger();
account.UserLevel = response["AccessLevel"].AsInteger();
account.UserTitle = response["UserTitle"].AsString();
account.LocalToGrid = true;
if (response.ContainsKey("LocalToGrid"))
account.LocalToGrid = (response["LocalToGrid"].AsString() == "true" ? true : false);
GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName);
// Cache the user account info
m_accountCache.AddOrUpdate(account.PrincipalID, account, CACHE_EXPIRATION_SECONDS);
return account;
}
/// <summary>
/// Convert a name with a single space in it to a first and last name
/// </summary>
/// <param name="name">A full name such as "John Doe"</param>
/// <param name="firstName">First name</param>
/// <param name="lastName">Last name (surname)</param>
private static void GetFirstLastName(string name, out string firstName, out string lastName)
{
if (String.IsNullOrEmpty(name))
{
firstName = String.Empty;
lastName = String.Empty;
}
else
{
string[] names = name.Split(' ');
if (names.Length == 2)
{
firstName = names[0];
lastName = names[1];
}
else
{
firstName = String.Empty;
lastName = name;
}
}
}
}
}
| |
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 Framework.WebServices.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
function GuiEditorUndoManager::onAddUndo( %this )
{
GuiEditor.updateUndoMenu();
}
//-----------------------------------------------------------------------------------------
// Undo adding an object
function UndoActionAddObject::create( %set, %trash, %treeView )
{
%act = UndoActionAddDelete::create( UndoActionAddObject, %set, %trash, %treeView );
%act.actionName = "Add Objects";
return %act;
}
function UndoActionAddObject::undo(%this)
{
%this.trashObjects();
}
function UndoActionAddObject::redo(%this)
{
%this.restoreObjects();
}
//-----------------------------------------------------------------------------------------
// Undo Deleting an object
function UndoActionDeleteObject::create( %set, %trash, %treeView )
{
%act = UndoActionAddDelete::create( UndoActionDeleteObject, %set, %trash, %treeView, true );
%act.designatedDeleter = true;
%act.actionName = "Delete Objects";
return %act;
}
function UndoActionDeleteObject::undo( %this )
{
%this.restoreObjects();
}
function UndoActionDeleteObject::redo( %this )
{
%this.trashObjects();
}
//-----------------------------------------------------------------------------------------
// Behavior common to Add and Delete UndoActions
function UndoActionAddDelete::create( %class, %set, %trash, %treeView, %clearNames )
{
// record objects
// record parents
// record trash
// return new subclass %class of UndoActionAddDelete
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%act = new UndoScriptAction() { class = %class; superclass = UndoActionAddDelete; };
// Restore the instant group.
popInstantGroup();
for(%i = 0; %i < %set.getCount(); %i++)
{
%obj = %set.getObject(%i);
%act.object[ %i ] = %obj.getId();
%act.parent[ %i ] = %obj.getParent();
%act.objectName[ %i ] = %obj.name;
// Clear object name so we don't get name clashes with the trash.
if( %clearNames )
%obj.name = "";
}
%act.objCount = %set.getCount();
%act.trash = %trash;
%act.tree = %treeView;
return %act;
}
function UndoActionAddDelete::trashObjects(%this)
{
// Move objects to trash.
for( %i = 0; %i < %this.objCount; %i ++ )
{
%object = %this.object[ %i ];
%this.trash.add( %object );
%object.name = "";
}
// Note that we're responsible for deleting those objects we've moved to the trash.
%this.designatedDeleter = true;
// Update the tree view.
if( isObject( %this.tree ) )
%this.tree.update();
}
function UndoActionAddDelete::restoreObjects(%this)
{
// Move objects to saved parent and restore names.
for( %i = 0; %i < %this.objCount; %i ++ )
{
%object = %this.object[ %i ];
%object.name = %this.objectName[ %i ];
%this.parent[ %i ].add( %object );
}
// Note that we no longer own the objects, and should not delete them when we're deleted.
%this.designatedDeleter = false;
// Update the tree view.
if( isObject( %this.tree ) )
%this.tree.update();
}
function UndoActionAddObject::onRemove(%this)
{
// if this undoAction owns objects in the trash, delete them.
if( !%this.designatedDeleter)
return;
for( %i = 0; %i < %this.objCount; %i ++)
%this.object[ %i ].delete();
}
//-----------------------------------------------------------------------------------------
// Undo grouping/ungrouping of controls.
function GuiEditorGroupUngroupAction::groupControls( %this )
{
for( %i = 0; %i < %this.count; %i ++ )
%this.group[ %i ].group();
GuiEditorTreeView.update();
}
function GuiEditorGroupUngroupAction::ungroupControls( %this )
{
for( %i = 0; %i < %this.count; %i ++ )
%this.group[ %i ].ungroup();
GuiEditorTreeView.update();
}
function GuiEditorGroupUngroupAction::onRemove( %this )
{
for( %i = 0; %i < %this.count; %i ++ )
if( isObject( %this.group[ %i ] ) )
%this.group[ %i ].delete();
}
function GuiEditorGroupAction::create( %set, %root )
{
// Create action object.
pushInstantGroup();
%action = new UndoScriptAction()
{
actionName = "Group";
className = GuiEditorGroupAction;
superClass = GuiEditorGroupUngroupAction;
count = 1;
group[ 0 ] = new ScriptObject()
{
className = GuiEditorGroup;
count = %set.getCount();
groupParent = GuiEditor.getCurrentAddSet();
};
};
popInstantGroup();
// Add objects from set to group.
%group = %action.group[ 0 ];
%num = %set.getCount();
for( %i = 0; %i < %num; %i ++ )
{
%ctrl = %set.getObject( %i );
if( %ctrl != %root )
%group.ctrl[ %i ] = %ctrl;
}
return %action;
}
function GuiEditorGroupAction::undo( %this )
{
%this.ungroupControls();
}
function GuiEditorGroupAction::redo( %this )
{
%this.groupControls();
}
function GuiEditorUngroupAction::create( %set, %root )
{
// Create action object.
pushInstantGroup();
%action = new UndoScriptAction()
{
actionName = "Ungroup";
className = GuiEditorUngroupAction;
superClass = GuiEditorGroupUngroupAction;
};
// Add groups from set to action.
%groupCount = 0;
%numInSet = %set.getCount();
for( %i = 0; %i < %numInSet; %i ++ )
{
%obj = %set.getObject( %i );
if( %obj.getClassName() $= "GuiControl" && %obj != %root )
{
// Create group object.
%group = new ScriptObject()
{
className = GuiEditorGroup;
count = %obj.getCount();
groupParent = %obj.parentGroup;
groupObject = %obj;
};
%action.group[ %groupCount ] = %group;
%groupCount ++;
// Add controls.
%numControls = %obj.getCount();
for( %j = 0; %j < %numControls; %j ++ )
%group.ctrl[ %j ] = %obj.getObject( %j );
}
}
popInstantGroup();
%action.count = %groupCount;
return %action;
}
function GuiEditorUngroupAction::undo( %this )
{
%this.groupControls();
}
function GuiEditorUngroupAction::redo( %this )
{
%this.ungroupControls();
}
//------------------------------------------------------------------------------
// Undo Any State Change.
function GenericUndoAction::create()
{
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%act = new UndoScriptAction() { class = GenericUndoAction; };
%act.actionName = "Edit Objects";
// Restore the instant group.
popInstantGroup();
return %act;
}
function GenericUndoAction::watch(%this, %object)
{
// make sure we're working with the object id, because it cannot change.
%object = %object.getId();
%fieldCount = %object.getFieldCount();
%dynFieldCount = %object.getDynamicFieldCount();
// inspect all the fields on the object, including dyanamic ones.
// record field names and values.
for(%i = 0; %i < %fieldCount; %i++)
{
%field = %object.getField(%i);
%this.fieldNames[%object] = %this.fieldNames[%object] SPC %field;
%this.fieldValues[%object, %field] = %object.getFieldValue(%field);
}
for(%i = 0; %i < %dynFieldCount; %i++)
{
%field = %object.getDynamicField(%i);
%this.fieldNames[%object] = %this.fieldNames[%object] SPC %field;
%this.fieldValues[%object, %field] = %object.getFieldValue(%field);
}
// clean spurious spaces from the field name list
%this.fieldNames[%object] = trim(%this.fieldNames[%object]);
// record that we know this object
%this.objectIds[%object] = 1;
%this.objectIdList = %this.objectIdList SPC %object;
}
function GenericUndoAction::learn(%this, %object)
{
// make sure we're working with the object id, because it cannot change.
%object = %object.getId();
%fieldCount = %object.getFieldCount();
%dynFieldCount = %object.getDynamicFieldCount();
// inspect all the fields on the object, including dyanamic ones.
// record field names and values.
for(%i = 0; %i < %fieldCount; %i++)
{
%field = %object.getField(%i);
%this.newFieldNames[%object] = %this.newFieldNames[%object] SPC %field;
%this.newFieldValues[%object, %field] = %object.getFieldValue(%field);
}
for(%i = 0; %i < %dynFieldCount; %i++)
{
%field = %object.getDynamicField(%i);
%this.newFieldNames[%object] = %this.newFieldNames[%object] SPC %field;
%this.newFieldValues[%object, %field] = %object.getFieldValue(%field);
}
// trim
%this.newFieldNames[%object] = trim(%this.newFieldNames[%object]);
// look for differences
//----------------------------------------------------------------------
%diffs = false;
%newFieldNames = %this.newFieldNames[%object];
%oldFieldNames = %this.fieldNames[%object];
%numNewFields = getWordCount(%newFieldNames);
%numOldFields = getWordCount(%oldFieldNames);
// compare the old field list to the new field list.
// if a field is on the old list that isn't on the new list,
// add it to the newNullFields list.
for(%i = 0; %i < %numOldFields; %i++)
{
%field = getWord(%oldFieldNames, %i);
%newVal = %this.newFieldValues[%object, %field];
%oldVal = %this.fieldValues[%object, %field];
if(%newVal !$= %oldVal)
{
%diffs = true;
if(%newVal $= "")
{
%newNullFields = %newNullFields SPC %field;
}
}
}
// scan the new field list
// add missing fields to the oldNullFields list
for(%i = 0; %i < %numNewFields; %i++)
{
%field = getWord(%newFieldNames, %i);
%newVal = %this.newFieldValues[%object, %field];
%oldVal = %this.fieldValues[%object, %field];
if(%newVal !$= %oldVal)
{
%diffs = true;
if(%oldVal $= "")
{
%oldNullFields = %oldNullFields SPC %field;
}
}
}
%this.newNullFields[%object] = trim(%newNullFields);
%this.oldNullFields[%object] = trim(%oldNullFields);
return %diffs;
}
function GenericUndoAction::watchSet(%this, %set)
{
// scan the set
// this.watch each object.
%setcount = %set.getCount();
%i = 0;
for(; %i < %setcount; %i++)
{
%object = %set.getObject(%i);
%this.watch(%object);
}
}
function GenericUndoAction::learnSet(%this, %set)
{
// scan the set
// this.learn any objects that we have a this.objectIds[] entry for.
%diffs = false;
for(%i = 0; %i < %set.getCount(); %i++)
{
%object = %set.getObject(%i).getId();
if(%this.objectIds[%object] != 1)
continue;
if(%this.learn(%object))
%diffs = true;
}
return %diffs;
}
function GenericUndoAction::undo(%this)
{
// set the objects to the old values
// scan through our objects
%objectList = %this.objectIdList;
for(%i = 0; %i < getWordCount(%objectList); %i++)
{
%object = getWord(%objectList, %i);
// scan through the old extant fields
%fieldNames = %this.fieldNames[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, %this.fieldValues[%object, %field]);
}
// null out the fields in the null list
%fieldNames = %this.oldNullFields[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, "");
}
}
// update the tree view
if(isObject(%this.tree))
%this.tree.update();
}
function GenericUndoAction::redo(%this)
{
// set the objects to the new values
// set the objects to the new values
// scan through our objects
%objectList = %this.objectIdList;
for(%i = 0; %i < getWordCount(%objectList); %i++)
{
%object = getWord(%objectList, %i);
// scan through the new extant fields
%fieldNames = %this.newFieldNames[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, %this.newFieldValues[%object, %field]);
}
// null out the fields in the null list
%fieldNames = %this.newNullFields[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, "");
}
}
// update the tree view
if(isObject(%this.tree))
%this.tree.update();
}
//-----------------------------------------------------------------------------------------
// Gui Editor Undo hooks from code
function GuiEditor::onPreEdit(%this, %selection)
{
if ( isObject(%this.pendingGenericUndoAction) )
{
error("Error: attempting to create two generic undo actions at once in the same editor!");
return;
}
//echo("pre edit");
%act = GenericUndoAction::create();
%act.watchSet(%selection);
%act.tree = GuiEditorTreeView;
%this.pendingGenericUndoAction = %act;
%this.updateUndoMenu();
}
function GuiEditor::onPostEdit(%this, %selection)
{
if(!isObject(%this.pendingGenericUndoAction))
error("Error: attempting to complete a GenericUndoAction that hasn't been started!");
%act = %this.pendingGenericUndoAction;
%this.pendingGenericUndoAction = "";
%diffs = %act.learnSet(%selection);
if(%diffs)
{
//echo("adding generic undoaction to undo manager");
//%act.dump();
%act.addToManager(%this.getUndoManager());
}
else
{
//echo("deleting empty generic undoaction");
%act.delete();
}
%this.updateUndoMenu();
}
function GuiEditor::onPreSelectionNudged(%this, %selection)
{
%this.onPreEdit(%selection);
%this.pendingGenericUndoAction.actionName = "Nudge";
}
function GuiEditor::onPostSelectionNudged(%this, %selection)
{
%this.onPostEdit(%selection);
}
function GuiEditor::onAddNewCtrl(%this, %ctrl)
{
%set = new SimSet();
%set.add(%ctrl);
%act = UndoActionAddObject::create(%set, %this.getTrash(), GuiEditorTreeView);
%set.delete();
%act.addToManager(%this.getUndoManager());
%this.updateUndoMenu();
//GuiEditorInspectFields.update(0);
}
function GuiEditor::onAddNewCtrlSet(%this, %selection)
{
%act = UndoActionAddObject::create(%selection, %this.getTrash(), GuiEditorTreeView);
%act.addToManager(%this.getUndoManager());
%this.updateUndoMenu();
}
function GuiEditor::onTrashSelection(%this, %selection)
{
%act = UndoActionDeleteObject::create(%selection, %this.getTrash(), GuiEditorTreeView);
%act.addToManager(%this.getUndoManager());
%this.updateUndoMenu();
}
function GuiEditor::onControlInspectPreApply(%this, %object)
{
%set = new SimSet();
%set.add(%object);
%this.onPreEdit(%set);
%this.pendingGenericUndoAction.actionName = "Change Properties";
%set.delete();
}
function GuiEditor::onControlInspectPostApply(%this, %object)
{
%set = new SimSet();
%set.add(%object);
%this.onPostEdit(%set);
%set.delete();
GuiEditorTreeView.update();
}
function GuiEditor::onFitIntoParents( %this )
{
%selected = %this.getSelection();
//TODO
}
| |
using sly.buildresult;
using sly.lexer;
using Xunit;
namespace ParserTests.comments
{
public enum MultiLineCommentsToken
{
[Lexeme(GenericToken.Int)] INT = 1,
[Lexeme(GenericToken.Double)] DOUBLE = 2,
[Lexeme(GenericToken.Identifier)] ID = 3,
[MultiLineComment("/*", "*/")] COMMENT = 4
}
public class MultiLineCommentsTest
{
[Fact]
public void NotEndingMultiComment()
{
var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>());
Assert.False(lexerRes.IsError);
var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>;
var dump = lexer.ToString();
var code = @"1
2 /* not ending
comment";
var r = lexer.Tokenize(code);
Assert.True(r.IsOk);
var tokens = r.Tokens;
Assert.Equal(4, tokens.Count);
var token1 = tokens[0];
var token2 = tokens[1];
var token3 = tokens[2];
Assert.Equal(MultiLineCommentsToken.INT, token1.TokenID);
Assert.Equal("1", token1.Value);
Assert.Equal(0, token1.Position.Line);
Assert.Equal(0, token1.Position.Column);
Assert.Equal(MultiLineCommentsToken.INT, token2.TokenID);
Assert.Equal("2", token2.Value);
Assert.Equal(1, token2.Position.Line);
Assert.Equal(0, token2.Position.Column);
Assert.Equal(MultiLineCommentsToken.COMMENT, token3.TokenID);
Assert.Equal(@" not ending
comment", token3.Value);
Assert.Equal(1, token3.Position.Line);
Assert.Equal(2, token3.Position.Column);
}
[Fact]
public void TestGenericMultiLineComment()
{
var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>());
Assert.False(lexerRes.IsError);
var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>;
var dump = lexer.ToString();
var code = @"1
2 /* multi line
comment on 2 lines */ 3.0";
var r = lexer.Tokenize(code);
Assert.True(r.IsOk);
var tokens = r.Tokens;
Assert.Equal(5, tokens.Count);
var intToken1 = tokens[0];
var intToken2 = tokens[1];
var multiLineCommentToken = tokens[2];
var doubleToken = tokens[3];
Assert.Equal(MultiLineCommentsToken.INT, intToken1.TokenID);
Assert.Equal("1", intToken1.Value);
Assert.Equal(0, intToken1.Position.Line);
Assert.Equal(0, intToken1.Position.Column);
Assert.Equal(MultiLineCommentsToken.INT, intToken2.TokenID);
Assert.Equal("2", intToken2.Value);
Assert.Equal(1, intToken2.Position.Line);
Assert.Equal(0, intToken2.Position.Column);
Assert.Equal(MultiLineCommentsToken.COMMENT, multiLineCommentToken.TokenID);
Assert.Equal(@" multi line
comment on 2 lines ", multiLineCommentToken.Value);
Assert.Equal(1, multiLineCommentToken.Position.Line);
Assert.Equal(2, multiLineCommentToken.Position.Column);
Assert.Equal(MultiLineCommentsToken.DOUBLE, doubleToken.TokenID);
Assert.Equal("3.0", doubleToken.Value);
Assert.Equal(2, doubleToken.Position.Line);
Assert.Equal(22, doubleToken.Position.Column);
}
[Fact]
public void TestGenericSingleLineComment()
{
var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>());
Assert.False(lexerRes.IsError);
var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>;
var dump = lexer.ToString();
var r = lexer.Tokenize(@"1
2 // single line comment
3.0");
Assert.True(r.IsError);
Assert.Equal('/', r.Error.UnexpectedChar);
}
[Fact]
public void TestInnerMultiComment()
{
var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>());
Assert.False(lexerRes.IsError);
var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>;
var dump = lexer.ToString();
var code = @"1
2 /* inner */ 3
4
";
var r = lexer.Tokenize(code);
Assert.True(r.IsOk);
var tokens = r.Tokens;
Assert.Equal(6, tokens.Count);
var token1 = tokens[0];
var token2 = tokens[1];
var token3 = tokens[2];
var token4 = tokens[3];
var token5 = tokens[4];
Assert.Equal(MultiLineCommentsToken.INT, token1.TokenID);
Assert.Equal("1", token1.Value);
Assert.Equal(0, token1.Position.Line);
Assert.Equal(0, token1.Position.Column);
Assert.Equal(MultiLineCommentsToken.INT, token2.TokenID);
Assert.Equal("2", token2.Value);
Assert.Equal(1, token2.Position.Line);
Assert.Equal(0, token2.Position.Column);
Assert.Equal(MultiLineCommentsToken.COMMENT, token3.TokenID);
Assert.Equal(@" inner ", token3.Value);
Assert.Equal(1, token3.Position.Line);
Assert.Equal(2, token3.Position.Column);
Assert.Equal(MultiLineCommentsToken.INT, token4.TokenID);
Assert.Equal("3", token4.Value);
Assert.Equal(1, token4.Position.Line);
Assert.Equal(14, token4.Position.Column);
Assert.Equal(MultiLineCommentsToken.INT, token5.TokenID);
Assert.Equal("4", token5.Value);
Assert.Equal(2, token5.Position.Line);
Assert.Equal(0, token5.Position.Column);
}
[Fact]
public void TestMixedEOLComment()
{
var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>());
Assert.False(lexerRes.IsError);
var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>;
var dump = lexer.ToString();
var code = "1\n2\r\n/* multi line \rcomment on 2 lines */ 3.0";
var r = lexer.Tokenize(code);
Assert.True(r.IsOk);
var tokens = r.Tokens;
Assert.Equal(5, tokens.Count);
var token1 = tokens[0];
var token2 = tokens[1];
var token3 = tokens[2];
var token4 = tokens[3];
Assert.Equal(MultiLineCommentsToken.INT, token1.TokenID);
Assert.Equal("1", token1.Value);
Assert.Equal(0, token1.Position.Line);
Assert.Equal(0, token1.Position.Column);
Assert.Equal(MultiLineCommentsToken.INT, token2.TokenID);
Assert.Equal("2", token2.Value);
Assert.Equal(1, token2.Position.Line);
Assert.Equal(0, token2.Position.Column);
Assert.Equal(MultiLineCommentsToken.COMMENT, token3.TokenID);
Assert.Equal(" multi line \rcomment on 2 lines ", token3.Value);
Assert.Equal(2, token3.Position.Line);
Assert.Equal(0, token3.Position.Column);
Assert.Equal(MultiLineCommentsToken.DOUBLE, token4.TokenID);
Assert.Equal("3.0", token4.Value);
Assert.Equal(3, token4.Position.Line);
Assert.Equal(22, token4.Position.Column);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System;
using System.Diagnostics.Contracts;
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
[Serializable]
internal class EncoderNLS : Encoder, ISerializable
{
// Need a place for the last left over character, most of our encodings use this
internal char charLeftOver;
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_charsUsed;
#region Serialization
// Constructor called by serialization. called during deserialization.
internal EncoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
}
// ISerializable implementation. called during serialization.
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeEncoder(info);
info.AddValue("encoding", this.m_encoding);
info.AddValue("charLeftOver", this.charLeftOver);
info.SetType(typeof(Encoding.DefaultEncoder));
}
#endregion Serialization
internal EncoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.EncoderFallback;
this.Reset();
}
// This one is used when deserializing (like UTF7Encoding.Encoder)
internal EncoderNLS()
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
this.charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException( "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version
int result = -1;
fixed (char* pChars = chars)
{
result = GetByteCount(pChars + index, count, flush);
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException( "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetByteCount(chars, count, this);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
int byteCount = bytes.Length - byteIndex;
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
fixed (char* pChars = chars)
{
fixed (byte* pBytes = bytes)
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
}
}
}
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
[System.Security.SecurityCritical] // auto-generated
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_charsUsed = 0;
// Do conversion
bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = this.m_charsUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (charsUsed == charCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public Encoding Encoding
{
get
{
return m_encoding;
}
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our encoder?
internal virtual bool HasState
{
get
{
return (this.charLeftOver != (char)0);
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapCompareAttrNames.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.Ldap.Utilclass;
namespace Novell.Directory.Ldap
{
/// <summary> Compares Ldap entries based on attribute name.
///
/// An object of this class defines ordering when sorting LdapEntries,
/// usually from search results. When using this Comparator, LdapEntry objects
/// are sorted by the attribute names(s) passed in on the
/// constructor, in ascending or descending order. The object is typically
/// supplied to an implementation of the collection interfaces such as
/// java.util.TreeSet which performs sorting.
///
/// Comparison is performed via locale-sensitive Java String comparison,
/// which may not correspond to the Ldap ordering rules by which an Ldap server
/// would sort them.
///
/// </summary>
public class LdapCompareAttrNames : System.Collections.IComparer
{
private void InitBlock()
{
// location = Locale.getDefault();
location=System.Globalization.CultureInfo.CurrentCulture;
collator = System.Globalization.CultureInfo.CurrentCulture.CompareInfo;
}
/// <summary> Returns the locale to be used for sorting, if a locale has been
/// specified.
///
/// If locale is null, a basic String.compareTo method is used for
/// collation. If non-null, a locale-specific collation is used.
///
/// </summary>
/// <returns> The locale if one has been specified
/// </returns>
/// <summary> Sets the locale to be used for sorting.
///
/// </summary>
/// <param name="locale"> The locale to be used for sorting.
/// </param>
virtual public System.Globalization.CultureInfo Locale
{
get
{
//currently supports only English local.
return location;
}
set
{
collator = value.CompareInfo;
location = value;
}
}
private System.String[] sortByNames; //names to to sort by.
private bool[] sortAscending; //true if sorting ascending
private System.Globalization.CultureInfo location;
private System.Globalization.CompareInfo collator;
/// <summary> Constructs an object that sorts results by a single attribute, in
/// ascending order.
///
/// </summary>
/// <param name="attrName"> Name of an attribute by which to sort.
///
/// </param>
public LdapCompareAttrNames(System.String attrName)
{
InitBlock();
sortByNames = new System.String[1];
sortByNames[0] = attrName;
sortAscending = new bool[1];
sortAscending[0] = true;
}
/// <summary> Constructs an object that sorts results by a single attribute, in
/// either ascending or descending order.
///
/// </summary>
/// <param name="attrName"> Name of an attribute to sort by.
///
/// </param>
/// <param name="ascendingFlag"> True specifies ascending order; false specifies
/// descending order.
/// </param>
public LdapCompareAttrNames(System.String attrName, bool ascendingFlag)
{
InitBlock();
sortByNames = new System.String[1];
sortByNames[0] = attrName;
sortAscending = new bool[1];
sortAscending[0] = ascendingFlag;
}
/// <summary> Constructs an object that sorts by one or more attributes, in the
/// order provided, in ascending order.
///
/// Note: Novell eDirectory allows sorting by one attribute only. The
/// direcctory server must also be configured to index the specified
/// attribute.
///
/// </summary>
/// <param name="attrNames"> Array of names of attributes to sort by.
///
/// </param>
public LdapCompareAttrNames(System.String[] attrNames)
{
InitBlock();
sortByNames = new System.String[attrNames.Length];
sortAscending = new bool[attrNames.Length];
for (int i = 0; i < attrNames.Length; i++)
{
sortByNames[i] = attrNames[i];
sortAscending[i] = true;
}
}
/// <summary> Constructs an object that sorts by one or more attributes, in the
/// order provided, in either ascending or descending order for each
/// attribute.
///
/// Note: Novell eDirectory supports only ascending sort order (A,B,C ...)
/// and allows sorting only by one attribute. The directory server must be
/// configured to index this attribute.
///
/// </summary>
/// <param name="attrNames"> Array of names of attributes to sort by.
///
/// </param>
/// <param name="ascendingFlags"> Array of flags, one for each attrName, where
/// true specifies ascending order and false specifies
/// descending order. An LdapException is thrown if
/// the length of ascendingFlags is not greater than
/// or equal to the length of attrNames.
///
/// </param>
/// <exception> LdapException A general exception which includes an error
/// message and an Ldap error code.
///
/// </exception>
public LdapCompareAttrNames(System.String[] attrNames, bool[] ascendingFlags)
{
InitBlock();
if (attrNames.Length != ascendingFlags.Length)
{
throw new LdapException(ExceptionMessages.UNEQUAL_LENGTHS, LdapException.INAPPROPRIATE_MATCHING, (System.String) null);
//"Length of attribute Name array does not equal length of Flags array"
}
sortByNames = new System.String[attrNames.Length];
sortAscending = new bool[ascendingFlags.Length];
for (int i = 0; i < attrNames.Length; i++)
{
sortByNames[i] = attrNames[i];
sortAscending[i] = ascendingFlags[i];
}
}
/// <summary> Compares the the attributes of the first LdapEntry to the second.
/// Only the values of the attributes named at the construction of this
/// object will be compared. Multi-valued attributes compare on the first
/// value only.
///
/// </summary>
/// <param name="object1"> Target entry for comparison.
///
/// </param>
/// <param name="object2"> Entry to be compared to.
///
/// </param>
/// <returns> Negative value if the first entry is less than the second and
/// positive if the first is greater than the second. Zero is returned if all
/// attributes to be compared are the same.
/// </returns>
public virtual int Compare(System.Object object1, System.Object object2)
{
LdapEntry entry1 = (LdapEntry) object1;
LdapEntry entry2 = (LdapEntry) object2;
LdapAttribute one, two;
System.String[] first; //multivalued attributes are ignored.
System.String[] second; //we just use the first element
int compare, i = 0;
if (collator == null)
{
//using default locale
collator = System.Globalization.CultureInfo.CurrentCulture.CompareInfo;
}
do
{
//while first and second are equal
one = entry1.getAttribute(sortByNames[i]);
two = entry2.getAttribute(sortByNames[i]);
if ((one != null) && (two != null))
{
first = one.StringValueArray;
second = two.StringValueArray;
compare = collator.Compare(first[0], second[0]);
}
//We could also use the other multivalued attributes to break ties.
//one of the entries was null
else
{
if (one != null)
compare = - 1;
//one is greater than two
else if (two != null)
compare = 1;
//one is lesser than two
else
compare = 0; //tie - break it with the next attribute name
}
i++;
}
while ((compare == 0) && (i < sortByNames.Length));
if (sortAscending[i - 1])
{
// return the normal ascending comparison.
return compare;
}
else
{
// negate the comparison for a descending comparison.
return - compare;
}
}
/// <summary> Determines if this comparator is equal to the comparator passed in.
///
/// This will return true if the comparator is an instance of
/// LdapCompareAttrNames and compares the same attributes names in the same
/// order.
///
/// </summary>
/// <returns> true the comparators are equal
/// </returns>
public override bool Equals(System.Object comparator)
{
if (!(comparator is LdapCompareAttrNames))
{
return false;
}
LdapCompareAttrNames comp = (LdapCompareAttrNames) comparator;
// Test to see if the attribute to compare are the same length
if ((comp.sortByNames.Length != this.sortByNames.Length) || (comp.sortAscending.Length != this.sortAscending.Length))
{
return false;
}
// Test to see if the attribute names and sorting orders are the same.
for (int i = 0; i < this.sortByNames.Length; i++)
{
if (comp.sortAscending[i] != this.sortAscending[i])
return false;
if (!comp.sortByNames[i].ToUpper().Equals(this.sortByNames[i].ToUpper()))
return false;
}
return true;
}
}
}
| |
//#define ASTAR_NO_JSON
using System;
using UnityEngine;
using Pathfinding.Serialization.JsonFx;
#if NETFX_CORE
using System.Reflection;
#endif
using System.Collections.Generic;
#if NETFX_CORE && !UNITY_EDITOR
//using MarkerMetro.Unity.WinLegacy.IO;
//using MarkerMetro.Unity.WinLegacy.Reflection;
#endif
#if !ASTAR_NO_JSON
namespace Pathfinding.Serialization
{
public class UnityObjectConverter : JsonConverter {
public override bool CanConvert (Type type) {
#if NETFX_CORE
return typeof(UnityEngine.Object).GetTypeInfo().IsAssignableFrom (type.GetTypeInfo());
#else
return typeof(UnityEngine.Object).IsAssignableFrom (type);
#endif
}
public override object ReadJson ( Type objectType, Dictionary<string,object> values) {
if (values == null) return null;
//int instanceID = (int)values["InstanceID"];
string name = (string)values["Name"];
if ( name == null ) return null;
string typename = (string)values["Type"];
Type type = Type.GetType (typename);
if (System.Type.Equals (type, null)) {
Debug.LogError ("Could not find type '"+typename+"'. Cannot deserialize Unity reference");
return null;
}
if (values.ContainsKey ("GUID")) {
string guid = (string)values["GUID"];
UnityReferenceHelper[] helpers = UnityEngine.Object.FindObjectsOfType(typeof(UnityReferenceHelper)) as UnityReferenceHelper[];
for (int i=0;i<helpers.Length;i++) {
if (helpers[i].GetGUID () == guid) {
if (System.Type.Equals ( type, typeof(GameObject) )) {
return helpers[i].gameObject;
} else {
return helpers[i].GetComponent (type);
}
}
}
}
//Try to load from resources
UnityEngine.Object[] objs = Resources.LoadAll (name,type);
for (int i=0;i<objs.Length;i++) {
if (objs[i].name == name || objs.Length == 1) {
return objs[i];
}
}
return null;
}
public override Dictionary<string,object> WriteJson (Type type, object value) {
UnityEngine.Object obj = (UnityEngine.Object)value;
Dictionary<string, object> dict = new Dictionary<string, object>();
if ( value == null ) {
dict.Add ("Name",null);
return dict;
}
dict.Add ("Name",obj.name);
dict.Add ("Type",obj.GetType().AssemblyQualifiedName);
//Write scene path if the object is a Component or GameObject
Component component = value as Component;
GameObject go = value as GameObject;
if (component != null || go != null) {
if (component != null && go == null) {
go = component.gameObject;
}
UnityReferenceHelper helper = go.GetComponent<UnityReferenceHelper>();
if (helper == null) {
Debug.Log ("Adding UnityReferenceHelper to Unity Reference '"+obj.name+"'");
helper = go.AddComponent<UnityReferenceHelper>();
}
//Make sure it has a unique GUID
helper.Reset ();
dict.Add ("GUID",helper.GetGUID ());
}
return dict;
}
}
public class GuidConverter : JsonConverter {
public override bool CanConvert (Type type) {
return System.Type.Equals ( type, typeof(Pathfinding.Util.Guid) );
}
public override object ReadJson ( Type objectType, Dictionary<string,object> values) {
string s = (string)values["value"];
return new Pathfinding.Util.Guid(s);
}
public override Dictionary<string,object> WriteJson (Type type, object value) {
Pathfinding.Util.Guid m = (Pathfinding.Util.Guid)value;
return new Dictionary<string, object>() {{"value",m.ToString()}};
}
}
public class MatrixConverter : JsonConverter {
public override bool CanConvert (Type type) {
return System.Type.Equals ( type, typeof(Matrix4x4) );
}
public override object ReadJson ( Type objectType, Dictionary<string,object> values) {
Matrix4x4 m = new Matrix4x4();
Array arr = (Array)values["values"];
if (arr.Length != 16) {
Debug.LogError ("Number of elements in matrix was not 16 (got "+arr.Length+")");
return m;
}
for (int i=0;i<16;i++) m[i] = System.Convert.ToSingle (arr.GetValue(new int[] {i}));
return m;
}
/** Just a temporary array of 16 floats.
* Stores the elements of the matrices temporarily */
float[] values = new float[16];
public override Dictionary<string,object> WriteJson (Type type, object value) {
Matrix4x4 m = (Matrix4x4)value;
for (int i=0;i<values.Length;i++) values[i] = m[i];
return new Dictionary<string, object>() {
{"values",values}
};
}
}
public class BoundsConverter : JsonConverter {
public override bool CanConvert (Type type) {
return System.Type.Equals ( type, typeof(Bounds) );
}
public override object ReadJson ( Type objectType, Dictionary<string,object> values) {
Bounds b = new Bounds();
b.center = new Vector3( CastFloat(values["cx"]),CastFloat(values["cy"]),CastFloat(values["cz"]));
b.extents = new Vector3(CastFloat(values["ex"]),CastFloat(values["ey"]),CastFloat(values["ez"]));
return b;
}
public override Dictionary<string,object> WriteJson (Type type, object value) {
Bounds b = (Bounds)value;
return new Dictionary<string, object>() {
{"cx",b.center.x},
{"cy",b.center.y},
{"cz",b.center.z},
{"ex",b.extents.x},
{"ey",b.extents.y},
{"ez",b.extents.z}
};
}
}
public class LayerMaskConverter : JsonConverter {
public override bool CanConvert (Type type) {
return System.Type.Equals ( type, typeof(LayerMask) );
}
public override object ReadJson (Type type, Dictionary<string,object> values) {
return (LayerMask)(int)values["value"];
}
public override Dictionary<string,object> WriteJson (Type type, object value) {
return new Dictionary<string, object>() {{"value",((LayerMask)value).value}};
}
}
public class VectorConverter : JsonConverter
{
public override bool CanConvert (Type type) {
return System.Type.Equals ( type, typeof(Vector2) ) || System.Type.Equals ( type, typeof(Vector3) )||System.Type.Equals ( type, typeof(Vector4) );
}
public override object ReadJson (Type type, Dictionary<string,object> values) {
if (System.Type.Equals ( type, typeof(Vector2) )) {
return new Vector2(CastFloat(values["x"]),CastFloat(values["y"]));
} else if (System.Type.Equals ( type, typeof(Vector3) )) {
return new Vector3(CastFloat(values["x"]),CastFloat(values["y"]),CastFloat(values["z"]));
} else if (System.Type.Equals ( type, typeof(Vector4) )) {
return new Vector4(CastFloat(values["x"]),CastFloat(values["y"]),CastFloat(values["z"]),CastFloat(values["w"]));
} else {
throw new System.NotImplementedException ("Can only read Vector2,3,4. Not objects of type "+type);
}
}
public override Dictionary<string,object> WriteJson (Type type, object value) {
if (System.Type.Equals ( type, typeof(Vector2) )) {
Vector2 v = (Vector2)value;
return new Dictionary<string, object>() {
{"x",v.x},
{"y",v.y}
};
} else if (System.Type.Equals ( type, typeof(Vector3) )) {
Vector3 v = (Vector3)value;
return new Dictionary<string, object>() {
{"x",v.x},
{"y",v.y},
{"z",v.z}
};
} else if (System.Type.Equals ( type, typeof(Vector4) )) {
Vector4 v = (Vector4)value;
return new Dictionary<string, object>() {
{"x",v.x},
{"y",v.y},
{"z",v.z},
{"w",v.w}
};
}
throw new System.NotImplementedException ("Can only write Vector2,3,4. Not objects of type "+type);
}
}
/** Enables json serialization of dictionaries with integer keys.
*/
public class IntKeyDictionaryConverter : JsonConverter {
public override bool CanConvert (Type type) {
return ( System.Type.Equals (type, typeof(Dictionary<int,int>)) || System.Type.Equals (type, typeof(SortedDictionary<int,int>)) );
}
public override object ReadJson (Type type, Dictionary<string,object> values) {
Dictionary<int, int> holder = new Dictionary<int, int>();
foreach ( KeyValuePair<string, object> val in values )
{
holder.Add( System.Convert.ToInt32(val.Key), System.Convert.ToInt32(val.Value) );
}
return holder;
}
public override Dictionary<string,object> WriteJson (Type type, object value ) {
Dictionary<string, object> holder = new Dictionary<string, object>();
Dictionary<int, int> d = (Dictionary<int,int>)value;
foreach ( KeyValuePair<int, int> val in d )
{
holder.Add( val.Key.ToString(), val.Value );
}
return holder;
}
}
}
#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.Avatar.Chat;
namespace OpenSim.Region.OptionalModules.Avatar.Concierge
{
public class ConciergeModule : ChatModule, ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int DEBUG_CHANNEL = 2147483647;
private List<IScene> m_scenes = new List<IScene>();
private List<IScene> m_conciergedScenes = new List<IScene>();
private bool m_replacingChatModule = false;
private IConfig m_config;
private string m_whoami = "conferencier";
private Regex m_regions = null;
private string m_welcomes = null;
private int m_conciergeChannel = 42;
private string m_announceEntering = "{0} enters {1} (now {2} visitors in this region)";
private string m_announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)";
private string m_xmlRpcPassword = String.Empty;
private string m_brokerURI = String.Empty;
private int m_brokerUpdateTimeout = 300;
internal object m_syncy = new object();
internal bool m_enabled = false;
#region ISharedRegionModule Members
public override void Initialise(IConfigSource config)
{
m_config = config.Configs["Concierge"];
if (null == m_config)
return;
if (!m_config.GetBoolean("enabled", false))
return;
m_enabled = true;
// check whether ChatModule has been disabled: if yes,
// then we'll "stand in"
try
{
if (config.Configs["Chat"] == null)
{
// if Chat module has not been configured it's
// enabled by default, so we are not going to
// replace it.
m_replacingChatModule = false;
}
else
{
m_replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true);
}
}
catch (Exception)
{
m_replacingChatModule = false;
}
m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing");
// take note of concierge channel and of identity
m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel);
m_whoami = m_config.GetString("whoami", "conferencier");
m_welcomes = m_config.GetString("welcomes", m_welcomes);
m_announceEntering = m_config.GetString("announce_entering", m_announceEntering);
m_announceLeaving = m_config.GetString("announce_leaving", m_announceLeaving);
m_xmlRpcPassword = m_config.GetString("password", m_xmlRpcPassword);
m_brokerURI = m_config.GetString("broker", m_brokerURI);
m_brokerUpdateTimeout = m_config.GetInt("broker_timeout", m_brokerUpdateTimeout);
m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami);
// calculate regions Regex
if (m_regions == null)
{
string regions = m_config.GetString("regions", String.Empty);
if (!String.IsNullOrEmpty(regions))
{
m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
}
}
public override void AddRegion(Scene scene)
{
if (!m_enabled) return;
MainServer.Instance.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false);
lock (m_syncy)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
if (m_regions == null || m_regions.IsMatch(scene.RegionInfo.RegionName))
m_conciergedScenes.Add(scene);
// subscribe to NewClient events
scene.EventManager.OnNewClient += OnNewClient;
// subscribe to *Chat events
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
if (!m_replacingChatModule)
scene.EventManager.OnChatFromClient += OnChatFromClient;
scene.EventManager.OnChatBroadcast += OnChatBroadcast;
// subscribe to agent change events
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
}
}
m_log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName);
}
public override void RemoveRegion(Scene scene)
{
if (!m_enabled) return;
MainServer.Instance.RemoveXmlRPCHandler("concierge_update_welcome");
lock (m_syncy)
{
// unsubscribe from NewClient events
scene.EventManager.OnNewClient -= OnNewClient;
// unsubscribe from *Chat events
scene.EventManager.OnChatFromWorld -= OnChatFromWorld;
if (!m_replacingChatModule)
scene.EventManager.OnChatFromClient -= OnChatFromClient;
scene.EventManager.OnChatBroadcast -= OnChatBroadcast;
// unsubscribe from agent change events
scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent;
scene.EventManager.OnMakeChildAgent -= OnMakeChildAgent;
if (m_scenes.Contains(scene))
{
m_scenes.Remove(scene);
}
if (m_conciergedScenes.Contains(scene))
{
m_conciergedScenes.Remove(scene);
}
}
m_log.InfoFormat("[Concierge]: removed {0}", scene.RegionInfo.RegionName);
}
public override void PostInitialise()
{
}
public override void Close()
{
}
new public Type ReplaceableInterface
{
get { return null; }
}
public override string Name
{
get { return "ConciergeModule"; }
}
#endregion
#region ISimChat Members
public override void OnChatBroadcast(Object sender, OSChatMessage c)
{
if (m_replacingChatModule)
{
// distribute chat message to each and every avatar in
// the region
base.OnChatBroadcast(sender, c);
}
// TODO: capture logic
return;
}
public override void OnChatFromClient(Object sender, OSChatMessage c)
{
if (m_replacingChatModule)
{
// replacing ChatModule: need to redistribute
// ChatFromClient to interested subscribers
c = FixPositionOfChatMessage(c);
Scene scene = (Scene)c.Scene;
scene.EventManager.TriggerOnChatFromClient(sender, c);
if (m_conciergedScenes.Contains(c.Scene))
{
// when we are replacing ChatModule, we treat
// OnChatFromClient like OnChatBroadcast for
// concierged regions, effectively extending the
// range of chat to cover the whole
// region. however, we don't do this for whisper
// (got to have some privacy)
if (c.Type != ChatTypeEnum.Whisper)
{
base.OnChatBroadcast(sender, c);
return;
}
}
// redistribution will be done by base class
base.OnChatFromClient(sender, c);
}
// TODO: capture chat
return;
}
public override void OnChatFromWorld(Object sender, OSChatMessage c)
{
if (m_replacingChatModule)
{
if (m_conciergedScenes.Contains(c.Scene))
{
// when we are replacing ChatModule, we treat
// OnChatFromClient like OnChatBroadcast for
// concierged regions, effectively extending the
// range of chat to cover the whole
// region. however, we don't do this for whisper
// (got to have some privacy)
if (c.Type != ChatTypeEnum.Whisper)
{
base.OnChatBroadcast(sender, c);
return;
}
}
base.OnChatFromWorld(sender, c);
}
return;
}
#endregion
public override void OnNewClient(IClientAPI client)
{
client.OnLogout += OnClientLoggedOut;
if (m_replacingChatModule)
client.OnChatFromClient += OnChatFromClient;
}
public void OnClientLoggedOut(IClientAPI client)
{
client.OnLogout -= OnClientLoggedOut;
client.OnConnectionClosed -= OnClientLoggedOut;
if (m_conciergedScenes.Contains(client.Scene))
{
Scene scene = client.Scene as Scene;
m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName);
AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount()));
UpdateBroker(scene);
}
}
public void OnMakeRootAgent(ScenePresence agent)
{
if (m_conciergedScenes.Contains(agent.Scene))
{
Scene scene = agent.Scene;
m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName);
WelcomeAvatar(agent, scene);
AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name,
scene.RegionInfo.RegionName, scene.GetRootAgentCount()));
UpdateBroker(scene);
}
}
public void OnMakeChildAgent(ScenePresence agent)
{
if (m_conciergedScenes.Contains(agent.Scene))
{
Scene scene = agent.Scene;
m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName);
AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name,
scene.RegionInfo.RegionName, scene.GetRootAgentCount()));
UpdateBroker(scene);
}
}
internal class BrokerState
{
public string Uri;
public string Payload;
public HttpWebRequest Poster;
public Timer Timer;
public BrokerState(string uri, string payload, HttpWebRequest poster)
{
Uri = uri;
Payload = payload;
Poster = poster;
}
}
protected void UpdateBroker(Scene scene)
{
if (String.IsNullOrEmpty(m_brokerURI))
return;
string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID);
// create XML sniplet
StringBuilder list = new StringBuilder();
list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n",
scene.GetRootAgentCount(), scene.RegionInfo.RegionName,
scene.RegionInfo.RegionID,
DateTime.UtcNow.ToString("s")));
scene.ForEachScenePresence(delegate(ScenePresence sp)
{
if (!sp.IsChildAgent)
{
list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID));
list.Append("</avatars>");
}
});
string payload = list.ToString();
// post via REST to broker
HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest;
updatePost.Method = "POST";
updatePost.ContentType = "text/xml";
updatePost.ContentLength = payload.Length;
updatePost.UserAgent = "OpenSim.Concierge";
BrokerState bs = new BrokerState(uri, payload, updatePost);
bs.Timer = new Timer(delegate(object state)
{
BrokerState b = state as BrokerState;
b.Poster.Abort();
b.Timer.Dispose();
m_log.Debug("[Concierge]: async broker POST abort due to timeout");
}, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite);
try
{
updatePost.BeginGetRequestStream(UpdateBrokerSend, bs);
m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri);
}
catch (WebException we)
{
m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status);
}
}
private void UpdateBrokerSend(IAsyncResult result)
{
BrokerState bs = null;
try
{
bs = result.AsyncState as BrokerState;
string payload = bs.Payload;
HttpWebRequest updatePost = bs.Poster;
using (StreamWriter payloadStream = new StreamWriter(updatePost.EndGetRequestStream(result)))
{
payloadStream.Write(payload);
payloadStream.Close();
}
updatePost.BeginGetResponse(UpdateBrokerDone, bs);
}
catch (WebException we)
{
m_log.DebugFormat("[Concierge]: async broker POST to {0} failed: {1}", bs.Uri, we.Status);
}
catch (Exception)
{
m_log.DebugFormat("[Concierge]: async broker POST to {0} failed", bs.Uri);
}
}
private void UpdateBrokerDone(IAsyncResult result)
{
BrokerState bs = null;
try
{
bs = result.AsyncState as BrokerState;
HttpWebRequest updatePost = bs.Poster;
using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse)
{
m_log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode);
}
bs.Timer.Dispose();
}
catch (WebException we)
{
m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status);
if (null != we.Response)
{
using (HttpWebResponse resp = we.Response as HttpWebResponse)
{
m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode);
m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription);
m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server);
if (resp.ContentLength > 0)
{
StreamReader content = new StreamReader(resp.GetResponseStream());
m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd());
content.Close();
}
}
}
}
}
protected void WelcomeAvatar(ScenePresence agent, Scene scene)
{
// welcome mechanics: check whether we have a welcomes
// directory set and wether there is a region specific
// welcome file there: if yes, send it to the agent
if (!String.IsNullOrEmpty(m_welcomes))
{
string[] welcomes = new string[] {
Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName),
Path.Combine(m_welcomes, "DEFAULT")};
foreach (string welcome in welcomes)
{
if (File.Exists(welcome))
{
try
{
string[] welcomeLines = File.ReadAllLines(welcome);
foreach (string l in welcomeLines)
{
AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, m_whoami));
}
}
catch (IOException ioe)
{
m_log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}",
welcome, scene.RegionInfo.RegionName, agent.Name, ioe);
}
catch (FormatException fe)
{
m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe);
}
}
return;
}
m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName);
}
}
static private Vector3 PosOfGod = new Vector3(128, 128, 9999);
// protected void AnnounceToAgentsRegion(Scene scene, string msg)
// {
// ScenePresence agent = null;
// if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent))
// AnnounceToAgentsRegion(agent, msg);
// else
// m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name);
// }
protected void AnnounceToAgentsRegion(IScene scene, string msg)
{
OSChatMessage c = new OSChatMessage();
c.Message = msg;
c.Type = ChatTypeEnum.Say;
c.Channel = 0;
c.Position = PosOfGod;
c.From = m_whoami;
c.Sender = null;
c.SenderUUID = UUID.Zero;
c.Scene = scene;
if (scene is Scene)
(scene as Scene).EventManager.TriggerOnChatBroadcast(this, c);
}
protected void AnnounceToAgent(ScenePresence agent, string msg)
{
OSChatMessage c = new OSChatMessage();
c.Message = msg;
c.Type = ChatTypeEnum.Say;
c.Channel = 0;
c.Position = PosOfGod;
c.From = m_whoami;
c.Sender = null;
c.SenderUUID = UUID.Zero;
c.Scene = agent.Scene;
agent.ControllingClient.SendChatMessage(msg, (byte) ChatTypeEnum.Say, PosOfGod, m_whoami, UUID.Zero,
(byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully);
}
private static void checkStringParameters(XmlRpcRequest request, string[] param)
{
Hashtable requestData = (Hashtable) request.Params[0];
foreach (string p in param)
{
if (!requestData.Contains(p))
throw new Exception(String.Format("missing string parameter {0}", p));
if (String.IsNullOrEmpty((string)requestData[p]))
throw new Exception(String.Format("parameter {0} is empty", p));
}
}
public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[Concierge]: processing UpdateWelcome request");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
try
{
Hashtable requestData = (Hashtable)request.Params[0];
checkStringParameters(request, new string[] { "password", "region", "welcome" });
// check password
if (!String.IsNullOrEmpty(m_xmlRpcPassword) &&
(string)requestData["password"] != m_xmlRpcPassword) throw new Exception("wrong password");
if (String.IsNullOrEmpty(m_welcomes))
throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini");
string msg = (string)requestData["welcome"];
if (String.IsNullOrEmpty(msg))
throw new Exception("empty parameter \"welcome\"");
string regionName = (string)requestData["region"];
IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; });
if (scene == null)
throw new Exception(String.Format("unknown region \"{0}\"", regionName));
if (!m_conciergedScenes.Contains(scene))
throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName));
string welcome = Path.Combine(m_welcomes, regionName);
if (File.Exists(welcome))
{
m_log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome);
string welcomeBackup = String.Format("{0}~", welcome);
if (File.Exists(welcomeBackup))
File.Delete(welcomeBackup);
File.Move(welcome, welcomeBackup);
}
File.WriteAllText(welcome, msg);
responseData["success"] = "true";
response.Value = responseData;
}
catch (Exception e)
{
m_log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message);
responseData["success"] = "false";
responseData["error"] = e.Message;
response.Value = responseData;
}
m_log.Debug("[Concierge]: done processing UpdateWelcome request");
return response;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Tomato;
using Tomato.Hardware;
using System.Drawing.Drawing2D;
using System.Threading;
using Gif.Components;
using System.IO;
namespace Lettuce
{
public partial class LEM1802Window : DeviceHostForm
{
private Device[] managedDevices;
public override Device[] ManagedDevices
{
get { return managedDevices; }
}
public static List<int> AssignedKeyboards = new List<int>();
public LEM1802 Screen;
public GenericKeyboard Keyboard;
public DCPU CPU;
protected int ScreenIndex, KeyboardIndex;
protected virtual void InitClientSize()
{
this.ClientSize = new Size(LEM1802.Width * 4 + 20, LEM1802.Height * 4 + 35);
}
/// <summary>
/// Assigns a LEM to the window. If AssignKeyboard is true, it will search for a keyboard
/// in the given CPU and assign it to this window as well.
/// </summary>
public LEM1802Window(LEM1802 LEM1802, DCPU CPU, bool AssignKeyboard) : base()
{
InitializeComponent();
this.iad = new InvalidateAsyncDelegate(InvalidateAsync);
startRecordingToolStripMenuItem.Tag = false;
// Set up drawing
this.SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint | ControlStyles.Opaque, true);
// Take a screen
this.CPU = CPU;
Screen = LEM1802;
managedDevices = new Device[] { Screen };
ScreenIndex = CPU.Devices.IndexOf(Screen);
Keyboard = null;
// Take a keyboard
if (AssignKeyboard)
{
for (int i = 0; i < CPU.Devices.Count; i++)
{
if (AssignedKeyboards.Contains(i))
continue;
if (CPU.Devices[i] is GenericKeyboard)
{
Keyboard = CPU.Devices[i] as GenericKeyboard;
managedDevices = managedDevices.Concat(new Device[] { Keyboard }).ToArray();
AssignedKeyboards.Add(i);
KeyboardIndex = i;
this.detatchKeyboardToolStripMenuItem.Visible = true;
break;
}
}
}
this.KeyDown += new KeyEventHandler(LEM1802Window_KeyDown);
this.KeyUp += new KeyEventHandler(LEM1802Window_KeyUp);
if (this.Keyboard == null)
{
this.DragEnter += new DragEventHandler(LEM1802Window_DragEnter);
this.DragDrop += new DragEventHandler(LEM1802Window_DragDrop);
this.AllowDrop = true;
}
timer = new System.Threading.Timer(delegate(object o)
{
InvalidateAsync();
}, null, 16, 16); // 60 Hz
InitClientSize();
}
void LEM1802Window_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(GenericKeyboard)))
{
GenericKeyboard data = (GenericKeyboard)e.Data.GetData(typeof(GenericKeyboard));
if (Program.Windows.ContainsKey(data))
{
Program.Windows[data].Close();
Program.Windows.Remove(data);
Program.Windows.Add(data, this);
this.Keyboard = data;
this.KeyboardIndex = this.CPU.Devices.IndexOf(data);
managedDevices = managedDevices.Concat(new Device[] { Keyboard }).ToArray();
AssignedKeyboards.Add(KeyboardIndex);
this.DragEnter -= LEM1802Window_DragEnter;
this.DragDrop -= LEM1802Window_DragDrop;
this.detatchKeyboardToolStripMenuItem.Visible = true;
this.AllowDrop = false;
}
}
}
void LEM1802Window_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(GenericKeyboard)))
{
GenericKeyboard data = (GenericKeyboard)e.Data.GetData(typeof(GenericKeyboard));
e.Effect = DragDropEffects.Move;
}
}
System.Threading.Timer timer;
void LEM1802Window_KeyUp(object sender, KeyEventArgs e)
{
if (Keyboard != null)
Keyboard.KeyUp(e.KeyCode);
}
void LEM1802Window_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard != null)
Keyboard.KeyDown(e.KeyCode);
}
private delegate void InvalidateAsyncDelegate();
private InvalidateAsyncDelegate iad;
private void InvalidateAsync()
{
if (this.InvokeRequired)
{
try
{
this.Invoke(iad);
}
catch { }
}
else
{
this.Invalidate();
if(RuntimeInfo.IsLinux)
this.Update();
}
}
private Image screen;
protected override void OnPaint(PaintEventArgs e)
{
string title = "LEM1802 #" + ScreenIndex;
if (Keyboard != null)
title += ", Generic Keyboard #" + KeyboardIndex;
// Border
e.Graphics.FillRectangle(new SolidBrush(Screen.BorderColor), new Rectangle(0, 0, this.Width, this.Height));
// Title bar
e.Graphics.FillRectangle(Brushes.White, new Rectangle(0, 0, this.Width, 15));
// Devices
e.Graphics.DrawString(title, this.Font, Brushes.Black, new PointF(0, 0));
e.Graphics.DrawLine(Pens.Black, new Point(0, 15), new Point(this.Width, 15));
e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;
// Screen
screen = Screen.ScreenImage;
e.Graphics.DrawImage(screen, 10, 25, this.ClientSize.Width - 20, this.ClientSize.Height - 35);
if (CPU.IsRunning && gifEncoder != null && !gifEncoder.Finished)
{
// Update animated gif
gifEncoder.AddFrame(screen);
}
}
private void detatchKeyboardToolStripMenuItem_Click(object sender, EventArgs e)
{
Program.Windows.Remove(this.Keyboard);
GenericKeyboardWindow gkw = new GenericKeyboardWindow(this.Keyboard, this.CPU);
Program.Windows.Add(this.Keyboard, gkw);
gkw.Show();
managedDevices = managedDevices.Where(d => d != this.Keyboard).ToArray();
Keyboard = null;
AssignedKeyboards.Remove(this.KeyboardIndex);
KeyboardIndex = -1;
AllowDrop = true;
DragEnter += LEM1802Window_DragEnter;
DragDrop += LEM1802Window_DragDrop;
detatchKeyboardToolStripMenuItem.Visible = false;
}
private void takeScreenshotToolStripMenuItem_Click(object sender, EventArgs e)
{
Bitmap image = (Bitmap)Screen.ScreenImage.Clone();
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Bitmap Image (*.bmp)|*.bmp|All Files (*.*)|*.*";
if (sfd.ShowDialog() != DialogResult.OK)
return;
image.Save(sfd.FileName);
}
private DeferredGifEncoder gifEncoder;
private void startRecordingToolStripMenuItem_Click(object sender, EventArgs e)
{
if ((bool)startRecordingToolStripMenuItem.Tag)
{
// End recording
startRecordingToolStripMenuItem.Tag = false;
startRecordingToolStripMenuItem.Text = "Start Recording";
gifEncoder.FinishAsync(null);
}
else
{
// Begin recording an animated gif
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
sfd.Filter = "Animated Gif Image (*.gif)|*.gif";
if (sfd.ShowDialog() != DialogResult.OK)
return;
startRecordingToolStripMenuItem.Tag = true;
startRecordingToolStripMenuItem.Text = "Stop Recording";
AnimatedGifEncoder _gifEncoder = new AnimatedGifEncoder();
if (File.Exists(sfd.FileName))
File.Delete(sfd.FileName);
gifEncoder = new DeferredGifEncoder(_gifEncoder, sfd.FileName);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
internal sealed class SchemaElementDecl : SchemaDeclBase, IDtdAttributeListInfo
{
private readonly Dictionary<XmlQualifiedName, SchemaAttDef> _attdefs = new Dictionary<XmlQualifiedName, SchemaAttDef>();
private List<IDtdDefaultAttributeInfo> _defaultAttdefs;
private bool _isIdDeclared;
private bool _hasNonCDataAttribute = false;
private bool _isAbstract = false;
private bool _isNillable = false;
private bool _hasRequiredAttribute = false;
private bool _isNotationDeclared;
private readonly Dictionary<XmlQualifiedName, XmlQualifiedName> _prohibitedAttributes = new Dictionary<XmlQualifiedName, XmlQualifiedName>();
private ContentValidator _contentValidator;
private XmlSchemaAnyAttribute _anyAttribute;
private XmlSchemaDerivationMethod _block;
private CompiledIdentityConstraint[] _constraints;
private XmlSchemaElement _schemaElement;
internal static readonly SchemaElementDecl Empty = new SchemaElementDecl();
//
// Constructor
//
internal SchemaElementDecl()
{
}
internal SchemaElementDecl(XmlSchemaDatatype dtype)
{
Datatype = dtype;
_contentValidator = ContentValidator.TextOnly;
}
internal SchemaElementDecl(XmlQualifiedName name, string prefix)
: base(name, prefix)
{
}
//
// Static methods
//
internal static SchemaElementDecl CreateAnyTypeElementDecl()
{
SchemaElementDecl anyTypeElementDecl = new SchemaElementDecl();
anyTypeElementDecl.Datatype = DatatypeImplementation.AnySimpleType.Datatype;
return anyTypeElementDecl;
}
//
// IDtdAttributeListInfo interface
//
#region IDtdAttributeListInfo Members
string IDtdAttributeListInfo.Prefix
{
get { return ((SchemaElementDecl)this).Prefix; }
}
string IDtdAttributeListInfo.LocalName
{
get { return ((SchemaElementDecl)this).Name.Name; }
}
bool IDtdAttributeListInfo.HasNonCDataAttributes
{
get { return _hasNonCDataAttribute; }
}
IDtdAttributeInfo IDtdAttributeListInfo.LookupAttribute(string prefix, string localName)
{
XmlQualifiedName qname = new XmlQualifiedName(localName, prefix);
SchemaAttDef attDef;
if (_attdefs.TryGetValue(qname, out attDef))
{
return attDef;
}
return null;
}
IEnumerable<IDtdDefaultAttributeInfo> IDtdAttributeListInfo.LookupDefaultAttributes()
{
return _defaultAttdefs;
}
IDtdAttributeInfo IDtdAttributeListInfo.LookupIdAttribute()
{
foreach (SchemaAttDef attDef in _attdefs.Values)
{
if (attDef.TokenizedType == XmlTokenizedType.ID)
{
return (IDtdAttributeInfo)attDef;
}
}
return null;
}
#endregion
//
// SchemaElementDecl properties
//
internal bool IsIdDeclared
{
get { return _isIdDeclared; }
set { _isIdDeclared = value; }
}
internal bool HasNonCDataAttribute
{
get { return _hasNonCDataAttribute; }
set { _hasNonCDataAttribute = value; }
}
internal SchemaElementDecl Clone()
{
return (SchemaElementDecl)MemberwiseClone();
}
internal bool IsAbstract
{
get { return _isAbstract; }
set { _isAbstract = value; }
}
internal bool IsNillable
{
get { return _isNillable; }
set { _isNillable = value; }
}
internal XmlSchemaDerivationMethod Block
{
get { return _block; }
set { _block = value; }
}
internal bool IsNotationDeclared
{
get { return _isNotationDeclared; }
set { _isNotationDeclared = value; }
}
internal bool HasDefaultAttribute
{
get { return _defaultAttdefs != null; }
}
internal bool HasRequiredAttribute
{
get { return _hasRequiredAttribute; }
set { _hasRequiredAttribute = value; }
}
internal ContentValidator ContentValidator
{
get { return _contentValidator; }
set { _contentValidator = value; }
}
internal XmlSchemaAnyAttribute AnyAttribute
{
get { return _anyAttribute; }
set { _anyAttribute = value; }
}
internal CompiledIdentityConstraint[] Constraints
{
get { return _constraints; }
set { _constraints = value; }
}
internal XmlSchemaElement SchemaElement
{
get { return _schemaElement; }
set { _schemaElement = value; }
}
// add a new SchemaAttDef to the SchemaElementDecl
internal void AddAttDef(SchemaAttDef attdef)
{
_attdefs.Add(attdef.Name, attdef);
if (attdef.Presence == SchemaDeclBase.Use.Required || attdef.Presence == SchemaDeclBase.Use.RequiredFixed)
{
_hasRequiredAttribute = true;
}
if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed)
{ //Not adding RequiredFixed here
if (_defaultAttdefs == null)
{
_defaultAttdefs = new List<IDtdDefaultAttributeInfo>();
}
_defaultAttdefs.Add(attdef);
}
}
/*
* Retrieves the attribute definition of the named attribute.
* @param name The name of the attribute.
* @return an attribute definition object; returns null if it is not found.
*/
internal SchemaAttDef GetAttDef(XmlQualifiedName qname)
{
SchemaAttDef attDef;
if (_attdefs.TryGetValue(qname, out attDef))
{
return attDef;
}
return null;
}
internal IList<IDtdDefaultAttributeInfo> DefaultAttDefs
{
get { return _defaultAttdefs; }
}
internal Dictionary<XmlQualifiedName, SchemaAttDef> AttDefs
{
get { return _attdefs; }
}
internal Dictionary<XmlQualifiedName, XmlQualifiedName> ProhibitedAttributes
{
get { return _prohibitedAttributes; }
}
internal void CheckAttributes(Hashtable presence, bool standalone)
{
foreach (SchemaAttDef attdef in _attdefs.Values)
{
if (presence[attdef.Name] == null)
{
if (attdef.Presence == SchemaDeclBase.Use.Required)
{
throw new XmlSchemaException(SR.Sch_MissRequiredAttribute, attdef.Name.ToString());
}
else if (standalone && attdef.IsDeclaredInExternal && (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed))
{
throw new XmlSchemaException(SR.Sch_StandAlone, string.Empty);
}
}
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the machinelearning-2014-12-12.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.MachineLearning
{
/// <summary>
/// Constants used for properties of type Algorithm.
/// </summary>
public class Algorithm : ConstantClass
{
/// <summary>
/// Constant Sgd for Algorithm
/// </summary>
public static readonly Algorithm Sgd = new Algorithm("sgd");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public Algorithm(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static Algorithm FindValue(string value)
{
return FindValue<Algorithm>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator Algorithm(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type BatchPredictionFilterVariable.
/// </summary>
public class BatchPredictionFilterVariable : ConstantClass
{
/// <summary>
/// Constant CreatedAt for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable CreatedAt = new BatchPredictionFilterVariable("CreatedAt");
/// <summary>
/// Constant DataSourceId for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable DataSourceId = new BatchPredictionFilterVariable("DataSourceId");
/// <summary>
/// Constant DataURI for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable DataURI = new BatchPredictionFilterVariable("DataURI");
/// <summary>
/// Constant IAMUser for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable IAMUser = new BatchPredictionFilterVariable("IAMUser");
/// <summary>
/// Constant LastUpdatedAt for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable LastUpdatedAt = new BatchPredictionFilterVariable("LastUpdatedAt");
/// <summary>
/// Constant MLModelId for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable MLModelId = new BatchPredictionFilterVariable("MLModelId");
/// <summary>
/// Constant Name for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable Name = new BatchPredictionFilterVariable("Name");
/// <summary>
/// Constant Status for BatchPredictionFilterVariable
/// </summary>
public static readonly BatchPredictionFilterVariable Status = new BatchPredictionFilterVariable("Status");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public BatchPredictionFilterVariable(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static BatchPredictionFilterVariable FindValue(string value)
{
return FindValue<BatchPredictionFilterVariable>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator BatchPredictionFilterVariable(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DataSourceFilterVariable.
/// </summary>
public class DataSourceFilterVariable : ConstantClass
{
/// <summary>
/// Constant CreatedAt for DataSourceFilterVariable
/// </summary>
public static readonly DataSourceFilterVariable CreatedAt = new DataSourceFilterVariable("CreatedAt");
/// <summary>
/// Constant DataLocationS3 for DataSourceFilterVariable
/// </summary>
public static readonly DataSourceFilterVariable DataLocationS3 = new DataSourceFilterVariable("DataLocationS3");
/// <summary>
/// Constant IAMUser for DataSourceFilterVariable
/// </summary>
public static readonly DataSourceFilterVariable IAMUser = new DataSourceFilterVariable("IAMUser");
/// <summary>
/// Constant LastUpdatedAt for DataSourceFilterVariable
/// </summary>
public static readonly DataSourceFilterVariable LastUpdatedAt = new DataSourceFilterVariable("LastUpdatedAt");
/// <summary>
/// Constant Name for DataSourceFilterVariable
/// </summary>
public static readonly DataSourceFilterVariable Name = new DataSourceFilterVariable("Name");
/// <summary>
/// Constant Status for DataSourceFilterVariable
/// </summary>
public static readonly DataSourceFilterVariable Status = new DataSourceFilterVariable("Status");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DataSourceFilterVariable(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DataSourceFilterVariable FindValue(string value)
{
return FindValue<DataSourceFilterVariable>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DataSourceFilterVariable(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DetailsAttributes.
/// </summary>
public class DetailsAttributes : ConstantClass
{
/// <summary>
/// Constant Algorithm for DetailsAttributes
/// </summary>
public static readonly DetailsAttributes Algorithm = new DetailsAttributes("Algorithm");
/// <summary>
/// Constant PredictiveModelType for DetailsAttributes
/// </summary>
public static readonly DetailsAttributes PredictiveModelType = new DetailsAttributes("PredictiveModelType");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DetailsAttributes(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DetailsAttributes FindValue(string value)
{
return FindValue<DetailsAttributes>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DetailsAttributes(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type EntityStatus.
/// </summary>
public class EntityStatus : ConstantClass
{
/// <summary>
/// Constant COMPLETED for EntityStatus
/// </summary>
public static readonly EntityStatus COMPLETED = new EntityStatus("COMPLETED");
/// <summary>
/// Constant DELETED for EntityStatus
/// </summary>
public static readonly EntityStatus DELETED = new EntityStatus("DELETED");
/// <summary>
/// Constant FAILED for EntityStatus
/// </summary>
public static readonly EntityStatus FAILED = new EntityStatus("FAILED");
/// <summary>
/// Constant INPROGRESS for EntityStatus
/// </summary>
public static readonly EntityStatus INPROGRESS = new EntityStatus("INPROGRESS");
/// <summary>
/// Constant PENDING for EntityStatus
/// </summary>
public static readonly EntityStatus PENDING = new EntityStatus("PENDING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public EntityStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static EntityStatus FindValue(string value)
{
return FindValue<EntityStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator EntityStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type EvaluationFilterVariable.
/// </summary>
public class EvaluationFilterVariable : ConstantClass
{
/// <summary>
/// Constant CreatedAt for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable CreatedAt = new EvaluationFilterVariable("CreatedAt");
/// <summary>
/// Constant DataSourceId for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable DataSourceId = new EvaluationFilterVariable("DataSourceId");
/// <summary>
/// Constant DataURI for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable DataURI = new EvaluationFilterVariable("DataURI");
/// <summary>
/// Constant IAMUser for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable IAMUser = new EvaluationFilterVariable("IAMUser");
/// <summary>
/// Constant LastUpdatedAt for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable LastUpdatedAt = new EvaluationFilterVariable("LastUpdatedAt");
/// <summary>
/// Constant MLModelId for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable MLModelId = new EvaluationFilterVariable("MLModelId");
/// <summary>
/// Constant Name for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable Name = new EvaluationFilterVariable("Name");
/// <summary>
/// Constant Status for EvaluationFilterVariable
/// </summary>
public static readonly EvaluationFilterVariable Status = new EvaluationFilterVariable("Status");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public EvaluationFilterVariable(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static EvaluationFilterVariable FindValue(string value)
{
return FindValue<EvaluationFilterVariable>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator EvaluationFilterVariable(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type MLModelFilterVariable.
/// </summary>
public class MLModelFilterVariable : ConstantClass
{
/// <summary>
/// Constant Algorithm for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable Algorithm = new MLModelFilterVariable("Algorithm");
/// <summary>
/// Constant CreatedAt for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable CreatedAt = new MLModelFilterVariable("CreatedAt");
/// <summary>
/// Constant IAMUser for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable IAMUser = new MLModelFilterVariable("IAMUser");
/// <summary>
/// Constant LastUpdatedAt for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable LastUpdatedAt = new MLModelFilterVariable("LastUpdatedAt");
/// <summary>
/// Constant MLModelType for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable MLModelType = new MLModelFilterVariable("MLModelType");
/// <summary>
/// Constant Name for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable Name = new MLModelFilterVariable("Name");
/// <summary>
/// Constant RealtimeEndpointStatus for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable RealtimeEndpointStatus = new MLModelFilterVariable("RealtimeEndpointStatus");
/// <summary>
/// Constant Status for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable Status = new MLModelFilterVariable("Status");
/// <summary>
/// Constant TrainingDataSourceId for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable TrainingDataSourceId = new MLModelFilterVariable("TrainingDataSourceId");
/// <summary>
/// Constant TrainingDataURI for MLModelFilterVariable
/// </summary>
public static readonly MLModelFilterVariable TrainingDataURI = new MLModelFilterVariable("TrainingDataURI");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public MLModelFilterVariable(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static MLModelFilterVariable FindValue(string value)
{
return FindValue<MLModelFilterVariable>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator MLModelFilterVariable(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type MLModelType.
/// </summary>
public class MLModelType : ConstantClass
{
/// <summary>
/// Constant BINARY for MLModelType
/// </summary>
public static readonly MLModelType BINARY = new MLModelType("BINARY");
/// <summary>
/// Constant MULTICLASS for MLModelType
/// </summary>
public static readonly MLModelType MULTICLASS = new MLModelType("MULTICLASS");
/// <summary>
/// Constant REGRESSION for MLModelType
/// </summary>
public static readonly MLModelType REGRESSION = new MLModelType("REGRESSION");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public MLModelType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static MLModelType FindValue(string value)
{
return FindValue<MLModelType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator MLModelType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type RealtimeEndpointStatus.
/// </summary>
public class RealtimeEndpointStatus : ConstantClass
{
/// <summary>
/// Constant FAILED for RealtimeEndpointStatus
/// </summary>
public static readonly RealtimeEndpointStatus FAILED = new RealtimeEndpointStatus("FAILED");
/// <summary>
/// Constant NONE for RealtimeEndpointStatus
/// </summary>
public static readonly RealtimeEndpointStatus NONE = new RealtimeEndpointStatus("NONE");
/// <summary>
/// Constant READY for RealtimeEndpointStatus
/// </summary>
public static readonly RealtimeEndpointStatus READY = new RealtimeEndpointStatus("READY");
/// <summary>
/// Constant UPDATING for RealtimeEndpointStatus
/// </summary>
public static readonly RealtimeEndpointStatus UPDATING = new RealtimeEndpointStatus("UPDATING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public RealtimeEndpointStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static RealtimeEndpointStatus FindValue(string value)
{
return FindValue<RealtimeEndpointStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator RealtimeEndpointStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SortOrder.
/// </summary>
public class SortOrder : ConstantClass
{
/// <summary>
/// Constant Asc for SortOrder
/// </summary>
public static readonly SortOrder Asc = new SortOrder("asc");
/// <summary>
/// Constant Dsc for SortOrder
/// </summary>
public static readonly SortOrder Dsc = new SortOrder("dsc");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SortOrder(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SortOrder FindValue(string value)
{
return FindValue<SortOrder>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SortOrder(string value)
{
return FindValue(value);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ReflectPropertyDescriptor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.ComponentModel {
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters;
using System.Security;
using System.Security.Permissions;
/// <internalonly/>
/// <devdoc>
/// <para>
/// ReflectPropertyDescriptor defines a property. Properties are the main way that a user can
/// set up the state of a component.
/// The ReflectPropertyDescriptor class takes a component class that the property lives on,
/// a property name, the type of the property, and various attributes for the
/// property.
/// For a property named XXX of type YYY, the associated component class is
/// required to implement two methods of the following
/// form:
/// </para>
/// <code>
/// public YYY GetXXX();
/// public void SetXXX(YYY value);
/// </code>
/// The component class can optionally implement two additional methods of
/// the following form:
/// <code>
/// public boolean ShouldSerializeXXX();
/// public void ResetXXX();
/// </code>
/// These methods deal with a property's default value. The ShouldSerializeXXX()
/// method returns true if the current value of the XXX property is different
/// than it's default value, so that it should be persisted out. The ResetXXX()
/// method resets the XXX property to its default value. If the ReflectPropertyDescriptor
/// includes the default value of the property (using the DefaultValueAttribute),
/// the ShouldSerializeXXX() and ResetXXX() methods are ignored.
/// If the ReflectPropertyDescriptor includes a reference to an editor
/// then that value editor will be used to
/// edit the property. Otherwise, a system-provided editor will be used.
/// Various attributes can be passed to the ReflectPropertyDescriptor, as are described in
/// Attribute.
/// ReflectPropertyDescriptors can be obtained by a user programmatically through the
/// ComponentManager.
/// </devdoc>
[HostProtection(SharedState = true)]
internal sealed class ReflectPropertyDescriptor : PropertyDescriptor {
private static readonly Type[] argsNone = new Type[0];
private static readonly object noValue = new object();
private static TraceSwitch PropDescCreateSwitch = new TraceSwitch("PropDescCreate", "ReflectPropertyDescriptor: Dump errors when creating property info");
private static TraceSwitch PropDescUsageSwitch = new TraceSwitch("PropDescUsage", "ReflectPropertyDescriptor: Debug propertydescriptor usage");
private static TraceSwitch PropDescSwitch = new TraceSwitch("PropDesc", "ReflectPropertyDescriptor: Debug property descriptor");
private static readonly int BitDefaultValueQueried = BitVector32.CreateMask();
private static readonly int BitGetQueried = BitVector32.CreateMask(BitDefaultValueQueried);
private static readonly int BitSetQueried = BitVector32.CreateMask(BitGetQueried);
private static readonly int BitShouldSerializeQueried = BitVector32.CreateMask(BitSetQueried);
private static readonly int BitResetQueried = BitVector32.CreateMask(BitShouldSerializeQueried);
private static readonly int BitChangedQueried = BitVector32.CreateMask(BitResetQueried);
private static readonly int BitIPropChangedQueried = BitVector32.CreateMask(BitChangedQueried);
private static readonly int BitReadOnlyChecked = BitVector32.CreateMask(BitIPropChangedQueried);
private static readonly int BitAmbientValueQueried = BitVector32.CreateMask(BitReadOnlyChecked);
private static readonly int BitSetOnDemand = BitVector32.CreateMask(BitAmbientValueQueried);
BitVector32 state = new BitVector32(); // Contains the state bits for this proeprty descriptor.
Type componentClass; // used to determine if we should all on us or on the designer
Type type; // the data type of the property
object defaultValue; // the default value of the property (or noValue)
object ambientValue; // the ambient value of the property (or noValue)
PropertyInfo propInfo; // the property info
MethodInfo getMethod; // the property get method
MethodInfo setMethod; // the property set method
MethodInfo shouldSerializeMethod; // the should serialize method
MethodInfo resetMethod; // the reset property method
EventDescriptor realChangedEvent; // <propertyname>Changed event handler on object
EventDescriptor realIPropChangedEvent; // INotifyPropertyChanged.PropertyChanged event handler on object
Type receiverType; // Only set if we are an extender
/// <devdoc>
/// The main constructor for ReflectPropertyDescriptors.
/// </devdoc>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type,
Attribute[] attributes)
: base(name, attributes) {
Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "Creating ReflectPropertyDescriptor for " + componentClass.FullName + "." + name);
try {
if (type == null) {
Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "type == null, name == " + name);
throw new ArgumentException(SR.GetString(SR.ErrorInvalidPropertyType, name));
}
if (componentClass == null) {
Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "componentClass == null, name == " + name);
throw new ArgumentException(SR.GetString(SR.InvalidNullArgument, "componentClass"));
}
this.type = type;
this.componentClass = componentClass;
}
catch (Exception t) {
Debug.Fail("Property '" + name + "' on component " + componentClass.FullName + " failed to init.");
Debug.Fail(t.ToString());
throw t;
}
}
/// <devdoc>
/// A constructor for ReflectPropertyDescriptors that have no attributes.
/// </devdoc>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, PropertyInfo propInfo, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) {
this.propInfo = propInfo;
this.getMethod = getMethod;
this.setMethod = setMethod;
if (getMethod != null && propInfo != null && setMethod == null )
state[BitGetQueried | BitSetOnDemand] = true;
else
state[BitGetQueried | BitSetQueried] = true;
}
/// <devdoc>
/// A constructor for ReflectPropertyDescriptors that creates an extender property.
/// </devdoc>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Type receiverType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) {
this.receiverType = receiverType;
this.getMethod = getMethod;
this.setMethod = setMethod;
state[BitGetQueried | BitSetQueried] = true;
}
/// <devdoc>
/// This constructor takes an existing ReflectPropertyDescriptor and modifies it by merging in the
/// passed-in attributes.
/// </devdoc>
public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldReflectPropertyDescriptor, Attribute[] attributes)
: base(oldReflectPropertyDescriptor, attributes) {
this.componentClass = componentClass;
this.type = oldReflectPropertyDescriptor.PropertyType;
if (componentClass == null) {
throw new ArgumentException(SR.GetString(SR.InvalidNullArgument, "componentClass"));
}
// If the classes are the same, we can potentially optimize the method fetch because
// the old property descriptor may already have it.
//
ReflectPropertyDescriptor oldProp = oldReflectPropertyDescriptor as ReflectPropertyDescriptor;
if (oldProp != null) {
if (oldProp.ComponentType == componentClass) {
propInfo = oldProp.propInfo;
getMethod = oldProp.getMethod;
setMethod = oldProp.setMethod;
shouldSerializeMethod = oldProp.shouldSerializeMethod;
resetMethod = oldProp.resetMethod;
defaultValue = oldProp.defaultValue;
ambientValue = oldProp.ambientValue;
state = oldProp.state;
}
// Now we must figure out what to do with our default value. First, check to see
// if the caller has provided an new default value attribute. If so, use it. Otherwise,
// just let it be and it will be picked up on demand.
//
if (attributes != null) {
foreach(Attribute a in attributes) {
DefaultValueAttribute dva = a as DefaultValueAttribute;
if (dva != null) {
defaultValue = dva.Value;
// Default values for enums are often stored as their underlying integer type:
if (defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType()) {
defaultValue = Enum.ToObject(PropertyType, defaultValue);
}
state[BitDefaultValueQueried] = true;
}
else {
AmbientValueAttribute ava = a as AmbientValueAttribute;
if (ava != null) {
ambientValue = ava.Value;
state[BitAmbientValueQueried] = true;
}
}
}
}
}
#if DEBUG
else if (oldReflectPropertyDescriptor is DebugReflectPropertyDescriptor)
{
DebugReflectPropertyDescriptor oldProp1 = (DebugReflectPropertyDescriptor)oldReflectPropertyDescriptor;
if (oldProp1.ComponentType == componentClass) {
propInfo = oldProp1.propInfo;
getMethod = oldProp1.getMethod;
setMethod = oldProp1.setMethod;
shouldSerializeMethod = oldProp1.shouldSerializeMethod;
resetMethod = oldProp1.resetMethod;
defaultValue = oldProp1.defaultValue;
ambientValue = oldProp1.ambientValue;
state = oldProp1.state;
}
// Now we must figure out what to do with our default value. First, check to see
// if the caller has provided an new default value attribute. If so, use it. Otherwise,
// just let it be and it will be picked up on demand.
//
if (attributes != null) {
foreach(Attribute a in attributes) {
if (a is DefaultValueAttribute) {
defaultValue = ((DefaultValueAttribute)a).Value;
state[BitDefaultValueQueried] = true;
}
else if (a is AmbientValueAttribute) {
ambientValue = ((AmbientValueAttribute)a).Value;
state[BitAmbientValueQueried] = true;
}
}
}
}
#endif
}
/// <devdoc>
/// Retrieves the ambient value for this property.
/// </devdoc>
private object AmbientValue {
get {
if (!state[BitAmbientValueQueried]) {
state[BitAmbientValueQueried] = true;
Attribute a = Attributes[typeof(AmbientValueAttribute)];
if (a != null) {
ambientValue = ((AmbientValueAttribute)a).Value;
}
else {
ambientValue = noValue;
}
}
return ambientValue;
}
}
/// <devdoc>
/// The EventDescriptor for the "{propertyname}Changed" event on the component, or null if there isn't one for this property.
/// </devdoc>
private EventDescriptor ChangedEventValue {
get {
if (!state[BitChangedQueried]) {
state[BitChangedQueried] = true;
realChangedEvent = TypeDescriptor.GetEvents(ComponentType)[string.Format(CultureInfo.InvariantCulture, "{0}Changed", Name)];
}
return realChangedEvent;
}
/*
The following code has been removed to fix FXCOP violations. The code
is left here incase it needs to be resurrected in the future.
set {
realChangedEvent = value;
state[BitChangedQueried] = true;
}
*/
}
/// <devdoc>
/// The EventDescriptor for the INotifyPropertyChanged.PropertyChanged event on the component, or null if there isn't one for this property.
/// </devdoc>
private EventDescriptor IPropChangedEventValue {
get {
if (!state[BitIPropChangedQueried]) {
state[BitIPropChangedQueried] = true;
if (typeof(INotifyPropertyChanged).IsAssignableFrom(ComponentType)) {
realIPropChangedEvent = TypeDescriptor.GetEvents(typeof(INotifyPropertyChanged))["PropertyChanged"];
}
}
return realIPropChangedEvent;
}
set {
realIPropChangedEvent = value;
state[BitIPropChangedQueried] = true;
}
}
/// <devdoc>
/// Retrieves the type of the component this PropertyDescriptor is bound to.
/// </devdoc>
public override Type ComponentType {
get {
return componentClass;
}
}
/// <devdoc>
/// Retrieves the default value for this property.
/// </devdoc>
private object DefaultValue {
get {
if (!state[BitDefaultValueQueried]) {
state[BitDefaultValueQueried] = true;
Attribute a = Attributes[typeof(DefaultValueAttribute)];
if (a != null) {
defaultValue = ((DefaultValueAttribute)a).Value;
// Default values for enums are often stored as their underlying integer type:
if (defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType()) {
defaultValue = Enum.ToObject(PropertyType, defaultValue);
}
}
else {
defaultValue = noValue;
}
}
return defaultValue;
}
}
/// <devdoc>
/// The GetMethod for this property
/// </devdoc>
private MethodInfo GetMethodValue {
get {
if (!state[BitGetQueried]) {
state[BitGetQueried] = true;
if (receiverType == null) {
if (propInfo == null) {
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty;
propInfo = componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]);
}
if (propInfo != null) {
getMethod = propInfo.GetGetMethod(true);
}
if (getMethod == null) {
throw new InvalidOperationException(SR.GetString(SR.ErrorMissingPropertyAccessors, componentClass.FullName + "." + Name));
}
}
else {
getMethod = FindMethod(componentClass, "Get" + Name, new Type[] { receiverType }, type);
if (getMethod == null) {
throw new ArgumentException(SR.GetString(SR.ErrorMissingPropertyAccessors, Name));
}
}
}
return getMethod;
}
/*
The following code has been removed to fix FXCOP violations. The code
is left here incase it needs to be resurrected in the future.
set {
state[BitGetQueried] = true;
getMethod = value;
}
*/
}
/// <devdoc>
/// Determines if this property is an extender property.
/// </devdoc>
private bool IsExtender {
get {
return (receiverType != null);
}
}
/// <devdoc>
/// Indicates whether this property is read only.
/// </devdoc>
public override bool IsReadOnly {
get {
return SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly;
}
}
/// <devdoc>
/// Retrieves the type of the property.
/// </devdoc>
public override Type PropertyType {
get {
return type;
}
}
/// <devdoc>
/// Access to the reset method, if one exists for this property.
/// </devdoc>
private MethodInfo ResetMethodValue {
get {
if (!state[BitResetQueried]) {
state[BitResetQueried] = true;
Type[] args;
if (receiverType == null) {
args = argsNone;
}
else {
args = new Type[] {receiverType};
}
IntSecurity.FullReflection.Assert();
try {
resetMethod = FindMethod(componentClass, "Reset" + Name, args, typeof(void), /* publicOnly= */ false);
}
finally {
CodeAccessPermission.RevertAssert();
}
}
return resetMethod;
}
/*
The following code has been removed to fix FXCOP violations. The code
is left here incase it needs to be resurrected in the future.
set {
state[BitResetQueried] = true;
resetMethod = value;
}
*/
}
/// <devdoc>
/// Accessor for the set method
/// </devdoc>
private MethodInfo SetMethodValue {
get {
if (!state[BitSetQueried] && state[BitSetOnDemand])
{
state[BitSetQueried] = true;
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
string name = propInfo.Name;
if (setMethod == null)
{
for (Type t = ComponentType.BaseType; t != null && t != typeof(object); t = t.BaseType)
{
if (t == null)
{
break;
}
PropertyInfo p = t.GetProperty(name, bindingFlags, null, PropertyType, new Type[0], null);
if (p != null)
{
setMethod = p.GetSetMethod();
if (setMethod != null)
{
break;
}
}
}
}
}
if (!state[BitSetQueried]) {
state[BitSetQueried] = true;
if (receiverType == null) {
if (propInfo == null) {
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty;
propInfo = componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]);
}
if (propInfo != null) {
setMethod = propInfo.GetSetMethod(true);
}
}
else {
setMethod = FindMethod(componentClass, "Set" + Name,
new Type[] { receiverType, type}, typeof(void));
}
}
return setMethod;
}
/*
The following code has been removed to fix FXCOP violations. The code
is left here incase it needs to be resurrected in the future.
set {
state[BitSetQueried] = true;
setMethod = value;
}
*/
}
/// <devdoc>
/// Accessor for the ShouldSerialize method.
/// </devdoc>
private MethodInfo ShouldSerializeMethodValue {
get {
if (!state[BitShouldSerializeQueried]) {
state[BitShouldSerializeQueried] = true;
Type[] args;
if (receiverType == null) {
args = argsNone;
}
else {
args = new Type[] {receiverType};
}
IntSecurity.FullReflection.Assert();
try {
shouldSerializeMethod = FindMethod(componentClass, "ShouldSerialize" + Name,
args, typeof(Boolean), /* publicOnly= */ false);
}
finally {
CodeAccessPermission.RevertAssert();
}
}
return shouldSerializeMethod;
}
/*
The following code has been removed to fix FXCOP violations. The code
is left here incase it needs to be resurrected in the future.
set {
state[BitShouldSerializeQueried] = true;
shouldSerializeMethod = value;
}
*/
}
/// <devdoc>
/// Allows interested objects to be notified when this property changes.
/// </devdoc>
public override void AddValueChanged(object component, EventHandler handler) {
if (component == null) throw new ArgumentNullException("component");
if (handler == null) throw new ArgumentNullException("handler");
// If there's an event called <propertyname>Changed, hook the caller's handler directly up to that on the component
EventDescriptor changedEvent = ChangedEventValue;
if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) {
changedEvent.AddEventHandler(component, handler);
}
// Otherwise let the base class add the handler to its ValueChanged event for this component
else {
// Special case: If this will be the FIRST handler added for this component, and the component implements
// INotifyPropertyChanged, the property descriptor must START listening to the generic PropertyChanged event
if (GetValueChangedHandler(component) == null) {
EventDescriptor iPropChangedEvent = IPropChangedEventValue;
if (iPropChangedEvent != null) {
iPropChangedEvent.AddEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged));
}
}
base.AddValueChanged(component, handler);
}
}
internal bool ExtenderCanResetValue(IExtenderProvider provider, object component) {
if (DefaultValue != noValue) {
return !object.Equals(ExtenderGetValue(provider, component),defaultValue);
}
MethodInfo reset = ResetMethodValue;
if (reset != null) {
MethodInfo shouldSerialize = ShouldSerializeMethodValue;
if (shouldSerialize != null) {
try {
provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider);
return (bool)shouldSerialize.Invoke(provider, new object[] { component});
}
catch {}
}
return true;
}
return false;
}
internal Type ExtenderGetReceiverType() {
return receiverType;
}
internal Type ExtenderGetType(IExtenderProvider provider) {
return PropertyType;
}
internal object ExtenderGetValue(IExtenderProvider provider, object component) {
if (provider != null) {
provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider);
return GetMethodValue.Invoke(provider, new object[] { component});
}
return null;
}
internal void ExtenderResetValue(IExtenderProvider provider, object component, PropertyDescriptor notifyDesc) {
if (DefaultValue != noValue) {
ExtenderSetValue(provider, component, DefaultValue, notifyDesc);
}
else if (AmbientValue != noValue) {
ExtenderSetValue(provider, component, AmbientValue, notifyDesc);
}
else if (ResetMethodValue != null) {
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object newValue;
// Announce that we are about to change this component
//
if (site != null) {
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null) {
oldValue = ExtenderGetValue(provider, component);
try {
changeService.OnComponentChanging(component, notifyDesc);
}
catch (CheckoutException coEx) {
if (coEx == CheckoutException.Canceled) {
return;
}
throw coEx;
}
}
provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider);
if (ResetMethodValue != null) {
ResetMethodValue.Invoke(provider, new object[] { component});
// Now notify the change service that the change was successful.
//
if (changeService != null) {
newValue = ExtenderGetValue(provider, component);
changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue);
}
}
}
}
internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc) {
if (provider != null) {
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
// Announce that we are about to change this component
//
if (site != null) {
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null) {
oldValue = ExtenderGetValue(provider, component);
try {
changeService.OnComponentChanging(component, notifyDesc);
}
catch (CheckoutException coEx) {
if (coEx == CheckoutException.Canceled) {
return;
}
throw coEx;
}
}
provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider);
if (SetMethodValue != null) {
SetMethodValue.Invoke(provider, new object[] { component, value});
// Now notify the change service that the change was successful.
//
if (changeService != null) {
changeService.OnComponentChanged(component, notifyDesc, oldValue, value);
}
}
}
}
internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object component) {
provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider);
if (IsReadOnly) {
if (ShouldSerializeMethodValue != null) {
try {
return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] {component});
}
catch {}
}
return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
}
else if (DefaultValue == noValue) {
if (ShouldSerializeMethodValue != null) {
try {
return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] {component});
}
catch {}
}
return true;
}
return !object.Equals(DefaultValue, ExtenderGetValue(provider, component));
}
/// <devdoc>
/// Indicates whether reset will change the value of the component. If there
/// is a DefaultValueAttribute, then this will return true if getValue returns
/// something different than the default value. If there is a reset method and
/// a ShouldSerialize method, this will return what ShouldSerialize returns.
/// If there is just a reset method, this always returns true. If none of these
/// cases apply, this returns false.
/// </devdoc>
public override bool CanResetValue(object component) {
if (IsExtender || IsReadOnly) {
return false;
}
if (DefaultValue != noValue) {
return !object.Equals(GetValue(component),DefaultValue);
}
if (ResetMethodValue != null) {
if (ShouldSerializeMethodValue != null) {
component = GetInvocationTarget(componentClass, component);
try {
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch {}
}
return true;
}
if (AmbientValue != noValue) {
return ShouldSerializeValue(component);
}
return false;
}
protected override void FillAttributes(IList attributes) {
Debug.Assert(componentClass != null, "Must have a component class for FillAttributes");
//
// The order that we fill in attributes is critical. The list of attributes will be
// filtered so that matching attributes at the end of the list replace earlier matches
// (last one in wins). Therefore, the four categories of attributes we add must be
// added as follows:
//
// 1. Attributes of the property type. These are the lowest level and should be
// overwritten by any newer attributes.
//
// 2. Attributes obtained from any SpecificTypeAttribute. These supercede attributes
// for the property type.
//
// 3. Attributes of the property itself, from base class to most derived. This way
// derived class attributes replace base class attributes.
//
// 4. Attributes from our base MemberDescriptor. While this seems opposite of what
// we want, MemberDescriptor only has attributes if someone passed in a new
// set in the constructor. Therefore, these attributes always
// supercede existing values.
//
// We need to include attributes from the type of the property.
//
foreach (Attribute typeAttr in TypeDescriptor.GetAttributes(PropertyType)) {
attributes.Add(typeAttr);
}
// NOTE : Must look at method OR property, to handle the case of Extender properties...
//
// Note : Because we are using BindingFlags.DeclaredOnly it is more effcient to re-aquire
// : the property info, rather than use the one we have cached. The one we have cached
// : may ave come from a base class, meaning we will request custom metadata for this
// : class twice.
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly;
Type currentReflectType = componentClass;
int depth = 0;
// First, calculate the depth of the object hierarchy. We do this so we can do a single
// object create for an array of attributes.
//
while(currentReflectType != null && currentReflectType != typeof(object)) {
depth++;
currentReflectType = currentReflectType.BaseType;
}
// Now build up an array in reverse order
//
if (depth > 0) {
currentReflectType = componentClass;
Attribute[][] attributeStack = new Attribute[depth][];
while(currentReflectType != null && currentReflectType != typeof(object)) {
MemberInfo memberInfo = null;
// Fill in our member info so we can get at the custom attributes.
//
if (IsExtender) {
//receiverType is used to avoid ambitiousness when there are overloads for the get method.
memberInfo = currentReflectType.GetMethod("Get" + Name, bindingFlags, null, new Type[] { receiverType }, null);
}
else {
memberInfo = currentReflectType.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]);
}
// Get custom attributes for the member info.
//
if (memberInfo != null) {
attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo);
}
// Ready for the next loop iteration.
//
currentReflectType = currentReflectType.BaseType;
}
// Look in the attribute stack for AttributeProviders
//
foreach(Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach(Attribute attr in attributeArray) {
AttributeProviderAttribute sta = attr as AttributeProviderAttribute;
if (sta != null)
{
Type specificType = Type.GetType(sta.TypeName);
if (specificType != null)
{
Attribute[] stAttrs = null;
if (!String.IsNullOrEmpty(sta.PropertyName)) {
MemberInfo[] milist = specificType.GetMember(sta.PropertyName);
if (milist.Length > 0 && milist[0] != null) {
stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(milist[0]);
}
}
else {
stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(specificType);
}
if (stAttrs != null)
{
foreach(Attribute stAttr in stAttrs)
{
attributes.Add(stAttr);
}
}
}
}
}
}
}
// Now trawl the attribute stack so that we add attributes
// from base class to most derived.
//
foreach(Attribute[] attributeArray in attributeStack) {
if (attributeArray != null)
{
foreach(Attribute attr in attributeArray) {
attributes.Add(attr);
}
}
}
}
// Include the base attributes. These override all attributes on the actual
// property, so we want to add them last.
//
base.FillAttributes(attributes);
// Finally, override any form of ReadOnlyAttribute.
//
if (SetMethodValue == null) {
attributes.Add(ReadOnlyAttribute.Yes);
}
}
/// <devdoc>
/// Retrieves the current value of the property on component,
/// invoking the getXXX method. An exception in the getXXX
/// method will pass through.
/// </devdoc>
public override object GetValue(object component) {
#if DEBUG
if (PropDescUsageSwitch.TraceVerbose) {
string compName = "(null)";
if (component != null)
compName = component.ToString();
Debug.WriteLine("[" + Name + "]: GetValue(" + compName + ")");
}
#endif
if (IsExtender) {
Debug.WriteLineIf(PropDescUsageSwitch.TraceVerbose, "[" + Name + "]: ---> returning: null");
return null;
}
Debug.Assert(component != null, "GetValue must be given a component");
if (component != null) {
component = GetInvocationTarget(componentClass, component);
try {
return SecurityUtils.MethodInfoInvoke(GetMethodValue, component, null);
}
catch (Exception t) {
string name = null;
IComponent comp = component as IComponent;
if (comp != null) {
ISite site = comp.Site;
if (site != null && site.Name != null) {
name = site.Name;
}
}
if (name == null) {
name = component.GetType().FullName;
}
if (t is TargetInvocationException) {
t = t.InnerException;
}
string message = t.Message;
if (message == null) {
message = t.GetType().Name;
}
throw new TargetInvocationException(SR.GetString(SR.ErrorPropertyAccessorException, Name, name, message), t);
}
}
Debug.WriteLineIf(PropDescUsageSwitch.TraceVerbose, "[" + Name + "]: ---> returning: null");
return null;
}
/// <devdoc>
/// Handles INotifyPropertyChanged.PropertyChange events from components.
/// If event pertains to this property, issue a ValueChanged event.
/// </devdoc>
/// </internalonly>
internal void OnINotifyPropertyChanged(object component, PropertyChangedEventArgs e) {
if (String.IsNullOrEmpty(e.PropertyName) ||
String.Compare(e.PropertyName, Name, true, System.Globalization.CultureInfo.InvariantCulture) == 0) {
OnValueChanged(component, e);
}
}
/// <devdoc>
/// This should be called by your property descriptor implementation
/// when the property value has changed.
/// </devdoc>
protected override void OnValueChanged(object component, EventArgs e) {
if (state[BitChangedQueried] && realChangedEvent == null) {
base.OnValueChanged(component, e);
}
}
/// <devdoc>
/// Allows interested objects to be notified when this property changes.
/// </devdoc>
public override void RemoveValueChanged(object component, EventHandler handler) {
if (component == null) throw new ArgumentNullException("component");
if (handler == null) throw new ArgumentNullException("handler");
// If there's an event called <propertyname>Changed, we hooked the caller's
// handler directly up to that on the component, so remove it now.
EventDescriptor changedEvent = ChangedEventValue;
if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) {
changedEvent.RemoveEventHandler(component, handler);
}
// Otherwise the base class added the handler to its ValueChanged
// event for this component, so let the base class remove it now.
else {
base.RemoveValueChanged(component, handler);
// Special case: If that was the LAST handler removed for this component, and the component implements
// INotifyPropertyChanged, the property descriptor must STOP listening to the generic PropertyChanged event
if (GetValueChangedHandler(component) == null) {
EventDescriptor iPropChangedEvent = IPropChangedEventValue;
if (iPropChangedEvent != null) {
iPropChangedEvent.RemoveEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged));
}
}
}
}
/// <devdoc>
/// Will reset the default value for this property on the component. If
/// there was a default value passed in as a DefaultValueAttribute, that
/// value will be set as the value of the property on the component. If
/// there was no default value passed in, a ResetXXX method will be looked
/// for. If one is found, it will be invoked. If one is not found, this
/// is a nop.
/// </devdoc>
public override void ResetValue(object component) {
object invokee = GetInvocationTarget(componentClass, component);
if (DefaultValue != noValue) {
SetValue(component, DefaultValue);
}
else if (AmbientValue != noValue) {
SetValue(component, AmbientValue);
}
else if (ResetMethodValue != null) {
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object newValue;
// Announce that we are about to change this component
//
if (site != null) {
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null) {
// invokee might be a type from mscorlib or system, GetMethodValue might return a NonPublic method
oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null);
try {
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx) {
if (coEx == CheckoutException.Canceled) {
return;
}
throw coEx;
}
}
if (ResetMethodValue != null) {
SecurityUtils.MethodInfoInvoke(ResetMethodValue, invokee, (object[])null);
// Now notify the change service that the change was successful.
//
if (changeService != null) {
newValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null);
changeService.OnComponentChanged(component, this, oldValue, newValue);
}
}
}
}
/// <devdoc>
/// This will set value to be the new value of this property on the
/// component by invoking the setXXX method on the component. If the
/// value specified is invalid, the component should throw an exception
/// which will be passed up. The component designer should design the
/// property so that getXXX following a setXXX should return the value
/// passed in if no exception was thrown in the setXXX call.
/// </devdoc>
public override void SetValue(object component, object value) {
#if DEBUG
if (PropDescUsageSwitch.TraceVerbose) {
string compName = "(null)";
string valName = "(null)";
if (component != null)
compName = component.ToString();
if (value != null)
valName = value.ToString();
Debug.WriteLine("[" + Name + "]: SetValue(" + compName + ", " + valName + ")");
}
#endif
if (component != null) {
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object invokee = GetInvocationTarget(componentClass, component);
if (!IsReadOnly) {
// Announce that we are about to change this component
//
if (site != null) {
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null) {
oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null);
try {
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx) {
if (coEx == CheckoutException.Canceled) {
return;
}
throw coEx;
}
}
try {
try {
SecurityUtils.MethodInfoInvoke(SetMethodValue, invokee, new object[] { value });
OnValueChanged(invokee, EventArgs.Empty);
}
catch (Exception t) {
// Give ourselves a chance to unwind properly before rethrowing the exception.
//
value = oldValue;
// If there was a problem setting the controls property then we get:
// ArgumentException (from properties set method)
// ==> Becomes inner exception of TargetInvocationException
// ==> caught here
if (t is TargetInvocationException && t.InnerException != null) {
// Propagate the original exception up
throw t.InnerException;
}
else {
throw t;
}
}
}
finally {
// Now notify the change service that the change was successful.
//
if (changeService != null) {
changeService.OnComponentChanged(component, this, oldValue, value);
}
}
}
}
}
/// <devdoc>
/// Indicates whether the value of this property needs to be persisted. In
/// other words, it indicates whether the state of the property is distinct
/// from when the component is first instantiated. If there is a default
/// value specified in this ReflectPropertyDescriptor, it will be compared against the
/// property's current value to determine this. If there is't, the
/// ShouldSerializeXXX method is looked for and invoked if found. If both
/// these routes fail, true will be returned.
///
/// If this returns false, a tool should not persist this property's value.
/// </devdoc>
public override bool ShouldSerializeValue(object component) {
component = GetInvocationTarget(componentClass, component);
if (IsReadOnly) {
if (ShouldSerializeMethodValue != null) {
try {
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch {}
}
return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
}
else if (DefaultValue == noValue) {
if (ShouldSerializeMethodValue != null) {
try {
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch {}
}
return true;
}
return !object.Equals(DefaultValue, GetValue(component));
}
/// <devdoc>
/// Indicates whether value change notifications for this property may originate from outside the property
/// descriptor, such as from the component itself (value=true), or whether notifications will only originate
/// from direct calls made to PropertyDescriptor.SetValue (value=false). For example, the component may
/// implement the INotifyPropertyChanged interface, or may have an explicit '{name}Changed' event for this property.
/// </devdoc>
public override bool SupportsChangeEvents {
get {
return IPropChangedEventValue != null || ChangedEventValue != null;
}
}
/*
The following code has been removed to fix FXCOP violations. The code
is left here incase it needs to be resurrected in the future.
/// <devdoc>
/// A constructor for ReflectPropertyDescriptors that have no attributes.
/// </devdoc>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type) : this(componentClass, name, type, (Attribute[])null) {
}
*/
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Xml;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Host;
using System.Globalization;
using System.Text;
#if CORECLR
// Use stubs for SystemException
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
/*
SUMMARY: this file contains a general purpose, reusable framework for
loading XML files, and do data validation.
It provides the capability of:
* logging errors, warnings and traces to a file or in memory
* managing the XML dom traversal using an add hoc stack frame management scheme
* validating common error conditions (e.g. missing node or unknown node)
*/
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// base exception to be used for all the exceptions that this framework will generate
/// </summary>
internal abstract class TypeInfoDataBaseLoaderException : SystemException
{
}
/// <summary>
/// exception thrown by the loader when the maximum number of errors is exceeded
/// </summary>
internal class TooManyErrorsException : TypeInfoDataBaseLoaderException
{
/// <summary>
/// error count that triggered the exception
/// </summary>
internal int errorCount;
}
/// <summary>
/// entry logged by the loader and made available to external consumers
/// </summary>
internal class XmlLoaderLoggerEntry
{
internal enum EntryType { Error, Trace };
/// <summary>
/// type of information being logged
/// </summary>
internal EntryType entryType;
/// <summary>
/// path of the file the info refers to
/// </summary>
internal string filePath = null;
/// <summary>
/// XPath location inside the file
/// </summary>
internal string xPath = null;
/// <summary>
/// message to be displayed to the user
/// </summary>
internal string message = null;
/// <summary>
/// indicate whether we fail to load the file due to the security reason
/// </summary>
internal bool failToLoadFile = false;
}
/// <summary>
/// logger object used by the loader (class XmlLoaderBase) to write log entries.
/// It logs to a memory buffer and (optionally) to a text file
/// </summary>
internal class XmlLoaderLogger : IDisposable
{
#region tracer
//PSS/end-user tracer
[TraceSource("FormatFileLoading", "Loading format files")]
private static PSTraceSource s_formatFileLoadingtracer = PSTraceSource.GetTracer("FormatFileLoading", "Loading format files", false);
#endregion tracer
/// <summary>
/// log an entry
/// </summary>
/// <param name="entry">entry to log</param>
internal void LogEntry(XmlLoaderLoggerEntry entry)
{
if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error)
_hasErrors = true;
if (_saveInMemory)
_entries.Add(entry);
if ((s_formatFileLoadingtracer.Options | PSTraceSourceOptions.WriteLine) != 0)
WriteToTracer(entry);
}
private void WriteToTracer(XmlLoaderLoggerEntry entry)
{
if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error)
{
s_formatFileLoadingtracer.WriteLine("ERROR:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message);
}
else if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Trace)
{
s_formatFileLoadingtracer.WriteLine("TRACE:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message);
}
}
/// <summary>
/// IDisposable implementation
/// </summary>
/// <remarks>This method calls GC.SuppressFinalize</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
}
internal List<XmlLoaderLoggerEntry> LogEntries
{
get
{
return _entries;
}
}
internal bool HasErrors
{
get
{
return _hasErrors;
}
}
/// <summary>
/// if true, log entries to memory
/// </summary>
private bool _saveInMemory = true;
/// <summary>
/// list of entries logged if saveInMemory is true
/// </summary>
private List<XmlLoaderLoggerEntry> _entries = new List<XmlLoaderLoggerEntry>();
/// <summary>
/// true if we ever logged an error
/// </summary>
private bool _hasErrors = false;
}
/// <summary>
/// base class providing XML loading basic functionality (stack management and logging facilities)
/// NOTE: you need to implement to load an actual XML document and traverse it as see fit
/// </summary>
internal abstract class XmlLoaderBase : IDisposable
{
#region tracer
[TraceSource("XmlLoaderBase", "XmlLoaderBase")]
private static PSTraceSource s_tracer = PSTraceSource.GetTracer("XmlLoaderBase", "XmlLoaderBase");
#endregion tracer
/// <summary>
/// class representing a stack frame for the XML document tree traversal
/// </summary>
private sealed class XmlLoaderStackFrame : IDisposable
{
internal XmlLoaderStackFrame(XmlLoaderBase loader, XmlNode n, int index)
{
_loader = loader;
this.node = n;
this.index = index;
}
/// <summary>
/// IDisposable implementation
/// </summary>
public void Dispose()
{
if (_loader != null)
{
_loader.RemoveStackFrame();
_loader = null;
}
}
/// <summary>
/// back pointer to the loader, used to pop a stack frame
/// </summary>
private XmlLoaderBase _loader;
/// <summary>
/// node the stack frame refers to
/// </summary>
internal XmlNode node;
/// <summary>
/// node index for enumerations, valid only if != -1
/// NOTE: this allows to express the XPath construct "foo[0]"
/// </summary>
internal int index = -1;
}
/// <summary>
/// IDisposable implementation
/// </summary>
/// <remarks>This method calls GC.SuppressFinalize</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_logger != null)
{
_logger.Dispose();
_logger = null;
}
}
}
/// <summary>
/// get the list of log entries
/// </summary>
/// <value>list of entries logged during a load</value>
internal List<XmlLoaderLoggerEntry> LogEntries
{
get
{
return _logger.LogEntries;
}
}
/// <summary>
/// check if there were errors
/// </summary>
/// <value>true of the log entry list has errors</value>
internal bool HasErrors
{
get
{
return _logger.HasErrors;
}
}
/// <summary>
/// to be called when starting a stack frame.
/// The returned IDisposable should be used in a using(){...} block
/// </summary>
/// <param name="n">node to push on the stack</param>
/// <returns>object to dispose when exiting the frame</returns>
protected IDisposable StackFrame(XmlNode n)
{
return StackFrame(n, -1);
}
/// <summary>
/// to be called when starting a stack frame.
/// The returned IDisposable should be used in a using(){...} block
/// </summary>
/// <param name="n">node to push on the stack</param>
/// <param name="index">index of the node of the same name in a collection</param>
/// <returns>object to dispose when exiting the frame</returns>
protected IDisposable StackFrame(XmlNode n, int index)
{
XmlLoaderStackFrame sf = new XmlLoaderStackFrame(this, n, index);
_executionStack.Push(sf);
if (_logStackActivity)
WriteStackLocation("Enter");
return sf;
}
/// <summary>
/// called by the Dispose code of the XmlLoaderStackFrame object
/// to pop a frame off the stack
/// </summary>
private void RemoveStackFrame()
{
if (_logStackActivity)
WriteStackLocation("Exit");
_executionStack.Pop();
}
protected void ProcessUnknownNode(XmlNode n)
{
if (IsFilteredOutNode(n))
return;
ReportIllegalXmlNode(n);
}
protected void ProcessUnknownAttribute(XmlAttribute a)
{
ReportIllegalXmlAttribute(a);
}
protected static bool IsFilteredOutNode(XmlNode n)
{
return (n is XmlComment || n is XmlWhitespace);
}
protected bool VerifyNodeHasNoChildren(XmlNode n)
{
if (n.ChildNodes.Count == 0)
return true;
if (n.ChildNodes.Count == 1)
{
if (n.ChildNodes[0] is XmlText)
return true;
}
//Error at XPath {0} in file {1}: Node {2} cannot have children.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoChildrenAllowed, ComputeCurrentXPath(), FilePath, n.Name));
return false;
}
internal string GetMandatoryInnerText(XmlNode n)
{
if (String.IsNullOrEmpty(n.InnerText))
{
this.ReportEmptyNode(n);
return null;
}
return n.InnerText;
}
internal string GetMandatoryAttributeValue(XmlAttribute a)
{
if (String.IsNullOrEmpty(a.Value))
{
this.ReportEmptyAttribute(a);
return null;
}
return a.Value;
}
/// <summary>
/// helper to compare node names, e.g. "foo" in <foo/>
/// it uses case sensitive, culture invariant compare.
/// This is because XML tags are case sensitive.
/// </summary>
/// <param name="n">XmlNode whose name is to compare</param>
/// <param name="s">string to compare the node name to</param>
/// <param name="allowAttributes">if true, accept the presence of attributes on the node</param>
/// <returns>true if there is a match</returns>
private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes)
{
bool match = false;
if (String.Equals(n.Name, s, StringComparison.Ordinal))
{
// we have a case sensitive match
match = true;
}
else if (String.Equals(n.Name, s, StringComparison.OrdinalIgnoreCase))
{
// try a case insensitive match
// we differ only in case: flag this as an ERROR for the time being
// and accept the comparison
string fmtString = "XML tag differ in case only {0} {1}";
ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, n.Name, s));
match = true;
}
if (match && !allowAttributes)
{
XmlElement e = n as XmlElement;
if (e != null && e.Attributes.Count > 0)
{
//Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes.
ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name));
}
}
return match;
}
internal bool MatchNodeNameWithAttributes(XmlNode n, string s)
{
return MatchNodeNameHelper(n, s, true);
}
internal bool MatchNodeName(XmlNode n, string s)
{
return MatchNodeNameHelper(n, s, false);
}
internal bool MatchAttributeName(XmlAttribute a, string s)
{
if (String.Equals(a.Name, s, StringComparison.Ordinal))
{
// we have a case sensitive match
return true;
}
else if (String.Equals(a.Name, s, StringComparison.OrdinalIgnoreCase))
{
// try a case insensitive match
// we differ only in case: flag this as an ERROR for the time being
// and accept the comparison
string fmtString = "XML attribute differ in case only {0} {1}";
ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, a.Name, s));
return true;
}
return false;
}
internal void ProcessDuplicateNode(XmlNode n)
{
//Error at XPath {0} in file {1}: Duplicated node.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.DuplicatedNode, ComputeCurrentXPath(), FilePath), XmlLoaderLoggerEntry.EntryType.Error);
}
internal void ProcessDuplicateAlternateNode(string node1, string node2)
{
//Error at XPath {0} in file {1}: {2} and {3} are mutually exclusive.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MutuallyExclusiveNode, ComputeCurrentXPath(), FilePath, node1, node2), XmlLoaderLoggerEntry.EntryType.Error);
}
internal void ProcessDuplicateAlternateNode(XmlNode n, string node1, string node2)
{
//Error at XPath {0} in file {1}: {2}, {3} and {4} are mutually exclusive.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.ThreeMutuallyExclusiveNode, ComputeCurrentXPath(), FilePath, n.Name, node1, node2), XmlLoaderLoggerEntry.EntryType.Error);
}
private void ReportIllegalXmlNode(XmlNode n)
{
//UnknownNode=Error at XPath {0} in file {1}: {2} is an unknown node.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.UnknownNode, ComputeCurrentXPath(), FilePath, n.Name), XmlLoaderLoggerEntry.EntryType.Error);
}
private void ReportIllegalXmlAttribute(XmlAttribute a)
{
//Error at XPath {0} in file {1}: {2} is an unknown attribute.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.UnknownAttribute, ComputeCurrentXPath(), FilePath, a.Name), XmlLoaderLoggerEntry.EntryType.Error);
}
protected void ReportMissingAttribute(string name)
{
//Error at XPath {0} in file {1}: {2} is a missing attribute.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingAttribute, ComputeCurrentXPath(), FilePath, name), XmlLoaderLoggerEntry.EntryType.Error);
}
protected void ReportMissingNode(string name)
{
//Error at XPath {0} in file {1}: Missing Node {2}.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, name), XmlLoaderLoggerEntry.EntryType.Error);
}
protected void ReportMissingNodes(string[] names)
{
//Error at XPath {0} in file {1}: Missing Node from {2}.
string namesString = string.Join(", ", names);
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNodeFromList, ComputeCurrentXPath(), FilePath, namesString), XmlLoaderLoggerEntry.EntryType.Error);
}
protected void ReportEmptyNode(XmlNode n)
{
//Error at XPath {0} in file {1}: {2} is an empty node.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyNode, ComputeCurrentXPath(), FilePath, n.Name), XmlLoaderLoggerEntry.EntryType.Error);
}
protected void ReportEmptyAttribute(XmlAttribute a)
{
//EmptyAttribute=Error at XPath {0} in file {1}: {2} is an empty attribute.
ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyAttribute, ComputeCurrentXPath(), FilePath, a.Name), XmlLoaderLoggerEntry.EntryType.Error);
}
/// <summary>
/// For tracing purposes only, don't add to log
/// </summary>
/// <param name="message">
/// trace message, non-localized string is OK.
/// </param>
protected void ReportTrace(string message)
{
ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Trace);
}
protected void ReportError(string message)
{
ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Error);
}
private void ReportLogEntryHelper(string message, XmlLoaderLoggerEntry.EntryType entryType, bool failToLoadFile = false)
{
string currentPath = ComputeCurrentXPath();
XmlLoaderLoggerEntry entry = new XmlLoaderLoggerEntry();
entry.entryType = entryType;
entry.filePath = this.FilePath;
entry.xPath = currentPath;
entry.message = message;
if (failToLoadFile)
{
System.Management.Automation.Diagnostics.Assert(entryType == XmlLoaderLoggerEntry.EntryType.Error, "the entry type should be 'error' when a file cannot be loaded");
entry.failToLoadFile = true;
}
_logger.LogEntry(entry);
if (entryType == XmlLoaderLoggerEntry.EntryType.Error)
{
_currentErrorCount++;
if (_currentErrorCount >= _maxNumberOfErrors)
{
// we have to log a last error and then bail
if (_maxNumberOfErrors > 1)
{
XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry();
lastEntry.entryType = XmlLoaderLoggerEntry.EntryType.Error;
lastEntry.filePath = this.FilePath;
lastEntry.xPath = currentPath;
lastEntry.message = StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyErrors, FilePath);
_logger.LogEntry(lastEntry);
_currentErrorCount++;
}
// NOTE: this exception is an internal one, and it is caught
// internally by the calling code.
TooManyErrorsException e = new TooManyErrorsException();
e.errorCount = _currentErrorCount;
throw e;
}
}
}
/// <summary>
/// Report error when loading formatting data from object model
/// </summary>
/// <param name="message"></param>
/// <param name="typeName"></param>
protected void ReportErrorForLoadingFromObjectModel(string message, string typeName)
{
XmlLoaderLoggerEntry entry = new XmlLoaderLoggerEntry();
entry.entryType = XmlLoaderLoggerEntry.EntryType.Error;
entry.message = message;
_logger.LogEntry(entry);
_currentErrorCount++;
if (_currentErrorCount >= _maxNumberOfErrors)
{
// we have to log a last error and then bail
if (_maxNumberOfErrors > 1)
{
XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry();
lastEntry.entryType = XmlLoaderLoggerEntry.EntryType.Error;
lastEntry.message = StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyErrorsInFormattingData, typeName);
_logger.LogEntry(lastEntry);
_currentErrorCount++;
}
// NOTE: this exception is an internal one, and it is caught
// internally by the calling code.
TooManyErrorsException e = new TooManyErrorsException();
e.errorCount = _currentErrorCount;
throw e;
}
}
private void WriteStackLocation(string label)
{
ReportTrace(label);
}
protected string ComputeCurrentXPath()
{
StringBuilder path = new StringBuilder();
foreach (XmlLoaderStackFrame sf in _executionStack)
{
path.Insert(0, "/");
if (sf.index != -1)
{
path.Insert(1, string.Format(CultureInfo.InvariantCulture,
"{0}[{1}]", sf.node.Name, sf.index + 1));
}
else
{
path.Insert(1, sf.node.Name);
}
}
return path.Length > 0 ? path.ToString() : null;
}
#region helpers for loading XML documents
protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, out bool isFullyTrusted)
{
// get file contents
ExternalScriptInfo ps1xmlInfo = new ExternalScriptInfo(FilePath, FilePath);
string fileContents = ps1xmlInfo.ScriptContents;
isFullyTrusted = false;
if (ps1xmlInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage)
{
isFullyTrusted = true;
}
if (authorizationManager != null)
{
try
{
authorizationManager.ShouldRunInternal(ps1xmlInfo, CommandOrigin.Internal, host);
}
catch (PSSecurityException reason)
{
string errorMessage = StringUtil.Format(TypesXmlStrings.ValidationException,
string.Empty /* TODO/FIXME snapin */,
FilePath,
reason.Message);
ReportLogEntryHelper(errorMessage, XmlLoaderLoggerEntry.EntryType.Error, failToLoadFile: true);
return null;
}
}
// load file into XML document
try
{
XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
fileContents,
true, /* preserve whitespace, comments, etc. */
null); /* default maxCharacters */
this.ReportTrace("XmlDocument loaded OK");
return doc;
}
catch (XmlException e)
{
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, FilePath, e.Message));
this.ReportTrace("XmlDocument discarded");
return null;
}
catch (Exception e) // will rethrow
{
CommandProcessor.CheckForSevereException(e);
throw;
}
}
#endregion
/// <summary>
/// file system path for the file we are loading from
/// </summary>
///
protected string FilePath
{
get
{
return _loadingInfo.filePath;
}
}
protected void SetDatabaseLoadingInfo(XmlFileLoadInfo info)
{
_loadingInfo.fileDirectory = info.fileDirectory;
_loadingInfo.filePath = info.filePath;
}
protected void SetLoadingInfoIsFullyTrusted(bool isFullyTrusted)
{
_loadingInfo.isFullyTrusted = isFullyTrusted;
}
protected void SetLoadingInfoIsProductCode(bool isProductCode)
{
_loadingInfo.isProductCode = isProductCode;
}
private DatabaseLoadingInfo _loadingInfo = new DatabaseLoadingInfo();
protected DatabaseLoadingInfo LoadingInfo
{
get
{
DatabaseLoadingInfo info = new DatabaseLoadingInfo();
info.filePath = _loadingInfo.filePath;
info.fileDirectory = _loadingInfo.fileDirectory;
info.isFullyTrusted = _loadingInfo.isFullyTrusted;
info.isProductCode = _loadingInfo.isProductCode;
return info;
}
}
protected MshExpressionFactory expressionFactory;
protected DisplayResourceManagerCache displayResourceManagerCache;
internal bool VerifyStringResources { get; } = true;
private int _maxNumberOfErrors = 30;
private int _currentErrorCount = 0;
private bool _logStackActivity = false;
private Stack<XmlLoaderStackFrame> _executionStack = new Stack<XmlLoaderStackFrame>();
private XmlLoaderLogger _logger = new XmlLoaderLogger();
}
}
| |
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using SillyWidgets.Gizmos;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.DynamoDBv2.DocumentModel;
namespace SillyWidgets
{
public class SillyView : ISillyView
{
public SillyContentType ContentType { get; set; }
private Dictionary<string, SillyAttribute> BindVals = new Dictionary<string, SillyAttribute>();
public string Content
{
get
{
if (String.IsNullOrEmpty(_content))
{
return(Render());
}
return(_content);
}
set
{
_content = value;
}
}
private string _content = string.Empty;
private HtmlGizmo Html = null;
public SillyView()
{
ContentType = SillyContentType.Html;
Content = string.Empty;
}
public void Load(StreamReader data)
{
Html = new HtmlGizmo();
bool success = Html.Load(data);
if (!success)
{
throw new Exception("Parsing HTML: " + Html.ParseError);
}
}
public async Task<bool> LoadS3Async(string bucket, string key, Amazon.RegionEndpoint endpoint)
{
AmazonS3Client S3Client = new AmazonS3Client(endpoint);
GetObjectResponse response = await S3Client.GetObjectAsync(bucket, key);
using (StreamReader reader = new StreamReader(response.ResponseStream))
{
Load(reader);
}
return(true);
}
public SillyView Load(string filepath)
{
if (filepath == null ||
filepath.Length == 0)
{
throw new SillyException(SillyHttpStatusCode.NotFound, "Invalid view file specified, either NULL or empty");
}
if (!File.Exists(filepath))
{
throw new SillyException(SillyHttpStatusCode.NotFound, "View file '" + filepath + "' does not exist");
}
SillyView view = null;
FileStream fileStream = new FileStream(filepath, FileMode.Open);
using (StreamReader reader = new StreamReader(fileStream))
{
view = new SillyView();
view.Load(reader);
}
return(view);
}
public void Bind(string key, string text)
{
BindVals[key] = new SillyTextAttribute(key, new TextNode(text));
}
public void Bind(Document dynamoItem)
{
foreach(KeyValuePair<string, DynamoDBEntry> entry in dynamoItem)
{
BindVals[entry.Key] = new SillyTextAttribute(entry.Key, new TextNode(entry.Value.AsString()));
}
}
public void Bind(string key, SillyView view)
{
if (view == null ||
view.Html == null)
{
TextNode errorNode = new TextNode("Error binding " + key + ": no view or HTML to bind");
BindVals[key] = new SillyTextAttribute(key, errorNode);
return;
}
BindVals[key] = new SillyWidgetAttribute(key, view.Html.Root);
}
public async Task<bool> BindAsync(string key, string bucket, string bucketKey, Amazon.RegionEndpoint endpoint)
{
SillyView s3View = new SillyView();
bool loaded = await s3View.LoadS3Async(bucket, bucketKey, endpoint);
if (loaded)
{
Bind(key, s3View);
}
else
{
Bind(key, "Silly view not found: " + key);
}
return(loaded);
}
public string Render()
{
if (Html == null)
{
return(_content);
}
HtmlPayloadVisitor payloadCreator = new HtmlPayloadVisitor(BindVals);
Html.ExecuteHtmlVisitor(payloadCreator);
_content = payloadCreator.Payload.ToString();
return(_content);
}
}
internal class HtmlPayloadVisitor : IVisitor
{
public StringBuilder Payload { get; private set; }
private bool Exiting = false;
private Dictionary<string, SillyAttribute> BindVals = null;
public HtmlPayloadVisitor(Dictionary<string, SillyAttribute> bindVals)
{
Payload = new StringBuilder();
BindVals = bindVals;
}
public void Go(TreeNodeGizmo node)
{
if (node == null)
{
return;
}
Exiting = false;
node.Accept(this);
foreach(TreeNodeGizmo child in node.GetChildren())
{
Go(child);
}
Exiting = true;
node.Accept(this);
}
public void VisitElement(ElementNode node)
{
if (Exiting)
{
if (node.SelfCloseTag)
{
Payload.Append(" />");
}
else if (node.HasCloseTag)
{
Payload.Append("</");
Payload.Append(node.Name);
Payload.Append(">");
}
return;
}
Payload.Append("<");
Payload.Append(node.Name);
if (node.Attributes.Count > 0)
{
foreach(KeyValuePair<string, string> attr in node.Attributes)
{
if (BindVals != null)
{
if (SillyAttribute.IsSillyAttribute(attr.Key))
{
SillyAttribute boundAttr = null;
if (BindVals.TryGetValue(attr.Value, out boundAttr))
{
node.DeleteChildren();
if (boundAttr.BoundValues().Count == 0)
{
node.AddChild(new TextNode("Error rendering " + attr.Value + ": trying to bind null node"));
}
else
{
foreach(TreeNodeGizmo childNode in boundAttr.BoundValues())
{
node.AddChild(childNode);
}
}
continue;
}
}
}
Payload.Append(" ");
Payload.Append(attr.Key);
if (!String.IsNullOrEmpty(attr.Value))
{
Payload.Append("=\"");
Payload.Append(attr.Value);
Payload.Append("\"");
}
}
}
Payload.Append(">");
}
public void VisitText(TextNode node)
{
if (Exiting)
{
return;
}
Payload.Append(node.Text);
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.ElasticMapReduce.Model
{
/// <summary>
/// <para>Detailed information about an instance group. </para>
/// </summary>
public class InstanceGroupDetail
{
private string instanceGroupId;
private string name;
private string market;
private string instanceRole;
private string bidPrice;
private string instanceType;
private int? instanceRequestCount;
private int? instanceRunningCount;
private string state;
private string lastStateChangeReason;
private DateTime? creationDateTime;
private DateTime? startDateTime;
private DateTime? readyDateTime;
private DateTime? endDateTime;
/// <summary>
/// Unique identifier for the instance group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 256</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string InstanceGroupId
{
get { return this.instanceGroupId; }
set { this.instanceGroupId = value; }
}
/// <summary>
/// Sets the InstanceGroupId property
/// </summary>
/// <param name="instanceGroupId">The value to set for the InstanceGroupId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithInstanceGroupId(string instanceGroupId)
{
this.instanceGroupId = instanceGroupId;
return this;
}
// Check to see if InstanceGroupId property is set
internal bool IsSetInstanceGroupId()
{
return this.instanceGroupId != null;
}
/// <summary>
/// Friendly name for the instance group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 256</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Name
{
get { return this.name; }
set { this.name = value; }
}
/// <summary>
/// Sets the Name property
/// </summary>
/// <param name="name">The value to set for the Name property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithName(string name)
{
this.name = name;
return this;
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this.name != null;
}
/// <summary>
/// Market type of the Amazon EC2 instances used to create a cluster node.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>ON_DEMAND, SPOT</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Market
{
get { return this.market; }
set { this.market = value; }
}
/// <summary>
/// Sets the Market property
/// </summary>
/// <param name="market">The value to set for the Market property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithMarket(string market)
{
this.market = market;
return this;
}
// Check to see if Market property is set
internal bool IsSetMarket()
{
return this.market != null;
}
/// <summary>
/// Instance group role in the cluster
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>MASTER, CORE, TASK</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string InstanceRole
{
get { return this.instanceRole; }
set { this.instanceRole = value; }
}
/// <summary>
/// Sets the InstanceRole property
/// </summary>
/// <param name="instanceRole">The value to set for the InstanceRole property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithInstanceRole(string instanceRole)
{
this.instanceRole = instanceRole;
return this;
}
// Check to see if InstanceRole property is set
internal bool IsSetInstanceRole()
{
return this.instanceRole != null;
}
/// <summary>
/// Bid price for EC2 Instances when launching nodes as Spot Instances, expressed in USD.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 256</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string BidPrice
{
get { return this.bidPrice; }
set { this.bidPrice = value; }
}
/// <summary>
/// Sets the BidPrice property
/// </summary>
/// <param name="bidPrice">The value to set for the BidPrice property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithBidPrice(string bidPrice)
{
this.bidPrice = bidPrice;
return this;
}
// Check to see if BidPrice property is set
internal bool IsSetBidPrice()
{
return this.bidPrice != null;
}
/// <summary>
/// Amazon EC2 Instance type.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 256</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string InstanceType
{
get { return this.instanceType; }
set { this.instanceType = value; }
}
/// <summary>
/// Sets the InstanceType property
/// </summary>
/// <param name="instanceType">The value to set for the InstanceType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithInstanceType(string instanceType)
{
this.instanceType = instanceType;
return this;
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this.instanceType != null;
}
/// <summary>
/// Target number of instances to run in the instance group.
///
/// </summary>
public int InstanceRequestCount
{
get { return this.instanceRequestCount ?? default(int); }
set { this.instanceRequestCount = value; }
}
/// <summary>
/// Sets the InstanceRequestCount property
/// </summary>
/// <param name="instanceRequestCount">The value to set for the InstanceRequestCount property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithInstanceRequestCount(int instanceRequestCount)
{
this.instanceRequestCount = instanceRequestCount;
return this;
}
// Check to see if InstanceRequestCount property is set
internal bool IsSetInstanceRequestCount()
{
return this.instanceRequestCount.HasValue;
}
/// <summary>
/// Actual count of running instances.
///
/// </summary>
public int InstanceRunningCount
{
get { return this.instanceRunningCount ?? default(int); }
set { this.instanceRunningCount = value; }
}
/// <summary>
/// Sets the InstanceRunningCount property
/// </summary>
/// <param name="instanceRunningCount">The value to set for the InstanceRunningCount property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithInstanceRunningCount(int instanceRunningCount)
{
this.instanceRunningCount = instanceRunningCount;
return this;
}
// Check to see if InstanceRunningCount property is set
internal bool IsSetInstanceRunningCount()
{
return this.instanceRunningCount.HasValue;
}
/// <summary>
/// State of instance group. The following values are deprecated: STARTING, TERMINATED, and FAILED.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>PROVISIONING, STARTING, BOOTSTRAPPING, RUNNING, RESIZING, ARRESTED, SHUTTING_DOWN, TERMINATED, FAILED, ENDED</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string State
{
get { return this.state; }
set { this.state = value; }
}
/// <summary>
/// Sets the State property
/// </summary>
/// <param name="state">The value to set for the State property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithState(string state)
{
this.state = state;
return this;
}
// Check to see if State property is set
internal bool IsSetState()
{
return this.state != null;
}
/// <summary>
/// Details regarding the state of the instance group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 10280</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string LastStateChangeReason
{
get { return this.lastStateChangeReason; }
set { this.lastStateChangeReason = value; }
}
/// <summary>
/// Sets the LastStateChangeReason property
/// </summary>
/// <param name="lastStateChangeReason">The value to set for the LastStateChangeReason property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithLastStateChangeReason(string lastStateChangeReason)
{
this.lastStateChangeReason = lastStateChangeReason;
return this;
}
// Check to see if LastStateChangeReason property is set
internal bool IsSetLastStateChangeReason()
{
return this.lastStateChangeReason != null;
}
/// <summary>
/// The date/time the instance group was created.
///
/// </summary>
public DateTime CreationDateTime
{
get { return this.creationDateTime ?? default(DateTime); }
set { this.creationDateTime = value; }
}
/// <summary>
/// Sets the CreationDateTime property
/// </summary>
/// <param name="creationDateTime">The value to set for the CreationDateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithCreationDateTime(DateTime creationDateTime)
{
this.creationDateTime = creationDateTime;
return this;
}
// Check to see if CreationDateTime property is set
internal bool IsSetCreationDateTime()
{
return this.creationDateTime.HasValue;
}
/// <summary>
/// The date/time the instance group was started.
///
/// </summary>
public DateTime StartDateTime
{
get { return this.startDateTime ?? default(DateTime); }
set { this.startDateTime = value; }
}
/// <summary>
/// Sets the StartDateTime property
/// </summary>
/// <param name="startDateTime">The value to set for the StartDateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithStartDateTime(DateTime startDateTime)
{
this.startDateTime = startDateTime;
return this;
}
// Check to see if StartDateTime property is set
internal bool IsSetStartDateTime()
{
return this.startDateTime.HasValue;
}
/// <summary>
/// The date/time the instance group was available to the cluster.
///
/// </summary>
public DateTime ReadyDateTime
{
get { return this.readyDateTime ?? default(DateTime); }
set { this.readyDateTime = value; }
}
/// <summary>
/// Sets the ReadyDateTime property
/// </summary>
/// <param name="readyDateTime">The value to set for the ReadyDateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithReadyDateTime(DateTime readyDateTime)
{
this.readyDateTime = readyDateTime;
return this;
}
// Check to see if ReadyDateTime property is set
internal bool IsSetReadyDateTime()
{
return this.readyDateTime.HasValue;
}
/// <summary>
/// The date/time the instance group was terminated.
///
/// </summary>
public DateTime EndDateTime
{
get { return this.endDateTime ?? default(DateTime); }
set { this.endDateTime = value; }
}
/// <summary>
/// Sets the EndDateTime property
/// </summary>
/// <param name="endDateTime">The value to set for the EndDateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceGroupDetail WithEndDateTime(DateTime endDateTime)
{
this.endDateTime = endDateTime;
return this;
}
// Check to see if EndDateTime property is set
internal bool IsSetEndDateTime()
{
return this.endDateTime.HasValue;
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Runtime.InteropServices;
using VSLangProj;
using VSLangProj80;
namespace Microsoft.VisualStudioTools.Project.Automation {
/// <summary>
/// Represents the automation equivalent of ReferenceNode
/// </summary>
/// <typeparam name="RefType"></typeparam>
[ComVisible(true)]
public abstract class OAReferenceBase : Reference3 {
#region fields
private ReferenceNode referenceNode;
#endregion
#region ctors
internal OAReferenceBase(ReferenceNode referenceNode) {
this.referenceNode = referenceNode;
}
#endregion
#region properties
internal ReferenceNode BaseReferenceNode {
get { return referenceNode; }
}
#endregion
#region Reference Members
public virtual int BuildNumber {
get { return 0; }
}
public virtual References Collection {
get {
return BaseReferenceNode.Parent.Object as References;
}
}
public virtual EnvDTE.Project ContainingProject {
get {
return BaseReferenceNode.ProjectMgr.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual bool CopyLocal {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public virtual string Culture {
get { throw new NotImplementedException(); }
}
public virtual EnvDTE.DTE DTE {
get {
return BaseReferenceNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
public virtual string Description {
get {
return this.Name;
}
}
public virtual string ExtenderCATID {
get { throw new NotImplementedException(); }
}
public virtual object ExtenderNames {
get { throw new NotImplementedException(); }
}
public virtual string Identity {
get { throw new NotImplementedException(); }
}
public virtual int MajorVersion {
get { return 0; }
}
public virtual int MinorVersion {
get { return 0; }
}
public virtual string Name {
get { throw new NotImplementedException(); }
}
public virtual string Path {
get {
return BaseReferenceNode.Url;
}
}
public virtual string PublicKeyToken {
get { throw new NotImplementedException(); }
}
public virtual void Remove() {
BaseReferenceNode.Remove(false);
}
public virtual int RevisionNumber {
get { return 0; }
}
public virtual EnvDTE.Project SourceProject {
get { return null; }
}
public virtual bool StrongName {
get { return false; }
}
public virtual prjReferenceType Type {
get { throw new NotImplementedException(); }
}
public virtual string Version {
get { return new Version().ToString(); }
}
public virtual object get_Extender(string ExtenderName) {
throw new NotImplementedException();
}
#endregion
public string Aliases {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public bool AutoReferenced {
get { throw new NotImplementedException(); }
}
public virtual bool Isolated {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public virtual uint RefType {
get {
// Default to native reference to help prevent callers from
// making incorrect assumptions
return (uint)__PROJECTREFERENCETYPE.PROJREFTYPE_NATIVE;
}
}
public virtual bool Resolved {
get { throw new NotImplementedException(); }
}
public string RuntimeVersion {
get { throw new NotImplementedException(); }
}
public virtual bool SpecificVersion {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public virtual string SubType {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Mathematical operations that can be performed on variables.
/// </summary>
public enum SetOperator
{
/// <summary> = operator. </summary>
Assign, //
/// <summary> =! operator. </summary>
Negate,
/// <summary> += operator. </summary>
Add,
/// <summary> -= operator. </summary>
Subtract,
/// <summary> *= operator. </summary>
Multiply,
/// <summary> /= operator. </summary>
Divide
}
/// <summary>
/// Sets a Boolean, Integer, Float or String variable to a new value using a simple arithmetic operation. The value can be a constant or reference another variable of the same type.
/// </summary>
[CommandInfo("Variable",
"Set Variable",
"Sets a Boolean, Integer, Float or String variable to a new value using a simple arithmetic operation. The value can be a constant or reference another variable of the same type.")]
[AddComponentMenu("")]
public class SetVariable : Command
{
[Tooltip("The variable whos value will be set")]
[VariableProperty(typeof(BooleanVariable),
typeof(IntegerVariable),
typeof(FloatVariable),
typeof(StringVariable))]
[SerializeField] protected Variable variable;
[Tooltip("The type of math operation to be performed")]
[SerializeField] protected SetOperator setOperator;
[Tooltip("Boolean value to set with")]
[SerializeField] protected BooleanData booleanData;
[Tooltip("Integer value to set with")]
[SerializeField] protected IntegerData integerData;
[Tooltip("Float value to set with")]
[SerializeField] protected FloatData floatData;
[Tooltip("String value to set with")]
[SerializeField] protected StringDataMulti stringData;
protected virtual void DoSetOperation()
{
if (variable == null)
{
return;
}
if (variable.GetType() == typeof(BooleanVariable))
{
BooleanVariable lhs = (variable as BooleanVariable);
bool rhs = booleanData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.Value = rhs;
break;
case SetOperator.Negate:
lhs.Value = !rhs;
break;
}
}
else if (variable.GetType() == typeof(IntegerVariable))
{
IntegerVariable lhs = (variable as IntegerVariable);
int rhs = integerData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.Value = rhs;
break;
case SetOperator.Add:
lhs.Value += rhs;
break;
case SetOperator.Subtract:
lhs.Value -= rhs;
break;
case SetOperator.Multiply:
lhs.Value *= rhs;
break;
case SetOperator.Divide:
lhs.Value /= rhs;
break;
}
}
else if (variable.GetType() == typeof(FloatVariable))
{
FloatVariable lhs = (variable as FloatVariable);
float rhs = floatData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.Value = rhs;
break;
case SetOperator.Add:
lhs.Value += rhs;
break;
case SetOperator.Subtract:
lhs.Value -= rhs;
break;
case SetOperator.Multiply:
lhs.Value *= rhs;
break;
case SetOperator.Divide:
lhs.Value /= rhs;
break;
}
}
else if (variable.GetType() == typeof(StringVariable))
{
StringVariable lhs = (variable as StringVariable);
string rhs = stringData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.Value = rhs;
break;
}
}
}
#region Public members
/// <summary>
/// The type of math operation to be performed.
/// </summary>
public virtual SetOperator _SetOperator { get { return setOperator; } }
public override void OnEnter()
{
DoSetOperation();
Continue();
}
public override string GetSummary()
{
if (variable == null)
{
return "Error: Variable not selected";
}
string description = variable.Key;
switch (setOperator)
{
default:
case SetOperator.Assign:
description += " = ";
break;
case SetOperator.Negate:
description += " =! ";
break;
case SetOperator.Add:
description += " += ";
break;
case SetOperator.Subtract:
description += " -= ";
break;
case SetOperator.Multiply:
description += " *= ";
break;
case SetOperator.Divide:
description += " /= ";
break;
}
if (variable.GetType() == typeof(BooleanVariable))
{
description += booleanData.GetDescription();
}
else if (variable.GetType() == typeof(IntegerVariable))
{
description += integerData.GetDescription();
}
else if (variable.GetType() == typeof(FloatVariable))
{
description += floatData.GetDescription();
}
else if (variable.GetType() == typeof(StringVariable))
{
description += stringData.GetDescription();
}
return description;
}
public override bool HasReference(Variable variable)
{
return (variable == this.variable);
}
public override Color GetButtonColor()
{
return new Color32(253, 253, 150, 255);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Alluvial
{
/// <summary>
/// Methods for working with stream catchups.
/// </summary>
public static class StreamCatchup
{
/// <summary>
/// Specifies an amount of time to wait if a stream produces no data.
/// </summary>
/// <typeparam name="TData">The type of the data in the stream.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="duration">The duration to wait.</param>
/// <returns></returns>
public static IDistributedStreamCatchup<TData, TPartition> Backoff<TData, TPartition>(
this IDistributedStreamCatchup<TData, TPartition> catchup,
TimeSpan duration)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
catchup.OnReceive(async (lease, next) =>
{
using (var counter = catchup.Count())
{
await next(lease);
if (counter.Value == 0)
{
await lease.ExpireIn(duration);
}
}
});
return catchup;
}
internal static Counter<TData> Count<TData>(
this IStreamCatchup<TData> catchup)
{
var counter = new Counter<TData>();
var subscription = catchup.Subscribe((_, batch) => counter.Add(batch).CompletedTask(),
NoCursor(counter));
counter.OnDispose(subscription);
return counter;
}
/// <summary>
/// Creates a catchup for the specified stream.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="initialCursor">The initial cursor from which the catchup proceeds.</param>
/// <param name="batchSize">The number of items to retrieve from the stream per batch.</param>
/// <returns></returns>
public static IStreamCatchup<TData> Create<TData, TCursor>(
IStream<TData, TCursor> stream,
ICursor<TCursor> initialCursor = null,
int? batchSize = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
return new SingleStreamCatchup<TData, TCursor>(
stream,
initialCursor,
batchSize);
}
/// <summary>
/// Creates a multiple-stream catchup.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the upstream cursor.</typeparam>
/// <typeparam name="TDownstreamCursor">The type of the downstream cursor.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="cursor">The initial cursor position for the catchup.</param>
/// <param name="batchSize">The number of items to retrieve from the stream per batch.</param>
public static IStreamCatchup<TData> All<TData, TUpstreamCursor, TDownstreamCursor>(
IStream<IStream<TData, TDownstreamCursor>, TUpstreamCursor> stream,
ICursor<TUpstreamCursor> cursor = null,
int? batchSize = null)
{
var upstreamCatchup = new SingleStreamCatchup<IStream<TData, TDownstreamCursor>, TUpstreamCursor>(stream, batchSize: batchSize);
return new MultiStreamCatchup<TData, TUpstreamCursor, TDownstreamCursor>(
upstreamCatchup,
cursor ?? stream.NewCursor());
}
/// <summary>
/// Creates a multiple-stream catchup.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the upstream cursor.</typeparam>
/// <typeparam name="TDownstreamCursor">The type of the downstream cursor.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="manageUpstreamCursor">A delegate to fetch and store the cursor each time the query is performed.</param>
/// <param name="batchSize">The number of items to retrieve from the stream per batch.</param>
public static IStreamCatchup<TData> All<TData, TUpstreamCursor, TDownstreamCursor>(
IStream<IStream<TData, TDownstreamCursor>, TUpstreamCursor> stream,
FetchAndSave<ICursor<TUpstreamCursor>> manageUpstreamCursor,
int? batchSize = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (manageUpstreamCursor == null)
{
throw new ArgumentNullException(nameof(manageUpstreamCursor));
}
var upstreamCatchup = new SingleStreamCatchup<IStream<TData, TDownstreamCursor>, TUpstreamCursor>(
stream,
batchSize: batchSize);
return new MultiStreamCatchup<TData, TUpstreamCursor, TDownstreamCursor>(
upstreamCatchup,
manageUpstreamCursor);
}
/// <summary>
/// Creates a multiple-stream catchup.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the upstream cursor.</typeparam>
/// <typeparam name="TDownstreamCursor">The type of the downstream cursor.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="upstreamCursorStore">A store for the upstream cursor.</param>
/// <param name="batchSize">The number of items to retrieve from the stream per batch.</param>
public static IStreamCatchup<TData> All<TData, TUpstreamCursor, TDownstreamCursor>(
IStream<IStream<TData, TDownstreamCursor>, TUpstreamCursor> stream,
IProjectionStore<string, ICursor<TUpstreamCursor>> upstreamCursorStore,
int? batchSize = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (upstreamCursorStore == null)
{
throw new ArgumentNullException(nameof(upstreamCursorStore));
}
var upstreamCatchup = new SingleStreamCatchup<IStream<TData, TDownstreamCursor>, TUpstreamCursor>(
stream,
batchSize: batchSize);
return new MultiStreamCatchup<TData, TUpstreamCursor, TDownstreamCursor>(
upstreamCatchup,
upstreamCursorStore.AsHandler());
}
/// <summary>
/// Distributes a stream catchup the among one or more partitions using a specified distributor.
/// </summary>
/// <remarks>If no distributor is provided, then distribution is done in-process.</remarks>
public static IDistributedStreamCatchup<TData, TPartition> CreateDistributedCatchup<TData, TCursor, TPartition>(
this IPartitionedStream<TData, TCursor, TPartition> streams,
IDistributor<IStreamQueryPartition<TPartition>> distributor,
int? batchSize = null,
FetchAndSave<ICursor<TCursor>> fetchAndSavePartitionCursor = null)
{
if (streams == null)
{
throw new ArgumentNullException(nameof(streams));
}
var catchup = new DistributedSingleStreamCatchup<TData, TCursor, TPartition>(
streams,
distributor,
batchSize,
fetchAndSavePartitionCursor);
return catchup;
}
/// <summary>
/// Distributes a stream catchup the among one or more partitions using a specified distributor.
/// </summary>
/// <remarks>If no distributor is provided, then distribution is done in-process.</remarks>
public static IDistributedStreamCatchup<TData, TPartition> CreateDistributedCatchup<TData, TUpstreamCursor, TDownstreamCursor, TPartition>(
this IPartitionedStream<IStream<TData, TDownstreamCursor>, TUpstreamCursor, TPartition> streams,
IDistributor<IStreamQueryPartition<TPartition>> distributor,
int? batchSize = null,
FetchAndSave<ICursor<TUpstreamCursor>> fetchAndSavePartitionCursor = null)
{
if (streams == null)
{
throw new ArgumentNullException(nameof(streams));
}
var catchup = new DistributedMultiStreamCatchup<TData, TUpstreamCursor, TDownstreamCursor, TPartition>(
streams,
distributor,
batchSize,
fetchAndSavePartitionCursor);
return catchup;
}
/// <summary>
/// Runs the catchup query until it reaches an empty batch, then stops.
/// </summary>
public static async Task RunUntilCaughtUp<TData>(
this IStreamCatchup<TData> catchup,
ILease lease = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
lease = lease ?? new Lease(TimeSpan.FromHours(4));
var leaseExpiration = lease.Expiration();
using (var counter = catchup.Count())
{
var countBefore = 0;
do
{
if (leaseExpiration.IsCompleted ||
leaseExpiration.IsCanceled ||
leaseExpiration.IsFaulted)
{
break;
}
countBefore = counter.Value;
await catchup.RunSingleBatch(lease);
} while (countBefore != counter.Value);
}
}
/// <summary>
/// Runs catchup batches repeatedly with a specified interval after each batch.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="pollInterval">The amount of time to wait after each batch is processed.</param>
/// <returns>A disposable that, when disposed, stops the polling.</returns>
public static IDisposable Poll<TData>(
this IStreamCatchup<TData> catchup,
TimeSpan pollInterval)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
var canceled = false;
Task.Run(async () =>
{
while (!canceled)
{
await catchup.RunSingleBatch(Lease.CreateDefault());
await Task.Delay(pollInterval);
}
});
return Disposable.Create(() => { canceled = true; });
}
/// <summary>
/// Consumes a single batch from the source stream and updates the subscribed aggregators.
/// </summary>
/// <param name="catchup">The catchup.</param>
/// <returns>
/// The updated cursor position after the batch is consumed.
/// </returns>
public static async Task RunSingleBatch<T>(this IStreamCatchup<T> catchup)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
await catchup.RunSingleBatch(Lease.CreateDefault());
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregator">The aggregator.</param>
/// <param name="projectionStore">The projection store.</param>
/// <param name="onError">A function to handle exceptions thrown during aggregation.</param>
/// <returns>A disposable that, when disposed, unsubscribes the aggregator.</returns>
public static IDisposable Subscribe<TProjection, TData>(
this IStreamCatchup<TData> catchup,
IStreamAggregator<TProjection, TData> aggregator,
IProjectionStore<string, TProjection> projectionStore = null,
HandleAggregatorError<TProjection> onError = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregator == null)
{
throw new ArgumentNullException(nameof(aggregator));
}
return catchup.Subscribe(aggregator,
projectionStore.AsHandler(),
onError);
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregator">The aggregator.</param>
/// <param name="manage">A delegate to fetch and store the projection each time the query is performed.</param>
/// <param name="onError">A function to handle exceptions thrown during aggregation.</param>
/// <returns>A disposable that, when disposed, unsubscribes the aggregator.</returns>
public static IDisposable Subscribe<TProjection, TData>(
this IStreamCatchup<TData> catchup,
IStreamAggregator<TProjection, TData> aggregator,
FetchAndSave<TProjection> manage,
HandleAggregatorError<TProjection> onError = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregator == null)
{
throw new ArgumentNullException(nameof(aggregator));
}
if (manage == null)
{
throw new ArgumentNullException(nameof(manage));
}
return catchup.SubscribeAggregator(aggregator,
manage,
onError);
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregate">A delegate that performs an aggregate operation on projections receiving new data.</param>
/// <param name="projectionStore">The projection store.</param>
/// <param name="onError">A function to handle exceptions thrown during aggregation.</param>
/// <returns>
/// A disposable that, when disposed, unsubscribes the aggregator.
/// </returns>
public static IDisposable Subscribe<TProjection, TData>(
this IStreamCatchup<TData> catchup,
Aggregate<TProjection, TData> aggregate,
IProjectionStore<string, TProjection> projectionStore = null,
HandleAggregatorError<TProjection> onError = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregate == null)
{
throw new ArgumentNullException(nameof(aggregate));
}
return catchup.Subscribe(Aggregator.Create(aggregate),
projectionStore.AsHandler(),
onError);
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregate">An aggregator function.</param>
/// <param name="manage">A delegate to fetch and store the projection each time the query is performed.</param>
/// <param name="onError">A function to handle exceptions thrown during aggregation.</param>
/// <returns>
/// A disposable that, when disposed, unsubscribes the aggregator.
/// </returns>
public static IDisposable Subscribe<TProjection, TData>(
this IStreamCatchup<TData> catchup,
Aggregate<TProjection, TData> aggregate,
FetchAndSave<TProjection> manage,
HandleAggregatorError<TProjection> onError = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregate == null)
{
throw new ArgumentNullException(nameof(aggregate));
}
if (manage == null)
{
throw new ArgumentNullException(nameof(manage));
}
return catchup.Subscribe(Aggregator.Create(aggregate), manage, onError);
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregate">A delegate that performs an aggregate operation on projections receiving new data.</param>
/// <param name="projectionStore">The projection store.</param>
/// <param name="onError">A function to handle exceptions thrown during aggregation.</param>
/// <returns>
/// A disposable that, when disposed, unsubscribes the aggregator.
/// </returns>
public static IDisposable Subscribe<TProjection, TData>(
this IStreamCatchup<TData> catchup,
AggregateAsync<TProjection, TData> aggregate,
IProjectionStore<string, TProjection> projectionStore = null,
HandleAggregatorError<TProjection> onError = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregate == null)
{
throw new ArgumentNullException(nameof(aggregate));
}
return catchup.Subscribe(Aggregator.Create(aggregate),
projectionStore.AsHandler(),
onError);
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregate">An aggregator function.</param>
/// <param name="manage">A delegate to fetch and store the projection each time the query is performed.</param>
/// <param name="onError">A function to handle exceptions thrown during aggregation.</param>
/// <returns>
/// A disposable that, when disposed, unsubscribes the aggregator.
/// </returns>
public static IDisposable Subscribe<TProjection, TData>(
this IStreamCatchup<TData> catchup,
AggregateAsync<TProjection, TData> aggregate,
FetchAndSave<TProjection> manage,
HandleAggregatorError<TProjection> onError = null)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregate == null)
{
throw new ArgumentNullException(nameof(aggregate));
}
if (manage == null)
{
throw new ArgumentNullException(nameof(manage));
}
return catchup.Subscribe(Aggregator.Create(aggregate), manage, onError);
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregate">A side-effecting aggregator function.</param>
/// <returns>A disposable that, when disposed, unsubscribes the aggregator.</returns>
public static IDisposable Subscribe<TData>(
this IStreamCatchup<TData> catchup,
Func<IStreamBatch<TData>, Task> aggregate)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregate == null)
{
throw new ArgumentNullException(nameof(aggregate));
}
return catchup.Subscribe(
Aggregator.Create<Projection<Unit, Unit>, TData>(async (p, b) =>
{
await aggregate(b);
return p;
}),
new InMemoryProjectionStore<Projection<Unit, Unit>>());
}
/// <summary>
/// Subscribes the specified aggregator to a catchup.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="catchup">The catchup.</param>
/// <param name="aggregate">A side-effecting aggregator function.</param>
/// <returns>A disposable that, when disposed, unsubscribes the aggregator.</returns>
public static IDisposable Subscribe<TData>(
this IStreamCatchup<TData> catchup,
Action<IStreamBatch<TData>> aggregate)
{
if (catchup == null)
{
throw new ArgumentNullException(nameof(catchup));
}
if (aggregate == null)
{
throw new ArgumentNullException(nameof(aggregate));
}
return catchup.Subscribe(
Aggregator.Create<Projection<Unit, Unit>, TData>((p, b) =>
{
aggregate(b);
return p;
}),
new InMemoryProjectionStore<Projection<Unit, Unit>>());
}
private static FetchAndSave<TProjection> NoCursor<TProjection>(TProjection projection) =>
(streamId, aggregate) => aggregate(projection);
internal class Counter<TCursor> : Projection<int>, IDisposable
{
private IDisposable onDispose;
public Counter<TCursor> Add(IStreamBatch<TCursor> batch)
{
Value += batch.Count;
return this;
}
public void OnDispose(IDisposable disposable)
{
if (onDispose != null)
{
onDispose = Disposable.Create(() =>
{
onDispose.Dispose();
disposable.Dispose();
});
}
else
{
onDispose = disposable;
}
}
public void Dispose() => onDispose?.Dispose();
}
internal static Wrapper<TData> Wrap<TData>(
this IStreamCatchup<TData> innerCatchup,
Func<ILease, Task> runSingleBatch,
[CallerMemberName] string caller = null)
{
return new Wrapper<TData>(innerCatchup,
runSingleBatch,
caller);
}
internal static Wrapper<TData, TPartition> Wrap<TData, TPartition>(
this IDistributedStreamCatchup<TData, TPartition> innerCatchup,
Func<ILease, Task> runSingleBatch,
[CallerMemberName] string caller = null)
{
return new Wrapper<TData, TPartition>(innerCatchup,
runSingleBatch,
caller);
}
internal class Wrapper<TData> : IStreamCatchup<TData>
{
private readonly IStreamCatchup<TData> inner;
private readonly Func<ILease, Task> runSingleBatch;
private readonly string caller;
public Wrapper(
IStreamCatchup<TData> inner,
Func<ILease, Task> runSingleBatch,
string caller)
{
if (inner == null)
{
throw new ArgumentNullException(nameof(inner));
}
if (runSingleBatch == null)
{
throw new ArgumentNullException(nameof(runSingleBatch));
}
this.inner = inner;
this.runSingleBatch = runSingleBatch;
var wrapper = inner as Wrapper<TData>;
if (wrapper != null)
{
caller = $"{wrapper.caller} -> {caller}";
}
this.caller = caller;
}
public IDisposable SubscribeAggregator<TProjection>(
IStreamAggregator<TProjection, TData> aggregator,
FetchAndSave<TProjection> fetchAndSave,
HandleAggregatorError<TProjection> onError)
=>
inner.SubscribeAggregator(aggregator,
fetchAndSave,
onError);
public Task RunSingleBatch(ILease lease) => runSingleBatch(lease);
public override string ToString()
{
return $"StreamCatchup {caller}";
}
}
internal class Wrapper<TData, TPartition> :
Wrapper<TData>,
IDistributedStreamCatchup<TData, TPartition>
{
private readonly IDistributedStreamCatchup<TData, TPartition> inner;
public Wrapper(
IDistributedStreamCatchup<TData, TPartition> inner,
Func<ILease, Task> runSingleBatch,
string caller) :
base(inner,
runSingleBatch,
caller)
{
this.inner = inner;
}
public void Dispose() => inner.Dispose();
public void OnReceive(DistributorPipeAsync<IStreamQueryPartition<TPartition>> onReceive) => inner.OnReceive(onReceive);
public void OnException(Action<Exception, Lease<IStreamQueryPartition<TPartition>>> onException) => inner.OnException(onException);
public Task Start() => inner.Start();
public Task<IEnumerable<IStreamQueryPartition<TPartition>>> Distribute(int count) => inner.Distribute(count);
public Task Stop() => inner.Stop();
}
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <mgorse@novell.com>
//
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
namespace Atspi
{
public class Text
{
private IText proxy;
private Properties properties;
private const string IFACE = "org.a11y.atspi.Text";
public Text (Accessible accessible)
{
ObjectPath op = new ObjectPath (accessible.path);
proxy = Registry.Bus.GetObject<IText> (accessible.application.name, op);
properties = Registry.Bus.GetObject<Properties> (accessible.application.name, op);
}
public string GetText ()
{
return proxy.GetText (0, -1);
}
public string GetText (int startOffset, int endOffset)
{
return proxy.GetText (startOffset, endOffset);
}
public bool SetCaretOffset (int offset)
{
return proxy.SetCaretOffset (offset);
}
public string GetTextBeforeOffset (int offset, BoundaryType type, out int startOffset, out int endOffset)
{
string text;
proxy.GetTextBeforeOffset (offset, type, out text, out startOffset, out endOffset);
return text;
}
public string GetTextAtOffset (int offset, BoundaryType type, out int startOffset, out int endOffset)
{
string text;
proxy.GetTextAtOffset (offset, type, out text, out startOffset, out endOffset);
return text;
}
public string GetTextAfterOffset (int offset, BoundaryType type, out int startOffset, out int endOffset)
{
string text;
proxy.GetTextAfterOffset (offset, type, out text, out startOffset, out endOffset);
return text;
}
public int GetCharacterAtOffset (int offset)
{
return proxy.GetCharacterAtOffset (offset);
}
public string GetAttributeValue (int offset, string attributeName, out int startOffset, out int endOffset, out bool defined)
{
string val;
proxy.GetAttributeValue (offset, attributeName, out val, out startOffset, out endOffset, out defined);
return val;
}
public void GetCharacterExtents (int offset, out int x, out int y, out int width, out int height, CoordType coordType)
{
proxy.GetCharacterExtents (offset, out x, out y, out width, out height, coordType);
}
public int GetOffsetAtPoint (int x, int y, CoordType coordType)
{
return proxy.GetOffsetAtPoint (x, y, coordType);
}
public int NSelections {
get { return proxy.GetNSelections (); }
}
public void GetSelection (int selectionNum, out int startOffset, out int endOffset)
{
proxy.GetSelection (selectionNum, out startOffset, out endOffset);
}
public bool AddSelection (int startOffset, int endOffset)
{
return proxy.AddSelection (startOffset, endOffset);
}
public bool RemoveSelection (int selectionNum)
{
return proxy.RemoveSelection (selectionNum);
}
public bool SetSelection (int selectionNum, int startOffset, int endOffset)
{
return proxy.SetSelection (selectionNum, startOffset, endOffset);
}
public void GetRangeExtents (int startOffset, int endOffset, out int x, out int y, out int width, out int height, CoordType coordType)
{
proxy.GetRangeExtents (startOffset, endOffset, out x, out y, out width, out height, coordType);
}
public RangeList [] GetBoundedRanges (int x, int y, int width, int height, CoordType coordType, ClipType xClipType, ClipType yClipType)
{
return proxy.GetBoundedRanges (x, y, width, height, coordType, xClipType, yClipType);
}
public IDictionary<string, string> GetAttributeRun (int offset, out int startOffset, out int endOffset, bool includeDefaults)
{
IDictionary<string, string> attributes;
proxy.GetAttributeRun (offset, out attributes, out startOffset, out endOffset, includeDefaults);
return attributes;
}
public IDictionary<string, string> GetDefaultAttributeSet ()
{
return proxy.GetDefaultAttributeSet ();
}
public int CharacterCount {
get {
return (int) properties.Get (IFACE, "CharacterCount");
}
}
public int CaretOffset {
get {
return (int) properties.Get (IFACE, "CaretOffset");
}
}
}
public struct TextDescription
{
public string Name;
public string Description;
public string KeyBinding;
}
public enum BoundaryType : uint
{
Char,
WordStart,
WordEnd,
SentenceStart,
SentenceEnd,
LineStart,
LineEnd
}
public enum ClipType : uint
{
None,
Min,
Max,
Both
}
public struct RangeList
{
public int StartOffset;
public int EndOffset;
public string Comment;
// TODO: How to map a variant? Is the below line correct?
public object unused;
}
[Interface ("org.a11y.atspi.Text")]
interface IText : Introspectable
{
string GetText (int startOffset, int endOffset);
bool SetCaretOffset (int offset);
void GetTextBeforeOffset (int offset, BoundaryType type, out string text, out int startOffset, out int endOffset);
void GetTextAtOffset (int offset, BoundaryType type, out string text, out int startOffset, out int endOffset);
void GetTextAfterOffset (int offset, BoundaryType type, out string text, out int startOffset, out int endOffset);
int GetCharacterAtOffset (int offset);
void GetAttributeValue (int offset, string attributeName, out string val, out int startOffset, out int endOffset, out bool defined);
void GetCharacterExtents (int offset, out int x, out int y, out int width, out int height, CoordType coordType);
int GetOffsetAtPoint (int x, int y, CoordType coordType);
int GetNSelections ();
void GetSelection (int selectionNum, out int startOffset, out int endOffset);
bool AddSelection (int startOffset, int endOffset);
bool RemoveSelection (int selectionNum);
bool SetSelection (int selectionNum, int startOffset, int endOffset);
void GetRangeExtents (int startOffset, int endOffset, out int x, out int y, out int width, out int height, CoordType coordType);
RangeList [] GetBoundedRanges (int x, int y, int width, int height, CoordType coordType, ClipType xClipType, ClipType yClipType);
void GetAttributeRun (int offset, out IDictionary<string, string> attributes, out int startOffset, out int endOffset, bool includeDefaults);
IDictionary<string, string> GetDefaultAttributeSet ();
}
}
| |
namespace CrystalMaiden
{
using System;
using System.Linq;
using System.Collections.Generic;
using Ensage;
using SharpDX;
using Ensage.Common.Extensions;
using Ensage.Common;
using Ensage.Common.Menu;
using static Toolset;
public class CrystalMaiden
{
private static void Main()
{
Events.OnLoad += (sender, args) =>
{
if (ObjectManager.LocalHero.ClassId != ClassId.CDOTA_Unit_Hero_CrystalMaiden) return;
me = ObjectManager.LocalHero;
Init();
Game.OnUpdate += Action;
Drawing.OnDraw += DrawUltiDamage;
};
Events.OnClose += (sender, args) =>
{
Drawing.OnDraw -= DrawUltiDamage;
me = null;
e = null;
Effect?.Dispose();
Effect = null;
Menus.RemoveFromMainMenu();
Game.OnUpdate -= Action;
};
}
private static void DrawingOnCore()
{
if (Menus.Item("Range Blink").GetValue<bool>() && blink != null)
{
blinkRange = 1200;
if (BlinkRange == null)
{
if (me.IsAlive)
{
BlinkRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
BlinkRange.SetControlPoint(3, new Vector3(5, 0, 0));
BlinkRange.SetControlPoint(2, new Vector3(255, 0, 222));
BlinkRange.SetControlPoint(1, new Vector3(blinkRange, 0, 222));
}
}
else
{
if (!me.IsAlive)
{
BlinkRange.Dispose();
BlinkRange = null;
}
else if (lastblinkRange != blinkRange)
{
BlinkRange.Dispose();
lastblinkRange = blinkRange;
BlinkRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
BlinkRange.SetControlPoint(3, new Vector3(5, 0, 0));
BlinkRange.SetControlPoint(2, new Vector3(255, 0, 222));
BlinkRange.SetControlPoint(1, new Vector3(blinkRange, 0, 222));
}
}
}
else
{
if (BlinkRange != null) BlinkRange.Dispose();
BlinkRange = null;
}
if (Menus.Item("Range Crystal Nova").GetValue<bool>() && Q != null && Q.Level > 0)
{
qRange = Q.GetCastRange();
if (QRange == null)
{
if (me.IsAlive)
{
QRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
QRange.SetControlPoint(3, new Vector3(5, 0, 0));
QRange.SetControlPoint(2, new Vector3(152, 92, 255));
QRange.SetControlPoint(1, new Vector3(qRange, 0, 222));
}
}
else
{
if (!me.IsAlive)
{
QRange.Dispose();
QRange = null;
}
else if (lastqRange != qRange)
{
QRange.Dispose();
lastqRange = qRange;
QRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
QRange.SetControlPoint(3, new Vector3(5, 0, 0));
QRange.SetControlPoint(2, new Vector3(152, 92, 255));
QRange.SetControlPoint(1, new Vector3(qRange, 0, 222));
}
}
}
else
{
if (QRange != null) QRange.Dispose();
QRange = null;
}
if (Menus.Item("Range Frostbite").GetValue<bool>() && W != null && W.Level > 0)
{
wRange = W.GetCastRange();
if (WRange == null)
{
if (me.IsAlive)
{
WRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
WRange.SetControlPoint(3, new Vector3(5, 0, 0));
WRange.SetControlPoint(2, new Vector3(64, 224, 208));
WRange.SetControlPoint(1, new Vector3(wRange, 0, 222));
}
}
else
{
if (!me.IsAlive)
{
WRange.Dispose();
WRange = null;
}
else if (lastwRange != wRange)
{
WRange.Dispose();
lastwRange = wRange;
WRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
WRange.SetControlPoint(3, new Vector3(5, 0, 0));
WRange.SetControlPoint(2, new Vector3(64, 224, 208));
WRange.SetControlPoint(1, new Vector3(wRange, 0, 222));
}
}
}
else
{
if (WRange != null) WRange.Dispose();
WRange = null;
}
if (Menus.Item("Range Freezing Field").GetValue<bool>() && R != null && R.Level >0)
{
rRange = R.GetCastRange();
if (RRange == null)
{
if (me.IsAlive)
{
RRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
RRange.SetControlPoint(3, new Vector3(5, 0, 0));
RRange.SetControlPoint(2, new Vector3(255, 0, 22));
RRange.SetControlPoint(1, new Vector3(rRange, 0, 222));
}
}
else
{
if (!me.IsAlive)
{
RRange.Dispose();
RRange = null;
}
else if (lastrRange != rRange)
{
RRange.Dispose();
lastrRange = rRange;
RRange = me.AddParticleEffect("materials/ensage_ui/particles/range_display_mod.vpcf");
RRange.SetControlPoint(3, new Vector3(5, 0, 0));
RRange.SetControlPoint(2, new Vector3(255, 0, 22));
RRange.SetControlPoint(1, new Vector3(rRange, 0, 222));
}
}
}
else
{
if (RRange != null) RRange.Dispose();
RRange = null;
}
}
private static void Action(EventArgs args)
{
Q = me.Spellbook.SpellQ;
W = me.Spellbook.SpellW;
R = me.Spellbook.SpellR;
// Item
ethereal = me.FindItem("item_ethereal_blade");
cyclone = me.FindItem("item_cyclone");
force = me.FindItem("item_force_staff");
urn = me.FindItem("item_urn_of_shadows");
glimmer = me.FindItem("item_glimmer_cape");
bkb = me.FindItem("item_black_king_bar");
mail = me.FindItem("item_blade_mail");
lotus = me.FindItem("item_lotus_orb");
vail = me.FindItem("item_veil_of_discord");
cheese = me.FindItem("item_cheese");
ghost = me.FindItem("item_ghost");
orchid = me.FindItem("item_orchid") ?? me.FindItem("item_bloodthorn");
atos = me.FindItem("item_rod_of_atos");
soul = me.FindItem("item_soul_ring");
arcane = me.FindItem("item_arcane_boots");
blink = me.FindItem("item_blink");
shiva = me.FindItem("item_shivas_guard");
shadB = me.FindItem("item_silver_edge") ?? me.FindItem("item_invis_sword");
dagon = me.Inventory.Items.FirstOrDefault(item => item.Name.Contains("item_dagon"));
e = TargetSelector.ClosestToMouse(me);
if (e == null || !e.IsValid || !e.IsAlive) return;
if (Effect == null || !Effect.IsValid)
{
Effect = new ParticleEffect(@"particles\ui_mouseactions\range_finder_tower_aoe.vpcf", e);
Effect.SetControlPoint(2, new Vector3(me.Position.X, me.Position.Y, me.Position.Z));
Effect.SetControlPoint(6, new Vector3(1, 0, 0));
Effect.SetControlPoint(7, new Vector3(e.Position.X, e.Position.Y, e.Position.Z));
}
else
{
Effect.SetControlPoint(2, new Vector3(me.Position.X, me.Position.Y, me.Position.Z));
Effect.SetControlPoint(6, new Vector3(1, 0, 0));
Effect.SetControlPoint(7, new Vector3(e.Position.X, e.Position.Y, e.Position.Z));
}
Active = Game.IsKeyDown(Menus.Item("keyBind").GetValue<KeyBind>().Key);
var noUlty = !R.IsInAbilityPhase && !R.IsChanneling && !me.IsChanneling() &&
!me.HasModifier("modifier_crystal_maiden_freezing_field");
if (Menus.Item("autoUlt").IsActive() && me.IsAlive)
{
AutoAbilities();
}
if (Menus.Item("AutoUsage").IsActive())
{
AutoSpells();
}
if (Active && noUlty)
{
try
{
var enemies = ObjectManager.GetEntities<Hero>()
.Where(x => x.IsAlive && x.Team != me.Team && !x.IsIllusion && !x.IsMagicImmune()
&& (!x.HasModifier("modifier_abaddon_borrowed_time")
|| !x.HasModifier("modifier_item_blade_mail_reflect")))
.ToList();
if (e.HasModifier("modifier_abaddon_borrowed_time")
|| e.HasModifier("modifier_item_blade_mail_reflect")
|| e.IsMagicImmune())
{
e = GetClosestToTarget(enemies, e) ?? null;
if (Utils.SleepCheck("spam"))
{
Utils.Sleep(5000, "spam");
}
}
if (e == null) return;
//spell
sheep = e.ClassId == ClassId.CDOTA_Unit_Hero_Tidehunter ? null : me.FindItem("item_sheepstick");
var stoneModif = e.HasModifier("modifier_medusa_stone_gaze_stone");
var stayHere = e.HasModifiers(new[]
{
"modifier_rod_of_atos_debuff",
"modifier_crystal_maiden_frostbite"
}, false);
var ally = ObjectManager.GetEntities<Hero>().Where(x => x.IsAlive && x.Team == me.Team && !x.IsIllusion).ToList();
var n = GetClosestToTarget(ally, e);
if (me.IsAlive && e.IsAlive && me.CanCast() && me.Distance2D(e)<= 1400 && Utils.SleepCheck("combosleep"))
{
Utils.Sleep(350, "combosleep");
if (R.IsInAbilityPhase || R.IsChanneling || me.IsChanneling())
return;
if (stoneModif) return;
//var noBlade = e.HasModifier("modifier_item_blade_mail_reflect");
if (e.IsVisible && me.Distance2D(e) <= 2300)
{
var distance = me.IsVisibleToEnemies ? 1400 : W.GetCastRange() + me.HullRadius;
float angle = me.FindAngleBetween(e.Position, true);
Vector3 pos = new Vector3((float)(e.Position.X - 250 * Math.Cos(angle)),
(float)(e.Position.Y - 250 * Math.Sin(angle)), 0);
if (e.IsLinkensProtected())
linken(e);
if (
// cheese
cheese != null
&& cheese.CanBeCasted()
&& me.Health <= me.MaximumHealth * 0.3
&& me.Distance2D(e) <= 700
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(cheese.Name)
)
cheese.UseAbility();
if ( // SoulRing Item
soul != null
&& soul.CanBeCasted()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(soul.Name)
&& me.CanCast()
&& me.Health >= me.MaximumHealth * 0.4
&& me.Mana <= R.ManaCost
)
soul.UseAbility();
if ( // Arcane Boots Item
arcane != null
&& arcane.CanBeCasted()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(arcane.Name)
&& me.CanCast()
&& me.Mana <= me.MaximumMana * 0.5
)
arcane.UseAbility();
if ( //Ghost
ghost != null
&& ghost.CanBeCasted()
&& me.CanCast()
&& me.Distance2D(e) < me.AttackRange
&& (me.Health <= me.MaximumHealth * 0.5
|| ((enemies.Count(x => x.Distance2D(me) <= 650) <=
Menus.Item("Heel").GetValue<Slider>().Value
|| !Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(bkb.Name)
|| bkb == null || !bkb.CanBeCasted())
&& R.CanBeCasted() && Menus.Item("Skills").GetValue<AbilityToggler>().IsEnabled(R.Name)))
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(ghost.Name)
&& !me.IsMagicImmune()
)
ghost.UseAbility();
if (blink != null
&& W.CanBeCasted()
&& me.CanCast()
&& blink.CanBeCasted()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(blink.Name)
&& me.Distance2D(e) >= 490
&& me.Distance2D(pos) <= 1180
)
blink.UseAbility(pos);
uint elsecount = 0;
elsecount += 1;
if (elsecount == 1
&& urn != null && urn.CanBeCasted() && urn.CurrentCharges > 0
&& me.Distance2D(e) <= urn.GetCastRange()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(urn.Name)
)
urn.UseAbility(e);
else elsecount += 1;
if (elsecount == 2
&& glimmer != null
&& glimmer.CanBeCasted()
&& me.Distance2D(e) <= 900
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(glimmer.Name)
)
glimmer.UseAbility(me);
else elsecount += 1;
if (elsecount == 3
&& mail != null
&& mail.CanBeCasted()
&& enemies.Count(x => x.Distance2D(me) <= 700) >=
Menus.Item("Heel").GetValue<Slider>().Value
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(mail.Name)
)
mail.UseAbility();
else elsecount += 1;
if (elsecount == 4
&& bkb != null
&& bkb.CanBeCasted()
&& enemies.Count(x => x.Distance2D(me) <= 700) >=
Menus.Item("Heel").GetValue<Slider>().Value
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(bkb.Name)
)
bkb.UseAbility();
else elsecount += 1;
if (elsecount == 5
&& lotus != null
&& lotus.CanBeCasted()
&& enemies.Count(x => x.Distance2D(me) <= 700) >= 1
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(lotus.Name)
)
lotus.UseAbility(me);
else elsecount += 1;
if (elsecount == 6
&& sheep != null
&& sheep.CanBeCasted()
&& me.CanCast()
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(sheep.Name)
)
sheep.UseAbility(e);
else elsecount += 1;
if (elsecount == 7
&& vail != null
&& vail.CanBeCasted()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(vail.Name)
&& me.CanCast()
&& !e.IsMagicImmune()
&& (me.Distance2D(e) < Q.GetCastRange()+50
|| n.Distance2D(e) <= 300 && me.Distance2D(e) <= 1200)
)
vail.UseAbility(e.Position);
else elsecount += 1;
if (elsecount == 8
&& orchid != null
&& orchid.CanBeCasted()
&& me.CanCast()
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled("item_bloodthorn")
)
orchid.UseAbility(e);
else elsecount += 1;
if (elsecount == 9
&& ethereal != null
&& ethereal.CanBeCasted()
&& me.CanCast()
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(ethereal.Name)
)
{
if (Menus.Item("debuff").GetValue<bool>())
{
var speed = ethereal.GetAbilityData("projectile_speed");
var time = e.Distance2D(me) / speed;
Utils.Sleep((int)(time * 1000.0f + Game.Ping) + 30, "combosleep");
ethereal.UseAbility(e);
}
else
{
ethereal.UseAbility(e);
Utils.Sleep(130, "combosleep");
}
}
else elsecount += 1;
if (elsecount == 10
&& Q != null
&& Q.CanBeCasted()
&& Menus.Item("Skills").GetValue<AbilityToggler>().IsEnabled(Q.Name)
&& me.CanCast()
&& !e.IsMagicImmune()
)
Q.UseAbility(e.Position);
elsecount += 1;
if (elsecount == 11
&& atos != null
&& atos.CanBeCasted()
&& me.CanCast()
&& !stayHere
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(atos.Name)
&& (me.Distance2D(e) < distance
|| n.Distance2D(e) <= 300 && me.Distance2D(e) <= 1400
|| me.Distance2D(e) <= Menus.Item("atosRange").GetValue<Slider>().Value)
)
atos.UseAbility(e);
else elsecount += 1;
if (elsecount == 12
&& W != null
&& W.CanBeCasted()
&& me.CanCast()
&& !stayHere
&& !e.IsMagicImmune()
&& Menus.Item("Skills").GetValue<AbilityToggler>().IsEnabled(W.Name)
)
W.UseAbility(e);
else elsecount += 1;
if (elsecount == 13
&& shiva != null
&& shiva.CanBeCasted()
&& me.CanCast()
&& !e.IsMagicImmune()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled(shiva.Name)
&& me.Distance2D(e) <= 600
)
shiva.UseAbility();
else elsecount += 1;
if (elsecount == 14
&& dagon != null
&& dagon.CanBeCasted()
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled("item_dagon")
&& me.CanCast()
&& (ethereal == null
|| e.HasModifier("modifier_item_ethereal_blade_slow")
|| ethereal.Cooldown < 17)
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
)
dagon.UseAbility(e);
else elsecount += 1;
if (elsecount == 15
&& R != null
&& R.CanBeCasted()
&& me.Distance2D(e) <= R.GetCastRange() - 100
&& !me.HasModifier("modifier_pugna_nether_ward_aura")
&& (e.HasModifiers(new[]
{
"modifier_rod_of_atos_debuff",
"modifier_meepo_earthbind",
"modifier_pudge_dismember",
"modifier_lone_druid_spirit_bear_entangle_effect",
"modifier_legion_commander_duel",
"modifier_kunkka_torrent",
"modifier_ice_blast",
"modifier_crystal_maiden_crystal_nova",
"modifier_enigma_black_hole_pull",
"modifier_ember_spirit_searing_chains",
"modifier_dark_troll_warlord_ensnare",
"modifier_crystal_maiden_frostbite",
"modifier_axe_berserkers_call",
"modifier_bane_fiends_grip",
"modifier_faceless_void_chronosphere_freeze",
"modifier_storm_spirit_electric_vortex_pull",
"modifier_naga_siren_ensnare"
}, false)
|| e.ClassId != ClassId.CDOTA_Unit_Hero_FacelessVoid
&& !e.HasModifier("modifier_faceless_void_chronosphere_freeze")
|| e.IsStunned()
|| e.IsHexed()
|| e.IsRooted())
&& !e.HasModifiers(new[]
{
"modifier_medusa_stone_gaze_stone",
"modifier_faceless_void_time_walk",
"modifier_item_monkey_king_bar",
"modifier_rattletrap_battery_assault",
"modifier_item_blade_mail_reflect",
"crystal_maiden_frostbite",
"modifier_pudge_meat_hook",
"modifier_zuus_lightningbolt_vision_thinker",
"modifier_puck_phase_shift",
"modifier_eul_cyclone",
"modifier_dazzle_shallow_grave",
"modifier_mirana_leap",
"modifier_abaddon_borrowed_time",
"modifier_winter_wyvern_winters_curse",
"modifier_earth_spirit_rolling_boulder_caster",
"modifier_brewmaster_storm_cyclone",
"modifier_spirit_breaker_charge_of_darkness",
"modifier_shadow_demon_disruption",
"modifier_tusk_snowball_movement",
"modifier_invoker_tornado",
"modifier_obsidian_destroyer_astral_imprisonment_prison"
}, false)
&& (e.FindSpell("abaddon_borrowed_time")?.Cooldown > 0
|| e.FindSpell("abaddon_borrowed_time") == null)
&& !e.IsMagicImmune()
&& e.Health >= e.MaximumHealth / 100 * Menus.Item("Healh").GetValue<Slider>().Value
&& Menus.Item("Skills").GetValue<AbilityToggler>().IsEnabled(R.Name)
)
{
R.UseAbility();
}
else elsecount += 1;
if (elsecount == 16
&& shadB != null
&& shadB.CanBeCasted()
&& me.CanCast()
&& !e.IsMagicImmune()
&& me.HasModifier("modifier_crystal_maiden_freezing_field")
&& Menus.Item("Items").GetValue<AbilityToggler>().IsEnabled("item_silver_edge")
&& me.Distance2D(e) <= 900
)
shadB.UseAbility();
//try
//{
if (Menus.Item("orbwalk").GetValue<bool>())
{
var modifInv = me.IsInvisible();
var range = modifInv
? me.Distance2D(e) <= me.GetAttackRange() / 100 * Menus.Item("range").GetValue<Slider>().Value
: me.Distance2D(e) >= me.GetAttackRange() / 100 * Menus.Item("range").GetValue<Slider>().Value;
if (!e.IsAttackImmune() && range)
{
Orbwalking.Orbwalk(e, 0, 1600, false, true);
}
else if (!e.IsAttackImmune() && me.Distance2D(e) <= me.GetAttackRange() / 100 * Menus.Item("range").GetValue<Slider>().Value && !e.IsAttackImmune() && Utils.SleepCheck("attack"))
{
Orbwalking.Orbwalk(e, 0, 1600, false, false);
}
}
}
}
}
catch (Exception ex)
{
var st = new System.Diagnostics.StackTrace(ex, true);
var line = st.GetFrame(0).GetFileLineNumber();
Console.WriteLine("Combo exception at line: " + line);
}
}
}
public static void linken(Hero z)
{
W = me.Spellbook.SpellW;
cyclone = me.FindItem("item_cyclone");
force = me.FindItem("item_force_staff");
atos = me.FindItem("item_rod_of_atos");
sheep = me.FindItem("item_sheepstick");
dagon = me.Inventory.Items.FirstOrDefault(item => item.Name.Contains("item_dagon"));
if ((cyclone.CanBeCasted() || force.CanBeCasted()
|| sheep.CanBeCasted() || atos.CanBeCasted() || W.CanBeCasted())
&& me.Distance2D(z)<=900 && Utils.SleepCheck("Combo2"))
{
Utils.Sleep(200, "Combo2");
if (cyclone != null && cyclone.CanBeCasted()
&& Menus.Item("Link").GetValue<AbilityToggler>().IsEnabled(cyclone.Name))
cyclone.UseAbility(z);
else if (force != null && force.CanBeCasted() &&
Menus.Item("Link").GetValue<AbilityToggler>().IsEnabled(force.Name))
force.UseAbility(z);
else if(W != null && W.CanBeCasted() &&
Menus.Item("Link").GetValue<AbilityToggler>().IsEnabled(W.Name)
&& !me.IsMagicImmune())
W.UseAbility(z);
else if(atos != null && atos.CanBeCasted()
&& Menus.Item("Link").GetValue<AbilityToggler>().IsEnabled(atos.Name))
atos.UseAbility(z);
else if (sheep != null && sheep.CanBeCasted()
&& Menus.Item("Link").GetValue<AbilityToggler>().IsEnabled(sheep.Name))
sheep.UseAbility(z);
}
}
private static void AutoAbilities()
{
try
{
W = me.Spellbook.SpellW;
R = me.Spellbook.SpellR;
// Item
cyclone = me.FindItem("item_cyclone");
force = me.FindItem("item_force_staff");
glimmer = me.FindItem("item_glimmer_cape");
bkb = me.FindItem("item_black_king_bar");
ghost = me.FindItem("item_ghost");
atos = me.FindItem("item_rod_of_atos");
shadB = me.FindItem("item_silver_edge") ?? me.FindItem("item_invis_sword");
dagon = me.Inventory.Items.FirstOrDefault(item => item.Name.Contains("item_dagon"));
var v = ObjectManager.GetEntities<Hero>()
.Where(x => x.IsVisible && x.IsAlive && x.Team != me.Team && !x.IsIllusion).ToList();
if (shadB != null
&& shadB.CanBeCasted()
&& me.CanCast()
&& !e.IsMagicImmune()
&& me.HasModifier("modifier_crystal_maiden_freezing_field")
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled("item_silver_edge")
&& me.Distance2D(e) <= 900
&& Utils.SleepCheck("combosleep")
)
{
shadB.UseAbility();
Utils.Sleep(150, "combosleep");
}
if (glimmer != null
&& glimmer.CanBeCasted()
&& me.Distance2D(e) <= 900
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(glimmer.Name)
&& me.HasModifier("modifier_crystal_maiden_freezing_field")
&& Utils.SleepCheck("combosleep")
)
{
glimmer.UseAbility(me);
Utils.Sleep(150, "combosleep");
}
if ( Game.Ping <= 200
&& R != null
&& R.CanBeCasted()
&& R.IsInAbilityPhase
&& me.Distance2D(e) <= R.GetCastRange()
&& Utils.SleepCheck("combosleep")
)
{
Utils.Sleep(150, "combosleep");
if (bkb != null
&& bkb.CanBeCasted()
&& v.Count(x => x.Distance2D(me) <= 650) >=
Menus.Item("Heel").GetValue<Slider>().Value
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(bkb.Name)
)
{
me.Stop();
bkb.UseAbility();
R.UseAbility();
}
if (ghost != null
&& ghost.CanBeCasted()
&& !me.IsMagicImmune()
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(ghost.Name)
&& (bkb == null
|| !bkb.CanBeCasted()
|| v.Count(x => x.Distance2D(me) <= 650) <= Menus.Item("Heel").GetValue<Slider>().Value
|| !Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(bkb.Name))
)
{
me.Stop();
ghost.UseAbility();
R.UseAbility();
}
}
if (Active) return;
if (R.IsInAbilityPhase || R.IsChanneling || me.IsChanneling())
return;
var ecount = v.Count;
if (ecount <= 0)
{
foreach (var z in v)
{
var stayHere = z.HasModifiers(new[]
{
"modifier_rod_of_atos_debuff",
"modifier_crystal_maiden_frostbite"
}, false);
if (me.HasModifier("modifier_spirit_breaker_charge_of_darkness_vision"))
{
if (z.ClassId == ClassId.CDOTA_Unit_Hero_SpiritBreaker)
{
if (W != null && W.CanBeCasted() && me.Distance2D(z) <= W.GetCastRange() + me.HullRadius
&& !z.IsMagicImmune()
&& !stayHere
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(W.Name)
)
{
W.UseAbility(z);
}
else if (atos != null
&& atos.CanBeCasted()
&& me.Distance2D(z) <= W.GetCastRange() + me.HullRadius
&& !z.IsMagicImmune()
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(atos.Name)
)
{
atos.UseAbility(z);
}
}
}
if (W != null && W.CanBeCasted() && me.Distance2D(z) <= 500
&& z.Distance2D(me) <= me.HullRadius + 50
&& !stayHere
&& z.NetworkActivity == NetworkActivity.Attack
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(W.Name)
&& !z.IsMagicImmune()
)
{
W.UseAbility(e);
}
if (W != null && W.CanBeCasted() && me.Distance2D(z) <= W.GetCastRange() + me.HullRadius + 24
&& !z.IsLinkensProtected()
&&
!z.HasModifiers(new[]
{
"modifier_rod_of_atos_debuff",
"modifier_shadow_shaman_shackles",
"modifier_winter_wyvern_cold_embrace",
"modifier_storm_spirit_electric_vortex_pull",
"modifier_rubick_telekinesis",
"modifier_bane_fiends_grip",
"modifier_axe_berserkers_call",
"modifier_crystal_maiden_crystal_nova",
"modifier_dark_troll_warlord_ensnare",
"modifier_ember_spirit_searing_chains",
"modifier_enigma_black_hole_pull",
"modifier_ice_blast",
"modifier_kunkka_torrent",
"modifier_legion_commander_duel",
"modifier_lone_druid_spirit_bear_entangle_effect",
"modifier_naga_siren_ensnare",
"modifier_pudge_dismember",
"modifier_meepo_earthbind"
}, false)
&& (z.FindSpell("magnataur_reverse_polarity").IsInAbilityPhase
|| z.FindItem("item_blink")?.Cooldown > 11
|| z.FindSpell("queenofpain_blink").IsInAbilityPhase
|| z.FindSpell("antimage_blink").IsInAbilityPhase
|| z.FindSpell("antimage_mana_void").IsInAbilityPhase
|| z.FindSpell("legion_commander_duel")?.Cooldown <= 0
|| z.FindSpell("doom_bringer_doom").IsInAbilityPhase
|| z.HasModifier("modifier_faceless_void_chronosphere_freeze")
|| z.FindSpell("witch_doctor_death_ward").IsInAbilityPhase
|| z.FindSpell("rattletrap_power_cogs").IsInAbilityPhase
|| z.FindSpell("tidehunter_ravage").IsInAbilityPhase
|| z.FindSpell("axe_berserkers_call").IsInAbilityPhase
|| z.FindSpell("brewmaster_primal_split").IsInAbilityPhase
|| z.FindSpell("omniknight_guardian_angel").IsInAbilityPhase
|| z.FindSpell("queenofpain_sonic_wave").IsInAbilityPhase
|| z.FindSpell("sandking_epicenter").IsInAbilityPhase
|| z.FindSpell("slardar_slithereen_crush").IsInAbilityPhase
|| z.FindSpell("tiny_toss").IsInAbilityPhase
|| z.FindSpell("tusk_walrus_punch").IsInAbilityPhase
|| z.FindSpell("faceless_void_time_walk").IsInAbilityPhase
|| z.FindSpell("faceless_void_chronosphere").IsInAbilityPhase
|| z.FindSpell("disruptor_static_storm")?.Cooldown <= 0
|| z.FindSpell("lion_finger_of_death")?.Cooldown <= 0
|| z.FindSpell("luna_eclipse")?.Cooldown <= 0
|| z.FindSpell("lina_laguna_blade")?.Cooldown <= 0
|| z.FindSpell("doom_bringer_doom")?.Cooldown <= 0
|| z.FindSpell("life_stealer_rage")?.Cooldown <= 0
&& me.Level >= 7
)
&& (z.FindItem("item_manta")?.Cooldown > 0
|| z.FindItem("item_manta") == null || z.IsStunned() || z.IsHexed() || z.IsRooted())
&& !z.IsMagicImmune()
&& Menus.Item("AutoAbility").GetValue<AbilityToggler>().IsEnabled(W.Name)
&& !z.HasModifier("modifier_medusa_stone_gaze_stone")
)
{
W.UseAbility(z);
}
}
}
}
catch (Exception ex)
{
var st = new System.Diagnostics.StackTrace(ex, true);
var line = st.GetFrame(0).GetFileLineNumber();
Console.WriteLine("AutoAbilities exception at line: " + line);
}
}
private static bool IsDisembodied(Unit target)
{
string[] modifs =
{
"modifier_item_ethereal_blade_ethereal",
"modifier_pugna_decrepify"
};
return target.HasModifiers(modifs);
}
private static bool CanIncreaseMagicDmg(Hero source, Hero target)
{
//var orchid = source.FindItem("item_orchid") ?? source.FindItem("item_bloodthorn");
var veil = source.FindItem("item_veil_of_discord");
ethereal = source.FindItem("item_ethereal_blade");
return (//(orchid != null && orchid.CanBeCasted() && !target.HasModifier("modifier_orchid_malevolence_debuff"))||
(veil != null && veil.CanBeCasted() && !target.HasModifier("modifier_item_veil_of_discord_debuff"))
|| (ethereal != null && ethereal.CanBeCasted() && !IsDisembodied(target))
)
&& source.CanUseItems();
}
private static void AutoSpells()
{
enemies = ObjectManager.GetEntities<Hero>()
.Where(x => x.IsVisible && x.IsAlive && x.Team != me.Team && !x.IsMagicImmune() && !x.IsMagicImmune() && !x.IsIllusion && !x.IsMagicImmune()).ToList();
e = TargetSelector.ClosestToMouse(me,8000);
if (e == null || !e.IsValid || !e.IsAlive) return;
Q = me.Spellbook.SpellQ;
W = me.Spellbook.SpellW;
// Item
ethereal = me.FindItem("item_ethereal_blade");
vail = me.FindItem("item_veil_of_discord");
orchid = me.FindItem("item_orchid") ?? me.FindItem("item_bloodthorn");
atos = me.FindItem("item_rod_of_atos");
blink = me.FindItem("item_blink");
shiva = me.FindItem("item_shivas_guard");
dagon = me.Inventory.Items.FirstOrDefault(item => item.Name.Contains("item_dagon"));
foreach (var v in enemies)
{
if (me.IsInvisible()) return;
if (v.IsMagicImmune()) return;
if (R.IsInAbilityPhase || R.IsChanneling || me.IsChanneling())
return;
if (v.IsLinkensProtected() && Menus.Item("autoLink").IsActive())
{
linken(v);
}
damage[v.Handle] = CalculateDamage(v);
var Range = me.HullRadius + Q?.GetCastRange()+200;
var stayHere = v.HasModifiers(new[]
{
"modifier_rod_of_atos_debuff",
"modifier_crystal_maiden_frostbite"
}, false);
float angle = me.FindAngleBetween(v.Position, true);
Vector3 pos = new Vector3((float)(v.Position.X - 200 * Math.Cos(angle)), (float)(v.Position.Y - 200 * Math.Sin(angle)), 0);
Vector3 posBlink = new Vector3((float)(v.Position.X - Range * Math.Cos(angle)), (float)(v.Position.Y - Range * Math.Sin(angle)), 0);
if (Utils.SleepCheck("steal"))
{
Utils.Sleep(250, "steal");
uint elsecount = 0;
elsecount += 1;
if (elsecount == 1
&& enemies.Count(
x => x.Distance2D(v) <= 500) <= Menus.Item("solo_kill").GetValue<Slider>().Value
&& blink != null
&& blink.CanBeCasted()
&& me.CanCast()
&& me.Health >= (me.MaximumHealth / 100 * Menus.Item("minHealth").GetValue<Slider>().Value)
&& v.Health <= damage[v.Handle]
&& me.Distance2D(pos) <= 1180
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(blink.Name)
&& me.Distance2D(v) > 500
)
blink.UseAbility(pos);
if (v.Health <= damage[v.Handle] && me.Distance2D(v) <= Range)
{
elsecount += 1;
if (elsecount == 2
&& orchid != null
&& orchid.CanBeCasted()
&& me.CanCast()
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled("item_bloodthorn")
)
orchid.UseAbility(e);
elsecount += 1;
if (elsecount == 3
&& atos != null
&& !stayHere
&& atos.CanBeCasted()
&& me.CanCast()
&& !e.IsLinkensProtected()
&& !e.IsMagicImmune()
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(atos.Name)
&& me.Distance2D(e) <= Menus.Item("atosRange").GetValue<Slider>().Value
)
atos.UseAbility(e);
else elsecount += 1;
if (elsecount == 4
&& vail != null
&& vail.CanBeCasted()
&& me.CanCast()
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(vail.Name)
)
vail.UseAbility(v.Position);
else elsecount += 1;
if (elsecount == 5
&& ethereal != null
&& ethereal.CanBeCasted()
&& me.CanCast()
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(ethereal.Name)
)
ethereal.UseAbility(v);
else elsecount += 1;
if (elsecount == 6
&& Q != null
&& Q.CanBeCasted()
&& me.Distance2D(v) <= Q.GetCastRange() + me.HullRadius
&& Menus.Item("AutoSpells").GetValue<AbilityToggler>().IsEnabled(Q.Name))
Q.UseAbility(v.Position);
else elsecount += 1;
if (elsecount == 7
&& Q != null
&& Q.CanBeCasted()
&& Menus.Item("AutoSpells").GetValue<AbilityToggler>().IsEnabled(Q.Name))
Q.UseAbility(pos);
else elsecount += 1;
if (elsecount == 8
&& W != null
&& W.CanBeCasted()
&& me.Distance2D(v) <= W.GetCastRange() + me.HullRadius
&& Menus.Item("AutoSpells").GetValue<AbilityToggler>().IsEnabled(W.Name))
W.UseAbility(v);
else elsecount += 1;
if (elsecount == 9
&& dagon != null
&& dagon.CanBeCasted()
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled("item_dagon"))
dagon.UseAbility(v);
if (elsecount == 10
&& shiva != null
&& shiva.CanBeCasted()
&& me.Distance2D(v) <= 600 + me.HullRadius
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(shiva.Name))
shiva.UseAbility();
if (W != null && W.CanBeCasted() && me.Distance2D(v) >= W.GetCastRange() + me.HullRadius && me.Distance2D(v) <= W.GetCastRange() + me.HullRadius + 325 && Menus.Item("AutoSpells").GetValue<AbilityToggler>().IsEnabled(W.Name) && Utils.SleepCheck("Move"))
{
me.Move(v.Position);
Utils.Sleep(250, "Move");
}
}
}
} // foreach::END
} // AutoSpells::END
private static void DrawUltiDamage(EventArgs args)
{
DrawingOnCore();
//var Drawing = Ensage.Drawing;
enemies = ObjectManager.GetEntities<Hero>()
.Where(x => x.IsVisible && x.IsAlive && x.Team != me.Team && !x.IsMagicImmune() && !x.IsIllusion).ToList();
if (!Game.IsInGame || Game.IsPaused || Game.IsWatchingGame || enemies.Count == 0) return;
if (Menus.Item("dmg").IsActive())
{
foreach (var v in enemies)
{
damage[v.Handle] = CalculateDamage(v);
var screenPos = HUDInfo.GetHPbarPosition(v);
if (!OnScreen(v.Position)) continue;
var text = v.Health <= damage[v.Handle] ? "Yes: " + Math.Floor(damage[v.Handle]) : "No: " + Math.Floor(damage[v.Handle]);
var size = new Vector2(18, 18);
var textSize = Drawing.MeasureText(text, "Arial", size, FontFlags.AntiAlias);
var position = new Vector2(screenPos.X - textSize.X + 85, screenPos.Y + 62);
Drawing.DrawText(
text,
new Vector2(screenPos.X - textSize.X + 84, screenPos.Y + 63),
size,
(Color.White),
FontFlags.AntiAlias);
Drawing.DrawText(
text,
position,
size,
(v.Health <= damage[v.Handle] ? Color.LawnGreen : Color.Red),
FontFlags.AntiAlias);
}
}
} // DrawUltiDamage::END
private static double CalculateDamage(Hero victim)
{
double dmgResult = 0;
var WPoint = me.FindSpell("special_bonus_unique_crystal_maiden_2");
qDmg = WPoint != null && WPoint.Level > 0? Q.GetAbilityData("nova_damage")+250: Q.GetAbilityData("nova_damage");
wDmg = W.GetAbilityData("hero_damage_tooltip");
if (Q != null && Menus.Item("AutoSpells").GetValue<AbilityToggler>().IsEnabled(Q.Name) && Q.CanBeCasted())
dmgResult += qDmg;
if (W != null && W.CanBeCasted() && Menus.Item("AutoSpells").GetValue<AbilityToggler>().IsEnabled(W.Name))
dmgResult += wDmg;
if (victim.NetworkName == "CDOTA_Unit_Hero_SkeletonKing" && victim.Spellbook.SpellR.Cooldown <=0 && victim.Mana>140)
dmgResult = 0;
if (victim.HasModifier("modifier_kunkka_ghost_ship_damage_absorb"))
dmgResult *= 0.5;
if (victim.HasModifier("modifier_bloodseeker_bloodrage"))
{
var blood = ObjectManager.GetEntities<Hero>()
.FirstOrDefault(x => x.ClassId == ClassId.CDOTA_Unit_Hero_Bloodseeker);
if (blood != null)
dmgResult *= bloodrage[blood.Spellbook.Spell1.Level];
else
dmgResult *= 1.4;
}
if (victim.HasModifier("modifier_chen_penitence"))
{
var chen =
ObjectManager.GetEntities<Hero>()
.FirstOrDefault(x => x.Team == me.Team && x.ClassId == ClassId.CDOTA_Unit_Hero_Chen);
if (chen != null)
dmgResult *= penitence[chen.Spellbook.Spell1.Level];
}
if (victim.HasModifier("modifier_shadow_demon_soul_catcher"))
{
var demon = ObjectManager.GetEntities<Hero>()
.FirstOrDefault(x => x.Team == me.Team && x.ClassId == ClassId.CDOTA_Unit_Hero_Shadow_Demon);
if (demon != null)
dmgResult *= souls[demon.Spellbook.Spell2.Level];
}
if (victim.HasModifier("modifier_item_mask_of_madness_berserk"))
dmgResult *= 1.3;
vail = me.FindItem("item_veil_of_discord");
if ((vail != null && vail.CanBeCasted() && Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(vail.Name)
|| victim.HasModifier("modifier_item_veil_of_discord_debuff"))
)
{
dmgResult *= 1.25;
}
var spellamplymult = 1 + (me.TotalIntelligence / 16 / 100);
dmgResult = dmgResult * spellamplymult;
if (dagon != null && dagon.CanBeCasted() && victim.Handle == e?.Handle && Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled("item_dagon"))
dmgResult += dagonDmg[dagon.Level];
shiva = me.FindItem("item_shivas_guard");
if (shiva != null && shiva.CanBeCasted() && Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(shiva.Name))
dmgResult += 200;
dmgResult *= 1 - victim.MagicDamageResist;
int etherealdamage = (int)((me.TotalIntelligence * 2) + 75);
if (ethereal != null && ethereal.CanBeCasted() && victim.Handle == e?.Handle
&& Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled(ethereal.Name))
dmgResult = dmgResult * 1.4 + etherealdamage;
if (orchid != null && orchid.CanBeCasted() && Menus.Item("AutoItems").GetValue<AbilityToggler>().IsEnabled("item_bloodthorn")|| victim.HasModifier("modifier_orchid_malevolence_debuff"))
dmgResult *= 1.3;
return dmgResult;
} // GetDamageTaken::END
public static bool OnScreen(Vector3 v)
{
return !(Drawing.WorldToScreen(v).X < 0 || Drawing.WorldToScreen(v).X > Drawing.Width
|| Drawing.WorldToScreen(v).Y < 0 || Drawing.WorldToScreen(v).Y > Drawing.Height);
}
private static Hero GetClosestToTarget(List<Hero> units, Hero z)
{
Hero closestHero = null;
foreach (var v in units.Where(v => closestHero == null || closestHero.Distance2D(z) > v.Distance2D(z)))
{
closestHero = v;
}
return closestHero;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Appleseed.Framework.Data;
using Appleseed.Framework.DataTypes;
using Appleseed.Framework.Site.Configuration;
using Appleseed.Framework.Users.Data;
using Appleseed.Framework.Web.UI.WebControls;
namespace Appleseed.Framework.Helpers
{
/// <summary>
/// Lists the possible types of data sources for the MDF system
/// </summary>
public enum DataSourceType
{
/// <summary>The current module</summary>
This,
/// <summary>All modules in the portal</summary>
All,
/// <summary>The specified list of modules (for the portal)</summary>
List
}
/// <summary>
/// MDFHelper file by Jakob Hansen.
/// MDF = Module Data Filter
/// This class Represents all settings used by the MDF settings system
/// </summary>
public class MDFSettings
{
#region Public Fields
/// <summary>
///
/// </summary>
public const string NameApplyMDF = "MDF_APPLY_MDF";
/// <summary>
///
/// </summary>
public const string NameDataSource = "MDF_DATA_SOURCE";
/// <summary>
///
/// </summary>
public const string NameMaxHits = "MDF_MAX_HITS";
/// <summary>
///
/// </summary>
public const string NameModuleList = "MDF_MODULE_LIST";
/// <summary>
///
/// </summary>
public const string NameAllNotInList = "MDF_ALL_NOT_IN_LIST";
/// <summary>
///
/// </summary>
public const string NameSortField = "MDF_SORT_FIELD";
/// <summary>
///
/// </summary>
public const string NameSortDirection= "MDF_SORT_DIRECTION";
/// <summary>
///
/// </summary>
public const string NameSearchString = "MDF_SEARCH_STRING";
/// <summary>
///
/// </summary>
public const string NameSearchField = "MDF_SEARCH_FIELD";
/// <summary>
///
/// </summary>
public const string NameMobileOnly = "MDF_MOBILE_ONLY";
/// <summary>
///
/// </summary>
public const bool DefaultValueApplyMDF = false;
/// <summary>
///
/// </summary>
public const DataSourceType DefaultValueDataSource = DataSourceType.This;
/// <summary>
///
/// </summary>
public const int DefaultValueMaxHits = 20;
/// <summary>
///
/// </summary>
public const string DefaultValueModuleList = "";
/// <summary>
///
/// </summary>
public const bool DefaultValueAllNotInList = false;
/// <summary>
///
/// </summary>
public const string DefaultValueSortField = "";
/// <summary>
///
/// </summary>
public const string DefaultValueSortDirection = "ASC";
/// <summary>
///
/// </summary>
public const string DefaultValueSearchString = "";
/// <summary>
///
/// </summary>
public const string DefaultValueSearchField = "";
/// <summary>
///
/// </summary>
public const bool DefaultValueMobileOnly = false;
#endregion
#region Private fields
bool _applyMDF = DefaultValueApplyMDF;
DataSourceType _dataSource = DefaultValueDataSource;
int _maxHits = DefaultValueMaxHits;
string _moduleList = DefaultValueModuleList; //Module ID. Can be a list: "23,45,56"
bool _allNotInList = DefaultValueAllNotInList;
string _sortField = DefaultValueSortField;
string _sortDirection = DefaultValueSortDirection;
string _searchString = DefaultValueSearchString;
string _searchField = DefaultValueSearchField;
bool _mobileOnly = DefaultValueMobileOnly;
bool _supportsWorkflow = false;
WorkFlowVersion _workflowVersion = WorkFlowVersion.Production;
string _itemTableName = "";
string _titleFieldName = "";
string _selectFieldList = "";
string _searchFieldList = "";
int _portalID = -1;
int _userID = -1;
#endregion
#region Public Properties
/// <summary>
/// Controls if the MDF system should be used.
/// Default value: false
/// </summary>
/// <value><c>true</c> if [apply MDF]; otherwise, <c>false</c>.</value>
public bool ApplyMDF
{
get {return _applyMDF;}
set {_applyMDF = value;}
}
/// <summary>
/// Controls the data displyed in the module
/// Default value: DataSourceType.This;
/// </summary>
/// <value>The data source.</value>
public DataSourceType DataSource
{
get {return _dataSource;}
set {_dataSource = value;}
}
/// <summary>
/// Represents the number of items returned by the service.
/// Value 0 means no hit limit (all found items are displayed).
/// Default value: 20
/// </summary>
/// <value>The max hits.</value>
public int MaxHits
{
get {return _maxHits;}
set {_maxHits = value;}
}
/// <summary>
/// Comma separated list of module ID's. e.g.: 1234,234,5454.
/// Only data for these ID's are listed. (see also AllNotInList!)
/// Default value: string.Empty
/// </summary>
/// <value>The module list.</value>
public string ModuleList
{
get {return _moduleList;}
set {_moduleList = value;}
}
/// <summary>
/// If DataSource is All or List this can exclude modules listed in ModuleList
/// Default value: false
/// </summary>
/// <value><c>true</c> if [all not in list]; otherwise, <c>false</c>.</value>
public bool AllNotInList
{
get {return _allNotInList;}
set {_allNotInList = value;}
}
/// <summary>
/// Sort list on this field
/// Valid values: You must set this in the module constructor.
/// Must be a existing field in the module core item table.
/// </summary>
/// <value>The sort field.</value>
public string SortField
{
get {return _sortField;}
set {_sortField = value;}
}
/// <summary>
/// Sort Ascending or Descending
/// Valid values: ASC;DESC
/// Default value: ASC
/// </summary>
/// <value>The sort direction.</value>
public string SortDirection
{
get {return _sortDirection;}
set {_sortDirection = value;}
}
/// <summary>
/// Search string. An empty string means no search (same as off).
/// Default value: string.Empty
/// </summary>
/// <value>The search string.</value>
public string SearchString
{
get {return _searchString;}
set {_searchString = value;}
}
/// <summary>
/// Set this if only a single field should be searched e.g.: "Title"
/// Default value: string.Empty
/// </summary>
/// <value>The search field.</value>
public string SearchField
{
get {return _searchField;}
set {_searchField = value;}
}
/// <summary>
/// Default value: false
/// </summary>
/// <value><c>true</c> if [supports workflow]; otherwise, <c>false</c>.</value>
public bool SupportsWorkflow
{
get {return _supportsWorkflow;}
set {_supportsWorkflow = value;}
}
/// <summary>
/// Default value: Production
/// </summary>
/// <value>The workflow version.</value>
public WorkFlowVersion WorkflowVersion
{
get {return _workflowVersion;}
set {_workflowVersion = value;}
}
/// <summary>
/// The name of the modules core item table e.g. "rb_Links" for module Links
/// Default value: string.Empty
/// </summary>
/// <value>The name of the item table.</value>
public string ItemTableName
{
get {return _itemTableName;}
set {_itemTableName = value;}
}
/// <summary>
/// The name of the field in the item table that is considered the item title. Typical value is "Title"
/// Default value: string.Empty
/// </summary>
/// <value>The name of the title field.</value>
public string TitleFieldName
{
get {return _titleFieldName;}
set {_titleFieldName = value;}
}
/// <summary>
/// The list of fields in the SQL select, separated with comma.
/// NOTE: must be prefixed with itm., e.g.: "itm.ItemID,itm.CreatedByUser,itm.CreatedDate,itm.Title"
/// Default value: string.Empty
/// </summary>
/// <value>The select field list.</value>
public string SelectFieldList
{
get {return _selectFieldList;}
set {_selectFieldList = value;}
}
/// <summary>
/// Fields to search - must be of nvarchar or ntext type.
/// NOTE: must be seperated with semicolon, e.g.: "Title;Url;MobileUrl;Description;CreatedByUser"
/// Default value: string.Empty
/// </summary>
/// <value>The search field list.</value>
public string SearchFieldList
{
get {return _searchFieldList;}
set {_searchFieldList = value;}
}
/// <summary>
/// When true only data for mobile devices are displyed
/// Default value: false
/// </summary>
/// <value><c>true</c> if [mobile only]; otherwise, <c>false</c>.</value>
public bool MobileOnly
{
get {return _mobileOnly;}
set {_mobileOnly = value;}
}
/// <summary>
/// The portal id
/// Default value: -1
/// </summary>
/// <value>The portal ID.</value>
public int PortalID
{
get {return _portalID;}
set {_portalID = value;}
}
/// <summary>
/// When the value of UserID is 0 the user has not signed in (it's a guest!)
/// Default value: -1
/// </summary>
/// <value>The user ID.</value>
public int UserID
{
get {return _userID;}
set {_userID = value;}
}
#endregion
#region Public Methods
/// <summary>
/// Fills all MDF settings. Returns true if no problems reading and
/// parsing all MDF settings.
/// </summary>
/// <param name="pmc">The PMC.</param>
/// <param name="itemTableName">Name of the item table.</param>
/// <param name="titleFieldName">Name of the title field.</param>
/// <param name="selectFieldList">The select field list.</param>
/// <param name="searchFieldList">The search field list.</param>
/// <returns></returns>
public bool Populate(PortalModuleControl pmc, string itemTableName, string titleFieldName, string selectFieldList, string searchFieldList)
{
bool PopulateDone;
try
{
_applyMDF = bool.Parse(pmc.Settings[NameApplyMDF].ToString());
string ds = pmc.Settings[NameDataSource].ToString();
if (ds == DataSourceType.This.ToString())
_dataSource = DataSourceType.This;
else if (ds == DataSourceType.All.ToString())
_dataSource = DataSourceType.All;
else if (ds == DataSourceType.List.ToString())
_dataSource = DataSourceType.List;
_maxHits = int.Parse(pmc.Settings[NameMaxHits].ToString());
_moduleList = pmc.Settings[NameModuleList].ToString();
_allNotInList = bool.Parse(pmc.Settings[NameAllNotInList].ToString());
_sortField = pmc.Settings[NameSortField].ToString();
_sortDirection = pmc.Settings[NameSortDirection].ToString();
_searchString = pmc.Settings[NameSearchString].ToString();
_searchField = pmc.Settings[NameSearchField].ToString();
_mobileOnly = bool.Parse(pmc.Settings[NameMobileOnly].ToString());
if (_dataSource == DataSourceType.This)
_moduleList = pmc.ModuleID.ToString();
if (_moduleList == "" && _dataSource == DataSourceType.List)
{
// Create data to lazy user that forgot to enter data in field Module List
_moduleList = pmc.ModuleID.ToString();
}
if (pmc.SupportsWorkflow)
{
_supportsWorkflow = pmc.SupportsWorkflow;
_workflowVersion = pmc.Version;
}
_itemTableName = itemTableName;
_titleFieldName = titleFieldName;
_selectFieldList = selectFieldList;
_searchFieldList = searchFieldList;
_portalID = pmc.PortalID;
UsersDB u = new UsersDB();
SqlDataReader dr = u.GetSingleUser(PortalSettings.CurrentUser.Identity.Email);
if (dr.Read())
_userID = Int32.Parse(dr["UserID"].ToString());
PopulateDone = true;
}
catch (Exception)
{
PopulateDone = false;
}
return PopulateDone;
}
/// <summary>
/// Initializes a new instance of the MDFSetting object with default settings.
/// </summary>
public MDFSettings()
{
//Nada code!
}
/// <summary>
/// Initializes a new instance of the MDFSetting object with real settings
/// </summary>
/// <param name="pmc">The PMC.</param>
/// <param name="itemTableName">Name of the item table.</param>
/// <param name="titleFieldName">Name of the title field.</param>
/// <param name="selectFieldList">The select field list.</param>
/// <param name="searchFieldList">The search field list.</param>
public MDFSettings(PortalModuleControl pmc, string itemTableName, string titleFieldName, string selectFieldList, string searchFieldList)
{
Populate(pmc, itemTableName, titleFieldName, selectFieldList, searchFieldList);
}
/// <summary>
/// Retuns true if the module is using MDF.
/// </summary>
/// <param name="pmc">The PMC.</param>
/// <returns>
/// <c>true</c> if [is MDF applied] [the specified PMC]; otherwise, <c>false</c>.
/// </returns>
static public bool IsMDFApplied(PortalModuleControl pmc)
{
return bool.Parse(pmc.Settings[NameApplyMDF].ToString());
}
/// <summary>
/// Max apply mdf
/// </summary>
/// <param name="defaultValue">if set to <c>true</c> [default value].</param>
/// <returns></returns>
static public SettingItem MakeApplyMDF(bool defaultValue)
{
SettingItem si = new SettingItem(new BooleanDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 1;
si.Value = defaultValue.ToString();
si.EnglishName = "Apply MDF";
si.Description = "Controls if the MDF system is activated or not";
return si;
}
/// <summary>
/// Make data source
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeDataSource(DataSourceType defaultValue)
{
SettingItem si = new SettingItem(
new ListDataType(DataSourceType.This.ToString() + ";" + DataSourceType.All.ToString() + ";" + DataSourceType.List.ToString()));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 2;
si.Required = true;
si.Value = defaultValue.ToString();
si.EnglishName = "DataSource";
si.Description = "Controls where data displyed in the module is comming from. " +
"'This' is the current module, 'All' is all modules in the current portal " +
"and with 'List' you must specify a list of module id's, e.g.: 20242,10243";
return si;
}
/// <summary>
/// Makes the max hits.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeMaxHits(int defaultValue)
{
SettingItem si = new SettingItem(new IntegerDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 3;
si.Required = true;
si.Value = defaultValue.ToString();
si.MinValue = 0;
si.MaxValue = int.MaxValue;
si.EnglishName = "Max Hits";
si.Description = "Represents the number of items returned by MDF. Value 0 means no hit limit (all found items are displayed)";
return si;
}
/// <summary>
/// Makes the module list.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeModuleList(string defaultValue)
{
SettingItem si = new SettingItem(new StringDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 4;
si.Required = false;
si.Value = defaultValue;
si.EnglishName = "Module List";
si.Description = "Comma separated list of module ID's. e.g.: 20242,10243. Only data for these ID's are listed. (see also AllNotInList!)";
return si;
}
/// <summary>
/// Makes all not in list.
/// </summary>
/// <param name="defaultValue">if set to <c>true</c> [default value].</param>
/// <returns></returns>
static public SettingItem MakeAllNotInList(bool defaultValue)
{
SettingItem si = new SettingItem(new BooleanDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 5;
si.Value = defaultValue.ToString();
si.EnglishName = "All Not In List";
si.Description = "If DataSource is 'All' or 'List' this can exclude modules listed in Module List";
return si;
}
/// <summary>
/// Makes the sort field list.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <param name="fieldList">The field list.</param>
/// <returns></returns>
static public SettingItem MakeSortFieldList(string defaultValue, string fieldList)
{
SettingItem si = new SettingItem(new ListDataType(fieldList));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 6;
si.Required = true;
si.Value = defaultValue;
si.EnglishName = "Sort Field";
si.Description = "A list of all fields from the core item table you want to sort on";
return si;
}
/// <summary>
/// Makes the sort direction.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeSortDirection(string defaultValue)
{
SettingItem si = new SettingItem(new ListDataType("ASC;DESC"));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 7;
si.Required = true;
si.Value = defaultValue;
si.EnglishName = "Sort Direction";
si.Description = "Sort Ascending or Descending";
return si;
}
/// <summary>
/// Makes the search string.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeSearchString(string defaultValue)
{
SettingItem si = new SettingItem(new StringDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 8;
si.Required = false;
si.Value = defaultValue;
si.EnglishName = "Search string";
si.Description = "An empty string means no search (same as off)";
return si;
}
/// <summary>
/// Makes the search field list.
/// </summary>
/// <param name="fieldList">The field list.</param>
/// <returns></returns>
static public SettingItem MakeSearchFieldList(string fieldList)
{
SettingItem si = new SettingItem(new ListDataType("All;" + fieldList));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 9;
si.Required = true;
si.Value = "All";
si.EnglishName = "Search field";
si.Description = "Search all fields or a single named field in the item record. " +
"The list of possible search fields are different for different modules";
return si;
}
/// <summary>
/// Makes the mobile only.
/// </summary>
/// <param name="defaultValue">if set to <c>true</c> [default value].</param>
/// <returns></returns>
static public SettingItem MakeMobileOnly(bool defaultValue)
{
SettingItem si = new SettingItem(new BooleanDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 10;
si.Value = defaultValue.ToString();
si.EnglishName = "Mobile Only";
si.Description = "When true only data for mobile devices are displyed";
return si;
}
/// <summary>
/// Gets the SQL select.
/// </summary>
/// <returns></returns>
public string GetSqlSelect()
{
StringBuilder select = new StringBuilder("", 1000);
select.Append(" SELECT");
if (MaxHits > 0)
select.Append(" TOP " + MaxHits);
select.Append(" ");
select.Append(SelectFieldList);
if (SupportsWorkflow && WorkflowVersion == WorkFlowVersion.Staging)
select.Append(" FROM " + ItemTableName + "_st itm");
else
select.Append(" FROM " + ItemTableName + " itm");
if (DataSource == DataSourceType.This)
{
// Note that there at this point are only one single moduleid in ModuleList!
select.Append(" WHERE itm.ModuleID = " + ModuleList + "");
}
else
{
select.Append(", rb_Modules mod, rb_ModuleDefinitions modDef");
if (_userID > -1)
select.Append(", rb_Roles, rb_UserRoles");
if (DataSource == DataSourceType.List)
if (AllNotInList)
select.Append(" WHERE itm.ModuleID NOT IN (" + ModuleList + ")");
else
select.Append(" WHERE itm.ModuleID IN (" + ModuleList + ")");
else
if (AllNotInList)
select.Append(" WHERE itm.ModuleID NOT IN (" + ModuleList + ")");
else
select.Append(" WHERE 1=1");
if (MobileOnly)
select.Append(" AND Mod.ShowMobile=1");
select.Append(" AND itm.ModuleID = mod.ModuleID");
select.Append(" AND mod.ModuleDefID = modDef.ModuleDefID");
select.Append(" AND modDef.PortalID = " + PortalID.ToString());
if (_userID > -1)
{
select.Append(" AND rb_UserRoles.UserID = " + _userID.ToString());
select.Append(" AND rb_UserRoles.RoleID = rb_Roles.RoleID");
select.Append(" AND rb_Roles.PortalID = " + _portalID.ToString());
select.Append(" AND ((mod.AuthorizedViewRoles LIKE '%All Users%') OR (mod.AuthorizedViewRoles LIKE '%'+rb_Roles.RoleName+'%'))");
}
else
{
select.Append(" AND (mod.AuthorizedViewRoles LIKE '%All Users%')");
}
}
// Why this? Because some Rb modules inserts a record containing null value fields! :o(
select.Append(" AND itm." + TitleFieldName + " IS NOT NULL");
if (SearchString != "")
{
select.Append(" AND (");
if (SearchField == "All")
{
string[] arrField = _searchFieldList.Split(';');
bool firstField = true;
foreach (string field in arrField)
{
if (firstField)
firstField = false;
else
select.Append(" OR ");
select.Append("itm." + field + " like '%" + SearchString + "%'");
}
}
else
{
select.Append("itm." + SearchField + " like '%" + SearchString + "%'");
}
select.Append(")");
}
select.Append(" ORDER BY itm." + SortField + " " + SortDirection);
return select.ToString();
}
/// <summary>
/// Get the item list data as a SqlDataReader
/// </summary>
/// <returns></returns>
public SqlDataReader GetDataReader()
{
string sqlSelect = GetSqlSelect();
return DBHelper.GetDataReader(sqlSelect);
}
/// <summary>
/// Get the item list data as a DataSet
/// </summary>
/// <returns></returns>
public DataSet GetDataSet()
{
string sqlSelect = GetSqlSelect();
return DBHelper.GetDataSet(sqlSelect);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ESS.UI.HelpPage.Areas.HelpPage.ModelDescriptions;
using ESS.UI.HelpPage.Areas.HelpPage.Models;
namespace ESS.UI.HelpPage.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Genral Functions of the site
public class General
{
#region "public functions"
//adds user from find users as both the only files phone number and database phone numbers
//need to have a loop to add muliple enties with the same phone number
public static int[] addMulipleEnties(System.Random ranNumber, int intDiffBetweenFilesDatabase, int[] arrOdds, string strPhoneNumber, string strLang, string strFileCreatedDate)
{
try
{
int intSpecialPINumber = DAL.getCountSpecialPIN("", strPhoneNumber.Trim());//holds the SpecialPIN for this phone number
//checks if the phone number is in the database if not then add it to the table
if(intSpecialPINumber == 0)
//adds the users number to the list of people who did not get their emails
DAL.addUpdateSpecialPIN(0, strPhoneNumber, DateTime.Now.ToString("MMddtt"));
//goes around until both the phone number in the file and database are equal
for (int intIndex = 0;intIndex < intDiffBetweenFilesDatabase;intIndex++)
{
//plays the odds and adds the user to the database
arrOdds = playingTheOdd(ranNumber,arrOdds,strPhoneNumber, strLang, strFileCreatedDate);
}//end of for loop
//updates all of the phone number for this day as it is all site and ready to go
DAL.updateRowValid(strFileCreatedDate, strPhoneNumber, true);
return arrOdds;
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
}//end of addMulipleEnties()
//creates a pin number
public static int createPin(System.Random ranNumber)
{
int intPin = ranNumber.Next(999999, 9999999);//holds the random number of the pin
DataTable dtlSpinToWin = DAL.getColData(" Where = '" + intPin + "'", "");//holds the spin to win: generted pin
//goes around checks if this random number has been used if so then create aother random number
//until a number that has not been used is display
while(dtlSpinToWin != null)
{
//creates another random and get it from the database
//in order to check if it is in the database
intPin = ranNumber.Next(999999, 9999999);
dtlSpinToWin = DAL.getColData(" Where = '" + intPin + "'", "");
}//end of if
return intPin;
}//end of createPin()
public static void CreateXML(string phoneNumber, string strSQLAND = "ISNULL([],'') = ''")
{
try
{
xiamSMS objxiamSMS = new xiamSMS();
DataTable dataTableSmsRequest = DAL.queryDbTable("SELECT * FROM WHERE [] = '" + phoneNumber + "' AND " + strSQLAND + " OR [] = '1" + phoneNumber + "' AND " + strSQLAND + " ORDER BY ;");
if (dataTableSmsRequest != null && dataTableSmsRequest.Rows.Count > 0)
{
xiamSMSSubmitRequest[] xiamSMSSubmitRequests = new xiamSMSSubmitRequest[dataTableSmsRequest.Rows.Count];
int i = 0;
foreach (DataRow dataRowSmsRequest in dataTableSmsRequest.Rows)
{
xiamSMSSubmitRequest objxiamSMSSubmitRequest = new xiamSMSSubmitRequest();
objxiamSMSSubmitRequest.id = dataRowSmsRequest[""].ToString();
objxiamSMSSubmitRequest.from = "";
objxiamSMSSubmitRequest.to = dataRowSmsRequest[""].ToString();
//content
xiamSMSSubmitRequestContent objxiamSMSSubmitRequestContent = new xiamSMSSubmitRequestContent();
objxiamSMSSubmitRequestContent.type = "text";
if (dataRowSmsRequest["LanguageCode"].ToString().Trim() == "f")
objxiamSMSSubmitRequestContent.Value = "chatr ROUE CHANCEUSE: Merci d'avoir reapprovisionner. Ton NIP de concours: " + dataRowSmsRequest[""].ToString() + " . Consulte: http://chatrrouechanceuse.com/. Desabonnement: chatrsansfil.com/stop";
else
objxiamSMSSubmitRequestContent.Value = "chatr SPIN to WIN: Thanks for topping up. Your Contest PIN is " + dataRowSmsRequest[""].ToString() + " . Go to http://chatrspintowin.com/ to see if you're a winner. To opt-out go to chatrwireless.com/stop";
objxiamSMSSubmitRequest.content = objxiamSMSSubmitRequestContent;
//sendOnGroup
xiamSMSSubmitRequestSendOnGroup objxiamSMSSubmitRequestSendOnGroup = new xiamSMSSubmitRequestSendOnGroup();
objxiamSMSSubmitRequestSendOnGroup.value = "RG_PROD";
objxiamSMSSubmitRequestSendOnGroup.Value = " ";
objxiamSMSSubmitRequest.sendOnGroup = objxiamSMSSubmitRequestSendOnGroup;
//requestDeliveryReport
xiamSMSSubmitRequestRequestDeliveryReport objxiamSMSSubmitRequestRequestDeliveryReport = new xiamSMSSubmitRequestRequestDeliveryReport();
objxiamSMSSubmitRequestRequestDeliveryReport.value = "yes";
objxiamSMSSubmitRequestRequestDeliveryReport.Value = " ";
objxiamSMSSubmitRequest.requestDeliveryReport = objxiamSMSSubmitRequestRequestDeliveryReport;
xiamSMSSubmitRequests[i] = objxiamSMSSubmitRequest;
i++;
}//end of foreach
objxiamSMS.submitRequest = xiamSMSSubmitRequests;
string xiamSMSXml = CreateUserXml(objxiamSMS);
WriteXmlToFile(xiamSMSXml, phoneNumber);
ConsumeWebService(xiamSMSXml, phoneNumber);
}//end of if
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
}//end of CreateXML()
//plays the odds and adds the user to the database
public static int[] playingTheOdd(System.Random ranNumber, int[] arrOddTotal, string strPhoneNumber, string strLang, string strDateEntryCreatedDate = "")
{
string strPin = createPin(ranNumber).ToString();//holds the pin that is being created this person
string strPrizeAmount = "";//holds the amount of the prize
bool boolIsWinner = false;//holds if this user is a winner
/*
arrOdds - Table of Contents
intNumberOfUsers - holds the number of users entred
intNumberPrizes - holds the number of winning prizes sent out
intSessionTotalOdd5 - holds this session total odds of winning the 5 dollar prize
intSessionTotalOdd10 - holds this session total odds of winning the 10 dollar prize
intSessionTotalOdd20 - holds this session total odds of winning the 20 dollar prize
intOdd5 - holds the odds of winning the 5 dollar prize
intOdd10 - holds the odds of winning the 10 dollar prize
intOdd20 - holds the odds of winning the 20 dollar prize
*/
//checks if this user is the winner of the five dollor prize
if(arrOddTotal[5] >= 5)
{
DataTable dtTotalGift = DAL.queryDbTable("SELECT * FROM where Value = '5'");//holds total of gifts avaiable
DataTable dtGiveOutTotalGift = DAL.queryDbTable("SELECT * FROM where = '5'");//holds current number gifts given out
//checks if there is ehough prizes to give out if so then set the amount and boolIsWinner
if(dtTotalGift.Rows.Count >= dtGiveOutTotalGift.Rows.Count)
{
//sets the amount for this prize and boolIsWinner for it to display
//for this user
strPrizeAmount = "5";
boolIsWinner = true;
//adds to the arrOddTotal[1] total
arrOddTotal[1]++;
//adds to the session total for this odd
arrOddTotal[2]++;
//resets the odds for the next round
arrOddTotal[5] = 1;
}//end of if
else
//sets this arrOddTotal to -1 to tell that there is no more gifts for this odd
arrOddTotal[5] = -1;
}//end of if
else
arrOddTotal[5]++;
//checks if this user is the winner of the ten dollor prize
if(arrOddTotal[6] >= 183 && string.IsNullOrEmpty(strPrizeAmount))
{
DataTable dtTotalGift = DAL.queryDbTable("SELECT * FROM where Value = '10'");//holds total of gifts avaiable
DataTable dtGiveOutTotalGift = DAL.queryDbTable("SELECT * FROM where = '10'");//holds current number gifts given out
//checks if there is ehough prizes to give out if so then set the amount and boolIsWinner
if(dtTotalGift.Rows.Count >= dtGiveOutTotalGift.Rows.Count)
{
//sets the amount for this prize and boolIsWinner for it to display
//for this user
strPrizeAmount = "10";
boolIsWinner = true;
//adds to the arrOddTotal[1] total
arrOddTotal[1]++;
//adds to the session total for this odd
arrOddTotal[3]++;
//resets the odds for the next round
arrOddTotal[6] = 1;
}//end of if
else
//sets this arrOddTotal to -1 to tell that there is no more gifts for this odd
arrOddTotal[6] = -1;
}//end of if
else
arrOddTotal[6]++;
//checks if this user is the winner of the twenty dollor prize
if(arrOddTotal[7] >= 183 && string.IsNullOrEmpty(strPrizeAmount))
{
DataTable dtTotalGift = DAL.queryDbTable("SELECT * FROM where Value = '20'");//holds total of gifts avaiable
DataTable dtGiveOutTotalGift = DAL.queryDbTable("SELECT * FROM where = '20'");//holds current number gifts given out
//checks if there is ehough prizes to give out if so then set the amount and boolIsWinner
if(dtTotalGift.Rows.Count >= dtGiveOutTotalGift.Rows.Count)
{
//sets the amount for this prize and boolIsWinner for it to display
//for this user
strPrizeAmount = "20";
boolIsWinner = true;
//adds to the arrOddTotal[1] total
arrOddTotal[1]++;
//adds to the session total for this odd
arrOddTotal[4]++;
//resets the odds for the next round
arrOddTotal[7] = 1;
}//end of if
else
//sets this arrOddTotal to -1 to tell that there is no more gifts for this odd
arrOddTotal[7] = -1;
}//end of if
else
arrOddTotal[7]++;
//adds all of those phones to the win a gift
DAL.addUpdateSpin(0, strPhoneNumber.Trim(), strLang.Trim(), strPin, false, boolIsWinner, "", "", boolIsWinner, false, -1, "", strPrizeAmount, "", "", "", strDateEntryCreatedDate);
//adds to the total number of users added to the database
arrOddTotal[0]++;
return arrOddTotal;
}//end of playingTheOdd()
//searches the file content for a phone number and returns the number of phone numbers in this file
public static int searchContentNumberOfPhoneNumbers(string strPhoneNumber, ArrayList alSearch)
{
try
{
int intSearchResults = 0;//holds the number of phone numbers that are the same as strPhoneNumber
//goes around until strPhoneNumber is found and counts the number of times it is in the csv file
foreach (CSVContent csvDetails in alSearch)
{
//checks if the phone number in csv index is the same as the one that the user is looking for
if (csvDetails.displayPhoneNumber() == strPhoneNumber)
//adds to the search results
intSearchResults++;
//checks if the search results is already been used if so then break
//in order to make the search a little faster
else if(intSearchResults > 0)
break;
}//end of foreach
return intSearchResults;
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
}//end of searchContentNumberOfPhoneNumbers()
public static void sendErrorMessage(string strEmailSubject, string strEmailBody)
{
MailMessage mmError = new MailMessage(new MailAddress(""));//holds the message of email
SmtpClient smtpMail = new SmtpClient();//holds the Smtp info for sending out e-mails
//sets the properties for the email
mmError.CC.Add(new MailAddress(""));
mmError.Subject = strEmailSubject;
mmError.Body = strEmailBody;
mmError.Priority = MailPriority.Normal;
mmError.IsBodyHtml = true;
//sets the settings of the email and send it out
smtpMail.Host = DotNetNuke.Entities.Host.HostSettings.GetHostSetting("SMTPServer");
smtpMail.Send(mmError);
}//end of sendErrorMessage()
#endregion
#region "private functions"
private static void WriteXmlToFile(string userProfileDetailXml, string spinToWinId)
{
try
{
StreamWriter sr;
sr = File.CreateText(HttpContext.Current.Server.MapPath(".\\TempXML\\") + spinToWinId + ".xml");
sr.WriteLine(userProfileDetailXml.Replace("utf-16", "utf-8").Replace("<xiamSMS>", "\r\n<!DOCTYPE xiamSMS SYSTEM \"xiamSMSMessage.dtd\">\r\n<xiamSMS>"));
sr.Close();
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
}//end of WriteXmlToFile()
private static void ConsumeWebService(string xiamSMSXml, string spinToWinId)
{
try
{
string url = "http://websvcs2.jumptxt.com/smsxml/collector";
// declare ascii encoding
ASCIIEncoding encoding = new ASCIIEncoding();
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.XmlResolver = null;
xmlDoc.Load(HttpContext.Current.Server.MapPath(".\\TempXML\\" + spinToWinId + ".xml"));
string postData = xmlDoc.InnerXml;
// convert xmlstring to byte using ascii encoding
byte[] data = encoding.GetBytes(postData);
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
//webrequest header information
webrequest.Headers.Add("HTTP_ACCEPT", "text/xml; charset=UTF-8");
webrequest.Headers.Add("X-XIAM-Provider-ID", "132");
webrequest.Headers.Add("HTTP_USER_AGENT", System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString());
webrequest.Headers.Add("HTTP_HOST", "websvcs2.jumptxt.com");
webrequest.Headers.Add("HTTP_CONTENT_LENGTH", data.Length.ToString());
// set method as post
webrequest.Method = "POST";
// get stream data out of webrequest object
Stream newStream = webrequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
// declare & read response from service
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
// set utf8 encoding
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
}//end of ConsumeWebService()
private static string CreateUserXml(xiamSMS objxiamSMS)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.Unicode);
// get serialise object
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(typeof(xiamSMS));
serializer.Serialize(writer, objxiamSMS, ns); // read object
int count = (int)stream.Length; // saves object in memory stream
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
return utf.GetString(arr).Trim();
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
finally
{
if (stream != null)
stream.Close();
if (writer != null)
writer.Close();
}//end of finally
}//end of try
#endregion
}//end of class General
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using Axiom.MathLib;
using Axiom.Core;
using Axiom.Graphics;
using Axiom.Scripting;
namespace Axiom.ParticleSystems {
public class BillboardParticleRenderer : ParticleSystemRenderer {
static string rendererTypeName = "billboard";
const string PARTICLE = "Particle";
/// <summary>
/// List of available attibute parsers for script attributes.
/// </summary>
private Dictionary<string, MethodInfo> attribParsers =
new Dictionary<string, MethodInfo>();
BillboardSet billboardSet;
public BillboardParticleRenderer() {
billboardSet = new BillboardSet("", 0, true);
billboardSet.SetBillboardsInWorldSpace(true);
// TODO: Is this the right way to do this?
RegisterParsers();
}
#region Attribute Parsers
[AttributeParser("billboard_type", PARTICLE)]
public static void ParseBillboardType(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 1) {
ParseHelper.LogParserError("billboard_type", _renderer.Type, "Wrong number of parameters.");
return;
}
// lookup the real enum equivalent to the script value
object val = ScriptEnumAttribute.Lookup(values[0], typeof(BillboardType));
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
// if a value was found, assign it
if (val != null)
renderer.BillboardType = (BillboardType)val;
else
ParseHelper.LogParserError("billboard_type", _renderer.Type, "Invalid enum value");
}
[AttributeParser("billboard_origin", PARTICLE)]
public static void ParseBillboardOrigin(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 1) {
ParseHelper.LogParserError("billboard_origin", _renderer.Type, "Wrong number of parameters.");
return;
}
// lookup the real enum equivalent to the script value
object val = ScriptEnumAttribute.Lookup(values[0], typeof(BillboardOrigin));
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
// if a value was found, assign it
if (val != null)
renderer.BillboardOrigin = (BillboardOrigin)val;
else
ParseHelper.LogParserError("billboard_origin", _renderer.Type, "Invalid enum value");
}
[AttributeParser("billboard_rotation_type", PARTICLE)]
public static void ParseBillboardRotationType(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 1) {
ParseHelper.LogParserError("billboard_rotation_type", _renderer.Type, "Wrong number of parameters.");
return;
}
// lookup the real enum equivalent to the script value
object val = ScriptEnumAttribute.Lookup(values[0], typeof(BillboardRotationType));
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
// if a value was found, assign it
if (val != null)
renderer.BillboardRotationType = (BillboardRotationType)val;
else
ParseHelper.LogParserError("billboard_rotation_type", _renderer.Type, "Invalid enum value");
}
[AttributeParser("common_direction", PARTICLE)]
public static void ParseCommonDirection(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 3) {
ParseHelper.LogParserError("common_direction", _renderer.Type, "Wrong number of parameters.");
return;
}
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
renderer.CommonDirection = StringConverter.ParseVector3(values);
}
[AttributeParser("common_up_vector", PARTICLE)]
public static void ParseCommonUpDirection(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 3) {
ParseHelper.LogParserError("common_up_vector", _renderer.Type, "Wrong number of parameters.");
return;
}
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
renderer.CommonUpVector = StringConverter.ParseVector3(values);
}
[AttributeParser("point_rendering", PARTICLE)]
public static void ParsePointRendering(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 1) {
ParseHelper.LogParserError("point_rendering", _renderer.Type, "Wrong number of parameters.");
return;
}
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
renderer.PointRenderingEnabled = StringConverter.ParseBool(values[0]);
}
[AttributeParser("accurate_facing", PARTICLE)]
public static void ParseAccurateFacing(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 1) {
ParseHelper.LogParserError("accurate_facing", _renderer.Type, "Wrong number of parameters.");
return;
}
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
renderer.UseAccurateFacing = StringConverter.ParseBool(values[0]);
}
[AttributeParser("depth_offset", PARTICLE)]
public static void ParseDepthOffset(string[] values, ParticleSystemRenderer _renderer) {
if (values.Length != 1) {
ParseHelper.LogParserError("depth_offset", _renderer.Type, "Wrong number of parameters.");
return;
}
BillboardParticleRenderer renderer = (BillboardParticleRenderer)_renderer;
renderer.DepthOffset = StringConverter.ParseFloat(values[0]);
}
/// <summary>
/// Registers all attribute names with their respective parser.
/// </summary>
/// <remarks>
/// Methods meant to serve as attribute parsers should use a method attribute to
/// </remarks>
private void RegisterParsers() {
MethodInfo[] methods = this.GetType().GetMethods();
// loop through all methods and look for ones marked with attributes
for (int i = 0; i < methods.Length; i++) {
// get the current method in the loop
MethodInfo method = methods[i];
// see if the method should be used to parse one or more material attributes
AttributeParserAttribute[] parserAtts =
(AttributeParserAttribute[])method.GetCustomAttributes(typeof(AttributeParserAttribute), true);
// loop through each one we found and register its parser
for (int j = 0; j < parserAtts.Length; j++) {
AttributeParserAttribute parserAtt = parserAtts[j];
switch (parserAtt.ParserType) {
// this method should parse a material attribute
case PARTICLE:
// attribParsers.Add(parserAtt.Name, Delegate.CreateDelegate(typeof(ParticleSystemRendererAttributeParser), method));
attribParsers[parserAtt.Name] = method;
break;
} // switch
} // for
} // for
}
public override void CopyParametersTo(ParticleSystemRenderer other) {
BillboardParticleRenderer otherBpr = (BillboardParticleRenderer)other;
Debug.Assert(otherBpr != null);
otherBpr.BillboardType = this.BillboardType;
otherBpr.BillboardOrigin = this.BillboardOrigin;
otherBpr.CommonUpVector = this.CommonUpVector;
otherBpr.CommonDirection = this.CommonDirection;
otherBpr.DepthOffset = this.DepthOffset;
otherBpr.UseAccurateFacing = this.UseAccurateFacing;
}
#endregion
/// <summary>
/// Parses an attribute intended for the particle system itself.
/// </summary>
/// <param name="line"></param>
/// <param name="system"></param>
public override bool SetParameter(string attr, string val) {
if (attribParsers.ContainsKey(attr)) {
object[] args = new object[2];
args[0] = val.Split(' ');
args[1] = this;
attribParsers[attr].Invoke(null, args);
//ParticleSystemRendererAttributeParser parser =
// (ParticleSystemRendererAttributeParser)attribParsers[attr];
//// call the parser method
//parser(val.Split(' '), this);
return true;
}
return false;
}
public override void UpdateRenderQueue(RenderQueue queue,
List<Particle> currentParticles,
bool cullIndividually)
{
billboardSet.CullIndividual = cullIndividually;
// Update billboard set geometry
billboardSet.BeginBillboards();
Billboard bb = new Billboard();
foreach (Particle p in currentParticles) {
bb.Position = p.Position;
if (billboardSet.BillboardType == BillboardType.OrientedSelf ||
billboardSet.BillboardType == BillboardType.PerpendicularSelf)
{
// Normalise direction vector
bb.Direction = p.Direction;
bb.Direction.Normalize();
}
bb.Color = p.Color;
bb.rotationInRadians = p.rotationInRadians;
bb.HasOwnDimensions = p.HasOwnDimensions;
if (bb.HasOwnDimensions)
{
bb.width = p.Width;
bb.height = p.Height;
}
billboardSet.InjectBillboard(bb);
}
billboardSet.EndBillboards();
// Update the queue
billboardSet.UpdateRenderQueue(queue);
}
//-----------------------------------------------------------------------
public override void SetMaterial(Material mat)
{
billboardSet.MaterialName = mat.Name;
}
//-----------------------------------------------------------------------
public override void NotifyCurrentCamera(Camera cam)
{
billboardSet.NotifyCurrentCamera(cam);
}
//-----------------------------------------------------------------------
public override void NotifyParticleRotated()
{
billboardSet.NotifyBillboardRotated();
}
//-----------------------------------------------------------------------
public override void NotifyDefaultDimensions(float width, float height)
{
billboardSet.SetDefaultDimensions(width, height);
}
//-----------------------------------------------------------------------
public override void NotifyParticleResized()
{
billboardSet.NotifyBillboardResized();
}
//-----------------------------------------------------------------------
public override void NotifyParticleQuota(int quota)
{
billboardSet.PoolSize = quota;
}
//-----------------------------------------------------------------------
public override void NotifyAttached(Node parent, bool isTagPoint)
{
billboardSet.NotifyAttached(parent, isTagPoint);
}
//-----------------------------------------------------------------------
public override void SetRenderQueueGroup(RenderQueueGroupID queueID) {
billboardSet.RenderQueueGroup = queueID;
}
//-----------------------------------------------------------------------
public override void SetKeepParticlesInLocalSpace(bool keepLocal) {
billboardSet.SetBillboardsInWorldSpace(!keepLocal);
}
//-----------------------------------------------------------------------
public BillboardType BillboardType {
get {
return billboardSet.BillboardType;
}
set {
billboardSet.BillboardType = value;
}
}
public BillboardOrigin BillboardOrigin {
get {
return billboardSet.BillboardOrigin;
}
set {
billboardSet.BillboardOrigin = value;
}
}
//-----------------------------------------------------------------------
public bool UseAccurateFacing {
get {
return billboardSet.UseAccurateFacing;
}
set {
billboardSet.UseAccurateFacing = value;
}
}
public BillboardRotationType BillboardRotationType {
get {
return billboardSet.BillboardRotationType;
}
set {
billboardSet.BillboardRotationType = value;
}
}
public Vector3 CommonDirection {
get {
return billboardSet.CommonDirection;
}
set {
billboardSet.CommonDirection = value;
}
}
public Vector3 CommonUpVector {
get {
return billboardSet.CommonUpVector;
}
set {
billboardSet.CommonUpVector = value;
}
}
public float DepthOffset {
get {
return billboardSet.DepthOffset;
}
set {
billboardSet.DepthOffset = value;
}
}
//-----------------------------------------------------------------------
//SortMode BillboardParticleRenderer::_getSortMode(void) const
//{
// return mBillboardSet->_getSortMode();
//}
//-----------------------------------------------------------------------
public bool PointRenderingEnabled {
get {
return billboardSet.PointRenderingEnabled;
}
set {
billboardSet.PointRenderingEnabled = value;
}
}
public override string Type {
get {
return rendererTypeName;
}
}
}
/** Factory class for BillboardParticleRenderer */
public class BillboardParticleRendererFactory : ParticleSystemRendererFactory
{
static string rendererTypeName = "billboard";
public BillboardParticleRendererFactory() {
}
/// @copydoc FactoryObj::createInstance
public override ParticleSystemRenderer CreateInstance(string name) {
return new BillboardParticleRenderer();
}
/// @copydoc FactoryObj::destroyInstance
public override void DestroyInstance(ParticleSystemRenderer inst) {
}
public override string Type {
get {
return rendererTypeName;
}
}
};
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
#region Using directives
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
using System.Workflow.ComponentModel;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Workflow.Runtime;
using System.Xml;
#endregion
namespace System.Workflow.Activities
{
internal static class CorrelationResolver
{
static Dictionary<Type, CorrelationMethodResolver> cachedTypeResolver = new Dictionary<Type, CorrelationMethodResolver>();
static object mutex = new object();
internal static bool IsInitializingMember(Type interfaceType, string memberName, object[] methodArgs)
{
if (interfaceType == null)
throw new ArgumentNullException("interfaceType");
if (memberName == null)
throw new ArgumentNullException("memberName");
if (memberName.Length == 0)
throw new ArgumentException(SR.GetString(SR.Error_EventNameMissing));
ICorrelationProvider correlationProvider = CorrelationResolver.GetCorrelationProvider(interfaceType);
return correlationProvider.IsInitializingMember(interfaceType, memberName, methodArgs);
}
internal static ICollection<CorrelationProperty> ResolveCorrelationValues(Type interfaceType, string eventName, object[] eventArgs, bool provideInitializerTokens)
{
if (interfaceType == null)
throw new ArgumentNullException("interfaceType");
if (eventName == null)
throw new ArgumentNullException("eventName");
if (eventName.Length == 0)
throw new ArgumentException(SR.GetString(SR.Error_EventNameMissing));
ICorrelationProvider correlationProvider = CorrelationResolver.GetCorrelationProvider(interfaceType);
return correlationProvider.ResolveCorrelationPropertyValues(interfaceType, eventName, eventArgs, provideInitializerTokens);
}
internal static ICorrelationProvider GetCorrelationProvider(Type interfaceType)
{
CorrelationMethodResolver resolver = GetResolver(interfaceType);
return resolver.CorrelationProvider;
}
private static CorrelationMethodResolver GetResolver(Type interfaceType)
{
CorrelationMethodResolver resolver = null;
cachedTypeResolver.TryGetValue(interfaceType, out resolver);
if (resolver == null)
{
lock (mutex)
{
cachedTypeResolver.TryGetValue(interfaceType, out resolver);
if (resolver == null)
{
resolver = new CorrelationMethodResolver(interfaceType);
cachedTypeResolver.Add(interfaceType, resolver);
}
}
}
return resolver;
}
}
internal sealed class CorrelationMethodResolver
{
Type interfaceType;
// a correlation provider for each interface type
ICorrelationProvider correlationProvider;
object corrProviderSync = new object();
internal CorrelationMethodResolver(Type interfaceType)
{
this.interfaceType = interfaceType;
}
internal ICorrelationProvider CorrelationProvider
{
get
{
if (this.correlationProvider == null)
{
lock (this.corrProviderSync)
{
if (this.correlationProvider == null)
{
ICorrelationProvider provider = null;
object[] corrProviderAttribs = this.interfaceType.GetCustomAttributes(typeof(CorrelationProviderAttribute), true);
if (corrProviderAttribs.Length == 0)
{
corrProviderAttribs = this.interfaceType.GetCustomAttributes(typeof(ExternalDataExchangeAttribute), true);
object[] corrParameterAttribs = this.interfaceType.GetCustomAttributes(typeof(CorrelationParameterAttribute), true);
if (corrProviderAttribs.Length != 0 && corrParameterAttribs.Length != 0)
{
// no provider specified but it is a data exchange correlation service
// hence use our default correlation
provider = new DefaultCorrelationProvider(this.interfaceType);
}
else
{
// opaque interface with no correlation
provider = new NonCorrelatedProvider();
}
}
else
{
CorrelationProviderAttribute cpattrib = corrProviderAttribs[0] as CorrelationProviderAttribute;
Type providerType = cpattrib.CorrelationProviderType;
provider = Activator.CreateInstance(providerType) as ICorrelationProvider;
}
System.Threading.Thread.MemoryBarrier();
this.correlationProvider = provider;
}
}
}
return this.correlationProvider;
}
}
}
internal sealed class CorrelationPropertyValue
{
string name;
string locationPath;
int signaturePosition;
internal CorrelationPropertyValue(string name, string locationPath, int signaturePosition)
{
this.name = name;
this.locationPath = locationPath;
this.signaturePosition = signaturePosition;
}
internal object GetValue(object[] args)
{
if (args.Length <= this.signaturePosition)
throw new ArgumentOutOfRangeException("args");
object arg = args[this.signaturePosition];
if (arg == null)
return arg;
Type type = arg.GetType();
object val = arg;
if (this.locationPath.Length != 0)
{
string[] split = locationPath.Split(new Char[] { '.' });
for (int i = 1; i < split.Length; i++)
{
string s = split[i];
if (null == arg)
break;
val = type.InvokeMember(s, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty, null, arg, null, null);
MemberInfo[] mInfos = type.GetMember(s, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty);
type = GetMemberType(mInfos[0]);
arg = val;
}
}
return val;
}
internal string Name
{
get
{
return this.name;
}
}
private Type GetMemberType(MemberInfo mInfo)
{
Type type = null;
switch (mInfo.MemberType)
{
case MemberTypes.Field:
type = ((FieldInfo)mInfo).FieldType;
break;
case MemberTypes.Property:
type = ((PropertyInfo)mInfo).PropertyType;
break;
default:
Debug.Assert(false, "locationPath points to something other than a Field/Property");
return null;
}
return type;
}
}
internal sealed class DefaultCorrelationProvider : ICorrelationProvider
{
Type interfaceType;
// map of method name to correlation properties
Dictionary<string, CorrelationPropertyValue[]> cachedCorrelationProperties;
object cachedCorrelationPropertiesSync = new object();
// cached initializers
// map operation to bool flag to indicate events
Dictionary<string, bool> initializerCorrelationPropertys = null;
object initializerCorrelationPropertysSync = new object();
internal DefaultCorrelationProvider(Type interfaceType)
{
this.cachedCorrelationProperties = new Dictionary<string, CorrelationPropertyValue[]>();
this.interfaceType = interfaceType;
}
ICollection<CorrelationProperty> ICorrelationProvider.ResolveCorrelationPropertyValues(Type interfaceType, string methodName, object[] methodArgs, bool provideInitializerTokens)
{
CorrelationPropertyValue[] correlationProperties = null;
if (methodArgs == null || provideInitializerTokens)
{
return null; // no initializer specific token to return
}
this.cachedCorrelationProperties.TryGetValue(methodName, out correlationProperties);
if (correlationProperties == null)
{
lock (this.cachedCorrelationPropertiesSync)
{
this.cachedCorrelationProperties.TryGetValue(methodName, out correlationProperties);
if (correlationProperties == null)
{
correlationProperties = GetCorrelationProperties(interfaceType, methodName);
this.cachedCorrelationProperties.Add(methodName, correlationProperties);
}
}
}
List<CorrelationProperty> predicates = new List<CorrelationProperty>();
for (int i = 0; i < correlationProperties.Length; i++)
{
predicates.Add(new CorrelationProperty(correlationProperties[i].Name, correlationProperties[i].GetValue(methodArgs)));
}
return predicates;
}
private Dictionary<string, bool> InitializerCorrelationPropertys
{
get
{
if (this.initializerCorrelationPropertys == null)
{
lock (this.initializerCorrelationPropertysSync)
{
if (this.initializerCorrelationPropertys == null)
{
Dictionary<string, bool> members = new Dictionary<string, bool>();
// note this is separated out since we may need to distinguish between events & methods
foreach (EventInfo member in this.interfaceType.GetEvents())
{
if ((member.GetCustomAttributes(typeof(CorrelationInitializerAttribute), true)).Length > 0)
{
members.Add(member.Name, true);
}
}
foreach (MethodInfo member in this.interfaceType.GetMethods())
{
if ((member.GetCustomAttributes(typeof(CorrelationInitializerAttribute), true)).Length > 0)
{
members.Add(member.Name, false);
}
}
this.initializerCorrelationPropertys = members;
}
}
}
return this.initializerCorrelationPropertys;
}
}
bool ICorrelationProvider.IsInitializingMember(Type interfaceType, string memberName, object[] methodArgs)
{
return InitializerCorrelationPropertys.ContainsKey(memberName);
}
private CorrelationPropertyValue[] GetCorrelationProperties(Type interfaceType, string methodName)
{
CorrelationPropertyValue[] correlationProperties = null;
if (interfaceType.GetCustomAttributes(typeof(ExternalDataExchangeAttribute), true).Length == 0)
throw new InvalidOperationException(SR.GetString(SR.Error_ExternalDataExchangeException, interfaceType.AssemblyQualifiedName));
List<Object> correlationParamAttributes = new List<Object>();
correlationParamAttributes.AddRange(GetCorrelationParameterAttributes(interfaceType));
if (correlationParamAttributes.Count == 0)
throw new InvalidOperationException(SR.GetString(SR.Error_CorrelationParameterException, interfaceType.AssemblyQualifiedName));
correlationProperties = new CorrelationPropertyValue[correlationParamAttributes.Count];
Dictionary<String, CorrelationAliasAttribute> corrAliases = null;
MethodInfo methodInfo = null;
GetMethodInfo(interfaceType, methodName, out methodInfo, out corrAliases);
if (methodInfo == null)
{
throw new MissingMethodException(interfaceType.AssemblyQualifiedName, methodName);
}
ParameterInfo[] parameters = methodInfo.GetParameters();
int i = 0;
foreach (CorrelationParameterAttribute paramAttribute in correlationParamAttributes)
{
String location = paramAttribute.Name;
CorrelationAliasAttribute aliasAttribute = GetMatchingCorrelationAlias(paramAttribute, corrAliases, correlationParamAttributes.Count == 1);
if (aliasAttribute != null)
location = aliasAttribute.Path;
CorrelationPropertyValue value = GetCorrelationProperty(parameters, paramAttribute.Name, location);
if (value == null)
throw new InvalidOperationException(SR.GetString(SR.Error_CorrelationParameterException, interfaceType.AssemblyQualifiedName, paramAttribute.Name, methodName));
correlationProperties[i++] = value;
}
return correlationProperties;
}
private CorrelationAliasAttribute GetMatchingCorrelationAlias(CorrelationParameterAttribute paramAttribute, Dictionary<String, CorrelationAliasAttribute> correlationAliases, bool defaultParameter)
{
CorrelationAliasAttribute corrAlias = null;
if (correlationAliases == null) return null;
if (defaultParameter)
{
if (correlationAliases.TryGetValue("", out corrAlias))
{
return corrAlias;
}
}
correlationAliases.TryGetValue(paramAttribute.Name, out corrAlias);
return corrAlias;
}
private CorrelationPropertyValue GetCorrelationProperty(ParameterInfo[] parameters, String propertyName, String location)
{
string[] split = location.Split(new Char[] { '.' });
if (split.Length == 1 && parameters.Length == 2)
{
if (typeof(ExternalDataEventArgs).IsAssignableFrom(parameters[1].ParameterType))
{
string aliasedLocation = "e." + location;
return GetCorrelationProperty(parameters, propertyName, "e", aliasedLocation);
}
}
string parameterName = split[0];
return GetCorrelationProperty(parameters, propertyName, parameterName, location);
}
private void GetMethodInfo(Type interfaceType, string methodName, out MethodInfo methodInfo, out Dictionary<String, CorrelationAliasAttribute> correlationAliases)
{
correlationAliases = new Dictionary<String, CorrelationAliasAttribute>();
Object[] customAttrs = null;
methodInfo = null;
// check events
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
EventInfo eventInfo = interfaceType.GetEvent(methodName, bindingFlags);
if (eventInfo != null)
{
customAttrs = eventInfo.GetCustomAttributes(typeof(CorrelationAliasAttribute), true);
if (customAttrs == null || customAttrs.Length == 0)
{
customAttrs = eventInfo.EventHandlerType.GetCustomAttributes(typeof(CorrelationAliasAttribute), true);
}
MethodInfo[] methInfo = eventInfo.EventHandlerType.GetMethods();
methodInfo = methInfo[0];
}
else
{
// check methods
methodInfo = interfaceType.GetMethod(methodName, bindingFlags);
if (methodInfo == null)
{
throw new MissingMethodException(interfaceType.AssemblyQualifiedName, methodName);
}
customAttrs = methodInfo.GetCustomAttributes(typeof(CorrelationAliasAttribute), true);
}
foreach (CorrelationAliasAttribute aliasAttribute in customAttrs)
{
if (customAttrs.Length > 1)
{
Debug.Assert(aliasAttribute.Name != null);
if (aliasAttribute.Name == null)
throw new ArgumentNullException("ParameterName");
}
correlationAliases.Add(aliasAttribute.Name == null ? "" : aliasAttribute.Name, aliasAttribute);
}
}
private CorrelationPropertyValue GetCorrelationProperty(ParameterInfo[] parameters, string propertyName, string parameterName, string location)
{
for (int j = 0; parameters != null && j < parameters.Length; j++)
{
ParameterInfo param = parameters[j];
if (param.Name == parameterName)
{
// parameter match
return new CorrelationPropertyValue(propertyName, location, param.Position);
}
}
return null;
}
private object[] GetCorrelationParameterAttributes(Type type)
{
return type.GetCustomAttributes(typeof(CorrelationParameterAttribute), true);
}
}
internal sealed class NonCorrelatedProvider : ICorrelationProvider
{
internal NonCorrelatedProvider()
{
}
ICollection<CorrelationProperty> ICorrelationProvider.ResolveCorrelationPropertyValues(Type interfaceType, string methodName, object[] methodArgs, bool provideInitializerTokens)
{
// non correlated
// no values to return
return null;
}
bool ICorrelationProvider.IsInitializingMember(Type interfaceType, string memberName, object[] methodArgs)
{
return true;
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEditor;
using UnityEngine;
namespace Fungus.EditorUtils
{
[CanEditMultipleObjects]
[CustomEditor (typeof(View))]
public class ViewEditor : Editor
{
static Color viewColor = Color.yellow;
protected SerializedProperty primaryAspectRatioProp;
protected SerializedProperty secondaryAspectRatioProp;
protected SerializedProperty viewSizeProp;
// Draw Views when they're not selected
#if UNITY_5_0
[DrawGizmo(GizmoType.NotSelected | GizmoType.SelectedOrChild)]
#else
[DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.InSelectionHierarchy)]
#endif
static void RenderCustomGizmo(Transform objectTransform, GizmoType gizmoType)
{
View view = objectTransform.gameObject.GetComponent<View>();
if (view != null)
{
DrawView(view, false);
}
}
protected virtual Vector2 LookupAspectRatio(int index)
{
switch (index)
{
default:
case 1:
return new Vector2(4, 3);
case 2:
return new Vector2(3, 2);
case 3:
return new Vector2(16, 10);
case 4:
return new Vector2(17, 10);
case 5:
return new Vector2(16, 9);
case 6:
return new Vector2(2, 1);
case 7:
return new Vector2(3, 4);
case 8:
return new Vector2(2, 3);
case 9:
return new Vector2(10, 16);
case 10:
return new Vector2(10, 17);
case 11:
return new Vector2(9, 16);
case 12:
return new Vector2(1, 2);
}
}
protected virtual void OnEnable()
{
primaryAspectRatioProp = serializedObject.FindProperty ("primaryAspectRatio");
secondaryAspectRatioProp = serializedObject.FindProperty ("secondaryAspectRatio");
viewSizeProp = serializedObject.FindProperty("viewSize");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(viewSizeProp);
string[] ratios = { "<None>", "Landscape / 4:3", "Landscape / 3:2", "Landscape / 16:10", "Landscape / 17:10", "Landscape / 16:9", "Landscape / 2:1", "Portrait / 3:4", "Portrait / 2:3", "Portrait / 10:16", "Portrait / 10:17", "Portrait / 9:16", "Portrait / 1:2" };
EditorGUILayout.PropertyField(primaryAspectRatioProp, new GUIContent("Primary Aspect Ratio", "Width and height values that define the primary aspect ratio (e.g. 4:3)"));
int primaryIndex = EditorGUILayout.Popup("Select Aspect Ratio", 0, ratios);
if (primaryIndex > 0)
{
primaryAspectRatioProp.vector2Value = LookupAspectRatio(primaryIndex);
}
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(secondaryAspectRatioProp, new GUIContent("Secondary Aspect Ratio", "Width and height values that define the primary aspect ratio (e.g. 4:3)"));
int secondaryIndex = EditorGUILayout.Popup("Select Aspect Ratio", 0, ratios);
if (secondaryIndex > 0)
{
secondaryAspectRatioProp.vector2Value = LookupAspectRatio(secondaryIndex);
}
EditorGUILayout.Separator();
if (EditorGUI.EndChangeCheck())
{
// Avoid divide by zero errors
if (primaryAspectRatioProp.vector2Value.y == 0)
{
primaryAspectRatioProp.vector2Value = new Vector2(primaryAspectRatioProp.vector2Value.x, 1f);
}
if (secondaryAspectRatioProp.vector2Value.y == 0)
{
secondaryAspectRatioProp.vector2Value = new Vector2(secondaryAspectRatioProp.vector2Value.x, 1f);
}
SceneView.RepaintAll();
}
serializedObject.ApplyModifiedProperties();
}
protected virtual void OnSceneGUI ()
{
View t = target as View;
if (t.enabled)
{
EditViewBounds();
}
}
protected virtual void EditViewBounds()
{
View view = target as View;
DrawView(view, true);
Vector3 pos = view.transform.position;
float viewSize = CalculateLocalViewSize(view);
Vector3[] handles = new Vector3[2];
handles[0] = view.transform.TransformPoint(new Vector3(0, -viewSize, 0));
handles[1] = view.transform.TransformPoint(new Vector3(0, viewSize, 0));
Handles.color = Color.white;
for (int i = 0; i < 2; ++i)
{
Vector3 newPos = Handles.FreeMoveHandle(handles[i],
Quaternion.identity,
HandleUtility.GetHandleSize(pos) * 0.1f,
Vector3.zero,
#if UNITY_5_6_OR_NEWER
Handles.CubeHandleCap);
#else
Handles.CubeCap);
#endif
if (newPos != handles[i])
{
Undo.RecordObject(view, "Set View Size");
view.ViewSize = (newPos - pos).magnitude;
EditorUtility.SetDirty(view);
break;
}
}
}
public static void DrawView(View view, bool drawInterior)
{
float height = CalculateLocalViewSize(view);
float widthA = height * (view.PrimaryAspectRatio.x / view.PrimaryAspectRatio.y);
float widthB = height * (view.SecondaryAspectRatio.x / view.SecondaryAspectRatio.y);
Color transparent = new Color(1,1,1,0f);
Color fill = viewColor;
Color outline = viewColor;
bool highlight = Selection.activeGameObject == view.gameObject;
var flowchart = FlowchartWindow.GetFlowchart();
if (flowchart != null)
{
var selectedCommands = flowchart.SelectedCommands;
foreach (var command in selectedCommands)
{
MoveToView moveToViewCommand = command as MoveToView;
if (moveToViewCommand != null &&
moveToViewCommand.TargetView == view)
{
highlight = true;
}
else
{
FadeToView fadeToViewCommand = command as FadeToView;
if (fadeToViewCommand != null &&
fadeToViewCommand.TargetView == view)
{
highlight = true;
}
}
}
}
if (highlight)
{
fill = outline = Color.green;
fill.a = 0.1f;
outline.a = 1f;
}
else
{
fill.a = 0.1f;
outline.a = 0.5f;
}
if (drawInterior)
{
// Draw left box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(-widthB, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(-widthB, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(-widthA, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(-widthA, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, fill, transparent);
}
// Draw right box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(widthA, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(widthA, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(widthB, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(widthB, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, fill, transparent);
}
// Draw inner box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(-widthA, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(-widthA, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(widthA, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(widthA, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, transparent, outline );
}
}
// Draw outer box
{
Vector3[] verts = new Vector3[4];
verts[0] = view.transform.TransformPoint(new Vector3(-widthB, -height, 0));
verts[1] = view.transform.TransformPoint(new Vector3(-widthB, height, 0));
verts[2] = view.transform.TransformPoint(new Vector3(widthB, height, 0));
verts[3] = view.transform.TransformPoint(new Vector3(widthB, -height, 0));
Handles.DrawSolidRectangleWithOutline(verts, transparent, outline );
}
}
// Calculate view size in local coordinates
// Kinda expensive, but accurate and only called in editor.
static float CalculateLocalViewSize(View view)
{
return view.transform.InverseTransformPoint(view.transform.position + new Vector3(0, view.ViewSize, 0)).magnitude;
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System;
namespace VNEngine
{
// Creates a new menu when you right click in the Hierarchy pane.
// Allows the user to easily create dialogue elements
public class VNEngineEditor : MonoBehaviour
{
[MenuItem("VN Engine/Documentation")]
private static void OpenDocumentation()
{
Application.OpenURL(Application.dataPath + "/VN Engine/README.pdf");
}
// Imports a .txt file specified by the user.
[MenuItem("VN Engine/Import script (from .txt file)")]
private static void ImportTxtScriptFile()
{
string path = EditorUtility.OpenFilePanel("Select a script file to import", "", "txt");
if (string.IsNullOrEmpty(path))
{
return;
}
Debug.Log("Reading in .txt script file: " + path);
// Read the file
string line;
System.IO.StreamReader file = new System.IO.StreamReader(path);
// Create a child object to hold all elements created from this file
Transform import_parent = (new GameObject(Path.GetFileNameWithoutExtension(path))).transform;
ConversationManager cur_conversation = null;
// Read it line by line
while ((line = file.ReadLine()) != null)
{
// Continue if it's an empty line
if (String.IsNullOrEmpty(line))
continue;
string[] split_line = line.Split(new char[] { ':' }, 2);
// Create a new conversation
if (line.StartsWith("Conversation", true, System.Globalization.CultureInfo.InvariantCulture))
{
GameObject go = new GameObject(split_line[1] + " Conversation");
go.transform.parent = import_parent;
ConversationManager new_conv = go.AddComponent<ConversationManager>();
if (cur_conversation != null)
{
cur_conversation.start_conversation_when_done = new_conv;
}
cur_conversation = new_conv;
}
else if (line.StartsWith("EnterActor", true, System.Globalization.CultureInfo.InvariantCulture))
{
GameObject go = new GameObject("Enter " + split_line[1]);
go.transform.parent = cur_conversation.transform;
EnterActorNode node = go.AddComponent<EnterActorNode>();
node.actor_name = split_line[1];
}
else if (line.StartsWith("ExitActor", true, System.Globalization.CultureInfo.InvariantCulture))
{
GameObject go = new GameObject("Exit " + split_line[1]);
go.transform.parent = cur_conversation.transform;
ExitActorNode node = go.AddComponent<ExitActorNode>();
node.actor_name = split_line[1];
}
else if (line.StartsWith("SetBackground", true, System.Globalization.CultureInfo.InvariantCulture))
{
GameObject go = new GameObject("Set Background " + split_line[1]);
go.transform.parent = cur_conversation.transform;
SetBackground node = go.AddComponent<SetBackground>();
try
{
node.sprite = Resources.Load<Sprite>(split_line[1]);
}
catch (Exception e)
{
Debug.Log("Error loading audio clip " + split_line[1] + ". Make sure your named clip matches the resource. Ex: some_folder/cool_music");
}
}
else if (line.StartsWith("SetMusic", true, System.Globalization.CultureInfo.InvariantCulture))
{
GameObject go = new GameObject("Set Music " + split_line[1]);
go.transform.parent = cur_conversation.transform;
SetMusicNode node = go.AddComponent<SetMusicNode>();
// If possible, load the necessary resource
try
{
node.new_music = Resources.Load<AudioClip>(split_line[1]);
}
catch (Exception e)
{
Debug.Log("Error loading audio clip " + split_line[1] + ". Make sure your named clip matches the resource. Ex: some_folder/cool_music");
}
}
// ADD MORE HERE IF YOU WISH TO EXTEND THE IMPORTING FUNCTIONALITY
//
//
//
//
//
// Must be a line of dialogue
else if (split_line.Length == 2)
{
GameObject go = new GameObject(split_line[0]);
go.transform.parent = cur_conversation.transform;
DialogueNode node = go.AddComponent<DialogueNode>();
node.actor = split_line[0];
node.textbox_title = split_line[0];
node.text = split_line[1];
}
}
file.Close();
Debug.Log("Done importing script: " + path);
}
[MenuItem("GameObject/VN Engine/Create DialogueCanvas", false, 0)]
private static void CreateDialogueCanvas(MenuCommand menuCommand)
{
GameObject go = PrefabUtility.InstantiatePrefab(Resources.Load("DialogueCanvas", typeof(GameObject))) as GameObject; // Create new object
go.name = "DialogueCanvas";
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
}
[MenuItem("GameObject/VN Engine/New Conversation", false, 0)]
private static void CreateConversation(MenuCommand menuCommand)
{
GameObject go = new GameObject("Conversation"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ConversationManager>();
}
[MenuItem("GameObject/VN Engine/Add Dialogue", false, 0)]
private static void AddDialogue(MenuCommand menuCommand)
{
GameObject go = new GameObject("Dialogue"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<DialogueNode>();
go.AddComponent<AudioSource>();
go.GetComponent<AudioSource>().playOnAwake = false;
}
[MenuItem("GameObject/VN Engine/Actors/Enter Actor", false, 5)]
private static void EnterActor(MenuCommand menuCommand)
{
GameObject go = new GameObject("Enter Actor"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<EnterActorNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Change Actor Image", false, 0)]
private static void ChangeActorImage(MenuCommand menuCommand)
{
GameObject go = new GameObject("Change Actor Image"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ChangeActorImageNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Exit Actor", false, 0)]
private static void ExitActor(MenuCommand menuCommand)
{
GameObject go = new GameObject("Exit Actor"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ExitActorNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Exit All Actors", false, 0)]
private static void ExitAllActors(MenuCommand menuCommand)
{
GameObject go = new GameObject("Exit All Actors"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ExitAllActorsNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Play Actor Animation", false, 0)]
private static void PlayActorAnimationNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Play Actor Animation"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<PlayActorAnimationNode>();
}
[MenuItem("GameObject/VN Engine/Change Conversation", false, 0)]
private static void ChangeConversation(MenuCommand menuCommand)
{
GameObject go = new GameObject("Change Conversation"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ChangeConversationNode>();
}
[MenuItem("GameObject/VN Engine/Misc/Wait", false, 0)]
private static void Wait(MenuCommand menuCommand)
{
GameObject go = new GameObject("Wait"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<WaitNode>();
}
[MenuItem("GameObject/VN Engine/Branching/Show Choices", false, 0)]
private static void ShowChoicesNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Show Choices"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ChoiceNode>();
}
[MenuItem("GameObject/VN Engine/Branching/If Then", false, 0)]
private static void IfNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("If"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<IfNode>();
}
[MenuItem("GameObject/VN Engine/Images/Set Background", false, 0)]
private static void SetBackground(MenuCommand menuCommand)
{
GameObject go = new GameObject("Set Background"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<SetBackground>();
}
[MenuItem("GameObject/VN Engine/Misc/Item", false, 0)]
private static void ItemNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Item"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ItemNode>();
}
[MenuItem("GameObject/VN Engine/Misc/Hide or Show UI", false, 0)]
private static void HideShowUI(MenuCommand menuCommand)
{
GameObject go = new GameObject("Hide/Show UI"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<HideShowUINode>();
}
[MenuItem("GameObject/VN Engine/Images/Fade in from Black", false, 0)]
private static void FadeInFromBlack(MenuCommand menuCommand)
{
GameObject go = Instantiate(Resources.Load("Conversation Pieces/Fade in from Black", typeof(GameObject))) as GameObject; // Create new object
go.name = "Fade in from Black";
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
}
[MenuItem("GameObject/VN Engine/Images/Fade out to Black", false, 0)]
private static void FadeToBlack(MenuCommand menuCommand)
{
GameObject go = Instantiate(Resources.Load("Conversation Pieces/Fade out to Black", typeof(GameObject))) as GameObject; // Create new object
go.name = "Fade out to Black";
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
}
[MenuItem("GameObject/VN Engine/Actors/Move Actor Inwards", false, 0)]
private static void MoveActorInwardsNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Move Actor Inwards"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<MoveActorInwardsNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Move Actor Outwards", false, 0)]
private static void MoveActorOutwardsNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Move Actor Outwards"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<MoveActorOutwardsNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Bring Actor Forward", false, 0)]
private static void BringActorForwardNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Bring Actor Forward"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<BringActorForwardNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Bring Actor Backward", false, 0)]
private static void BringActorBackwardNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Bring Actor Backward"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<BringActorBackwardNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Actor Change Side", false, 0)]
private static void ActorChangeSideNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Actor Change Side"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ChangeSideNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Darken Actor", false, 0)]
private static void DarkenActorNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Darken Actor"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<DarkenActorNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Brighten Actor", false, 0)]
private static void BrightenActorNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Brighten Actor"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<BrightenActorNode>();
}
[MenuItem("GameObject/VN Engine/Actors/Flip Actor", false, 0)]
private static void FlipActorFacingNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Flip Actor"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<FlipActorFacingNode>();
}
[MenuItem("GameObject/VN Engine/Sound/Play Sound Effect", false, 0)]
private static void PlaySoundEffectNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Play Sound Effect"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<PlaySoundEffectNode>();
go.AddComponent<AudioSource>();
go.GetComponent<AudioSource>().playOnAwake = false;
}
[MenuItem("GameObject/VN Engine/Sound/Play Music", false, 0)]
private static void PlayMusicNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Play Music"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<SetMusicNode>();
}
[MenuItem("GameObject/VN Engine/Sound/Fade out Music", false, 0)]
private static void FadeOutMusicNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Fade out Music"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<SetMusicNode>();
go.GetComponent<SetMusicNode>().fadeOutPreviousMusic = true;
go.GetComponent<SetMusicNode>().fadeOutTime = 5.0f;
}
[MenuItem("GameObject/VN Engine/Sound/Set Ambience Sounds", false, 0)]
private static void SetAmbienceSoundsNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Set Ambience"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<AmbienceNode>();
}
[MenuItem("GameObject/VN Engine/Sound/Change Audio Snapshot", false, 0)]
private static void ChangeAudioSnapshotNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Change Audio Snapshot Node"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ChangeAudioSnapshotNode>();
}
[MenuItem("GameObject/VN Engine/Perform Actions", false, 0)]
private static void PerformActionsNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Perform Actions"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<PerformActionsNode>();
}
[MenuItem("GameObject/VN Engine/Branching/Load Scene", false, 0)]
private static void LoadSceneNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Load Scene"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<LoadSceneNode>();
}
[MenuItem("GameObject/VN Engine/Misc/Clear Text", false, 0)]
private static void ClearTextNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Clear Text"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<ClearTextNode>();
}
[MenuItem("GameObject/VN Engine/Misc/Can Save", false, 0)]
private static void CanSaveNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Can Save"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<CanSaveNode>();
}
[MenuItem("GameObject/VN Engine/Images/Static Image", false, 0)]
private static void StaticImageNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Static Image"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<StaticImageNode>();
}
[MenuItem("GameObject/VN Engine/Misc/Set Autoplay", false, 0)]
private static void SetAutoplayNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Set Autoplay"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<SetAutoplayNode>();
}
[MenuItem("GameObject/VN Engine/Stats/Alter Stats", false, 0)]
private static void AlterStatsNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Alter Stats"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<AlterStatNode>();
}
[MenuItem("GameObject/VN Engine/Stats/Generate Random Number", false, 0)]
private static void GenerateRandomNumberNode(MenuCommand menuCommand)
{
GameObject go = new GameObject("Generate Random Number"); // Create new object
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
go.AddComponent<GenerateRandomNumberNode>();
}
[MenuItem("GameObject/VN Engine/Video/Play Video", false, 0)]
private static void PlayVideo(MenuCommand menuCommand)
{
GameObject go = Instantiate(Resources.Load("Conversation Pieces/Play Video", typeof(GameObject))) as GameObject; // Create new object
go.name = "Play Video";
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Parent the new object
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); // Register the creation in the undo system
Selection.activeObject = go;
}
}
}
| |
namespace StripeTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class AccountServiceTest : BaseStripeTest
{
private const string AccountId = "acct_123";
private readonly AccountService service;
private readonly AccountCreateOptions createOptions;
private readonly AccountUpdateOptions updateOptions;
private readonly AccountListOptions listOptions;
private readonly AccountRejectOptions rejectOptions;
public AccountServiceTest(
StripeMockFixture stripeMockFixture,
MockHttpClientFixture mockHttpClientFixture)
: base(stripeMockFixture, mockHttpClientFixture)
{
this.service = new AccountService(this.StripeClient);
this.createOptions = new AccountCreateOptions
{
Type = AccountType.Custom,
BusinessProfile = new AccountBusinessProfileOptions
{
Name = "business name",
},
BusinessType = "company",
Capabilities = new AccountCapabilitiesOptions
{
CardPayments = new AccountCapabilitiesCardPaymentsOptions
{
Requested = true,
},
Transfers = new AccountCapabilitiesTransfersOptions
{
Requested = true,
},
},
Company = new AccountCompanyOptions
{
Address = new AddressOptions
{
State = "CA",
City = "City",
Line1 = "Line1",
Line2 = "Line2",
PostalCode = "90210",
Country = "US",
},
Name = "Company name",
Verification = new AccountCompanyVerificationOptions
{
Document = new AccountCompanyVerificationDocumentOptions
{
Back = "file_back",
Front = "file_front",
},
},
},
ExternalAccount = "tok_visa_debit",
Settings = new AccountSettingsOptions
{
Branding = new AccountSettingsBrandingOptions
{
Logo = "file_123",
},
CardPayments = new AccountSettingsCardPaymentsOptions
{
DeclineOn = new AccountSettingsCardPaymentsDeclineOnOptions
{
AvsFailure = true,
CvcFailure = true,
},
StatementDescriptorPrefix = "STR",
},
Payments = new AccountSettingsPaymentsOptions
{
StatementDescriptor = "STRIPE 123",
},
Payouts = new AccountSettingsPayoutsOptions
{
DebitNegativeBalances = true,
Schedule = new AccountSettingsPayoutsScheduleOptions
{
Interval = "monthly",
MonthlyAnchor = "10",
},
},
},
TosAcceptance = new AccountTosAcceptanceOptions
{
Date = DateTime.Parse("Mon, 01 Jan 2001 00:00:00Z"),
Ip = "127.0.0.1",
UserAgent = "User-Agent",
},
};
this.updateOptions = new AccountUpdateOptions
{
Metadata = new Dictionary<string, string>
{
{ "key", "value" },
},
};
this.rejectOptions = new AccountRejectOptions
{
Reason = "terms_of_service",
};
this.listOptions = new AccountListOptions
{
Limit = 1,
};
}
[Fact]
public void Create()
{
var account = this.service.Create(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public async Task CreateAsync()
{
var account = await this.service.CreateAsync(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public void Delete()
{
var deleted = this.service.Delete(AccountId);
this.AssertRequest(HttpMethod.Delete, "/v1/accounts/acct_123");
Assert.NotNull(deleted);
}
[Fact]
public async Task DeleteAsync()
{
var deleted = await this.service.DeleteAsync(AccountId);
this.AssertRequest(HttpMethod.Delete, "/v1/accounts/acct_123");
Assert.NotNull(deleted);
}
[Fact]
public void Get()
{
var account = this.service.Get(AccountId);
this.AssertRequest(HttpMethod.Get, "/v1/accounts/acct_123");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public async Task GetAsync()
{
var account = await this.service.GetAsync(AccountId);
this.AssertRequest(HttpMethod.Get, "/v1/accounts/acct_123");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public void GetSelf()
{
var account = this.service.GetSelf();
this.AssertRequest(HttpMethod.Get, "/v1/account");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public async Task GetSelfAsync()
{
var account = await this.service.GetSelfAsync();
this.AssertRequest(HttpMethod.Get, "/v1/account");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public void List()
{
var accounts = this.service.List(this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/accounts");
Assert.NotNull(accounts);
Assert.Equal("list", accounts.Object);
Assert.Single(accounts.Data);
Assert.Equal("account", accounts.Data[0].Object);
}
[Fact]
public async Task ListAsync()
{
var accounts = await this.service.ListAsync(this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/accounts");
Assert.NotNull(accounts);
Assert.Equal("list", accounts.Object);
Assert.Single(accounts.Data);
Assert.Equal("account", accounts.Data[0].Object);
}
[Fact]
public void ListAutoPaging()
{
var account = this.service.ListAutoPaging(this.listOptions).First();
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public async Task ListAutoPagingAsync()
{
var account = await this.service.ListAutoPagingAsync(this.listOptions).FirstAsync();
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public void Reject()
{
var account = this.service.Reject(AccountId, this.rejectOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123/reject");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public async Task RejectAsync()
{
var account = await this.service.RejectAsync(AccountId, this.rejectOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123/reject");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public void Update()
{
var account = this.service.Update(AccountId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
[Fact]
public async Task UpdateAsync()
{
var account = await this.service.UpdateAsync(AccountId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123");
Assert.NotNull(account);
Assert.Equal("account", account.Object);
}
}
}
| |
using IdentityModel;
using IdentityServer4.Events;
using IdentityServer4.Quickstart.UI;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServerAspNetIdentity.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Host.Quickstart.Account
{
[SecurityHeaders]
[AllowAnonymous]
public class ExternalController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IEventService _events;
public ExternalController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IEventService events)
{
_userManager = userManager;
_signInManager = signInManager;
_interaction = interaction;
_clientStore = clientStore;
_events = events;
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
[HttpGet]
public async Task<IActionResult> Challenge(string provider, string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/";
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
if (AccountOptions.WindowsAuthenticationSchemeName == provider)
{
// windows authentication needs special handling
return await ProcessWindowsLoginAsync(returnUrl);
}
else
{
// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", provider },
}
};
return Challenge(props, provider);
}
}
/// <summary>
/// Post processing of external authentication
/// </summary>
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUserAsync(provider, providerUserId, claims);
}
// this allows us to collect any additonal claims or properties
// for the specific prtotocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
// we must issue the cookie maually, and can't use the SignInManager because
// it doesn't expose an API to issue additional claims from the login workflow
var principal = await _signInManager.CreateUserPrincipalAsync(user);
additionalLocalClaims.AddRange(principal.Claims);
var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id;
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, name));
await HttpContext.SignInAsync(user.Id, name, provider, localSignInProps, additionalLocalClaims.ToArray());
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// validate return URL and redirect back to authorization endpoint or a local page
var returnUrl = result.Properties.Items["returnUrl"];
if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("~/");
}
private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
// see if windows auth has already been requested and succeeded
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
// we will issue the external cookie and then redirect the
// user back to the external callback, in essence, treating windows
// auth the same as any other external authentication mechanism
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("Callback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName },
}
};
var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
// add the groups as claims -- be careful if the number of groups is too large
if (AccountOptions.IncludeWindowsGroups)
{
var wi = wp.Identity as WindowsIdentity;
var groups = wi.Groups.Translate(typeof(NTAccount));
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
id.AddClaims(roles);
}
await HttpContext.SignInAsync(
IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
// trigger windows auth
// since windows auth don't support the redirect uri,
// this URL is re-triggered when we call challenge
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
private async Task<(ApplicationUser user, string provider, string providerUserId, IEnumerable<Claim> claims)>
FindUserFromExternalProviderAsync(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
var user = await _userManager.FindByLoginAsync(provider, providerUserId);
return (user, provider, providerUserId, claims);
}
private async Task<ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable<Claim> claims)
{
// create a list of claims that we want to transfer into our store
var filtered = new List<Claim>();
// user's display name
var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
if (name != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, name));
}
else
{
var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
if (first != null && last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
}
else if (first != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first));
}
else if (last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, last));
}
}
// email
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null)
{
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
var user = new ApplicationUser
{
UserName = Guid.NewGuid().ToString(),
};
var identityResult = await _userManager.CreateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
if (filtered.Any())
{
identityResult = await _userManager.AddClaimsAsync(user, filtered);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
return user;
}
private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var id_token = externalResult.Properties.GetTokenValue("id_token");
if (id_token != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
}
private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
}
}
| |
//BSD, 2014-present, WinterDev
//MatterHackers
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//Maxim's note on C++ version:
//see https://pdfium.googlesource.com/pdfium/+/master/third_party/agg23/agg_rasterizer_scanline_aa.cpp#35
// ...
// The author gratefully acknowleges the support of David Turner,
// Robert Wilhelm, and Werner Lemberg - the authors of the FreeType
// libray - in producing this work. See http://www.freetype.org for details.
//
// Initially the rendering algorithm was designed by David Turner and the
// other authors of the FreeType library - see the above notice. I nearly
// created a similar renderer, but still I was far from David's work.
// I completely redesigned the original code and adapted it for Anti-Grain
// ideas. Two functions - render_line and render_hline are the core of
// the algorithm - they calculate the exact coverage of each pixel cell
// of the polygon. I left these functions almost as is, because there's
// no way to improve the perfection - hats off to David and his group!
//
// All other code is very different from the original.
//
//----------------------------------------------------------------------------
using System;
using PixelFarm.Drawing;
namespace PixelFarm.CpuBlit.Rasterization.Lines
{
//-----------------------------------------------------------line_aa_vertex
// Vertex (x, y) with the distance to the next one. The last vertex has
// the distance between the last and the first points
struct LineAAVertex
{
public readonly int x;
public readonly int y;
public int len;
//
const int SIGDIFF = LineAA.SUBPIXEL_SCALE + (LineAA.SUBPIXEL_SCALE / 2);
public LineAAVertex(int x, int y)
{
this.x = x;
this.y = y;
len = 0;
}
public bool IsDiff(LineAAVertex val)
{
//*** NEED 64 bits long
long dx = val.x - x;
long dy = val.y - y;
if ((dx + dy) == 0)
{
return false;
}
return (len = AggMath.uround(Math.Sqrt(dx * dx + dy * dy))) > SIGDIFF;
}
}
class LineAAVertexSequence
{
ArrayList<LineAAVertex> _list = new ArrayList<LineAAVertex>();
public void AddVertex(LineAAVertex val)
{
int count = _list.Count;
if (count > 1)
{
LineAAVertex[] innerArray = _list.UnsafeInternalArray;
if (!innerArray[count - 2].IsDiff(innerArray[count - 1]))
{
_list.RemoveLast();
}
}
_list.Append(val);
}
//
public LineAAVertex this[int index] => _list[index];
public int Count => _list.Count;
//
public void Clear() => _list.Clear();
//
public void ModifyLast(LineAAVertex val)
{
_list.RemoveLast();
AddVertex(val);
}
public void Close(bool closed)
{
//----------------------
//iter backward
int count = _list.Count;
var innerArray = _list.UnsafeInternalArray;
while (count > 1)
{
if (innerArray[count - 2].IsDiff(innerArray[count - 1]))
{
break;
}
else
{
LineAAVertex t = _list[count - 1];
_list.RemoveLast();
ModifyLast(t);
count--;
}
}
if (closed)
{
//if close figure
count = _list.Count;
var first = innerArray[0];
while (count > 1)
{
if (innerArray[count - 1].IsDiff(first))
{
break;
}
count--;
_list.RemoveLast();
}
}
}
}
//=======================================================rasterizer_outline_aa
public class OutlineAARasterizer
{
LineRenderer _ren;
LineAAVertexSequence _src_vertices = new LineAAVertexSequence();
OutlineJoin _line_join;
int _start_x;
int _start_y;
public enum OutlineJoin
{
NoJoin, //-----outline_no_join
Mitter, //-----outline_miter_join
Round, //-----outline_round_join
AccurateJoin //-----outline_accurate_join
}
public bool CompareDistStart(int d) => d > 0;
public bool CompareDistEnd(int d) => d <= 0;
struct DrawVarsPart0
{
public int idx;
public int lcurr, lnext;
public int flags;
}
struct DrawVarsPart1
{
public int x1, y1, x2, y2;
}
struct DrawVarsPart2
{
public int xb1, yb1, xb2, yb2;
}
#if DEBUG
static int dbuglatest_i = 0;
#endif
public OutlineAARasterizer(LineRenderer ren)
{
_ren = ren;
_line_join = (OutlineRenderer.AccurateJoinOnly ?
OutlineJoin.AccurateJoin :
OutlineJoin.Round);
RoundCap = (false);
_start_x = (0);
_start_y = (0);
}
void Draw(ref DrawVarsPart0 dv,
ref DrawVarsPart1 dv1,
ref DrawVarsPart2 dv2,
ref LineParameters curr,
ref LineParameters next,
int start,
int end)
{
try
{
for (int i = start; i < end; i++)
{
#if DEBUG
dbuglatest_i = i;
if (i == 6)
{
}
#endif
if (_line_join == OutlineJoin.Round)
{
dv2.xb1 = curr.x1 + (curr.y2 - curr.y1);
dv2.yb1 = curr.y1 - (curr.x2 - curr.x1);
dv2.xb2 = curr.x2 + (curr.y2 - curr.y1);
dv2.yb2 = curr.y2 - (curr.x2 - curr.x1);
}
switch (dv.flags)
{
case 0: _ren.Line3(curr, dv2.xb1, dv2.yb1, dv2.xb2, dv2.yb2); break;
case 1: _ren.Line2(curr, dv2.xb2, dv2.yb2); break;
case 2: _ren.Line1(curr, dv2.xb1, dv2.yb1); break;
case 3: _ren.Line0(curr); break;
}
if (_line_join == OutlineJoin.Round && (dv.flags & 2) == 0)
{
_ren.Pie(curr.x2, curr.y2,
curr.x2 + (curr.y2 - curr.y1),
curr.y2 - (curr.x2 - curr.x1),
curr.x2 + (next.y2 - next.y1),
curr.y2 - (next.x2 - next.x1));
}
dv1.x1 = dv1.x2;
dv1.y1 = dv1.y2;
dv.lcurr = dv.lnext;
dv.lnext = _src_vertices[dv.idx].len;
++dv.idx;
if (dv.idx >= _src_vertices.Count) dv.idx = 0;
dv1.x2 = _src_vertices[dv.idx].x;
dv1.y2 = _src_vertices[dv.idx].y;
curr = next;
next = new LineParameters(dv1.x1, dv1.y1, dv1.x2, dv1.y2, dv.lnext);
dv2.xb1 = dv2.xb2;
dv2.yb1 = dv2.yb2;
switch (_line_join)
{
case OutlineJoin.NoJoin:
dv.flags = 3;
break;
case OutlineJoin.Mitter:
dv.flags >>= 1;
dv.flags |= (curr.DiagonalQuadrant ==
next.DiagonalQuadrant ? 1 : 0);
if ((dv.flags & 2) == 0)
{
LineAA.Bisectrix(curr, next, out dv2.xb2, out dv2.yb2);
}
break;
case OutlineJoin.Round:
dv.flags >>= 1;
dv.flags |= (((curr.DiagonalQuadrant ==
next.DiagonalQuadrant) ? 1 : 0) << 1);
break;
case OutlineJoin.AccurateJoin:
dv.flags = 0;
LineAA.Bisectrix(curr, next, out dv2.xb2, out dv2.yb2);
break;
}
}
}
catch (Exception ex)
{
}
}
public void Attach(LineRenderer ren) => _ren = ren;
public OutlineJoin LineJoin
{
get => _line_join;
set
{
_line_join = OutlineRenderer.AccurateJoinOnly ?
OutlineJoin.AccurateJoin : value;
}
}
public bool RoundCap { get; set; }
public void MoveTo(int x, int y)
{
_src_vertices.ModifyLast(new LineAAVertex(_start_x = x, _start_y = y));
}
public void LineTo(int x, int y)
{
_src_vertices.AddVertex(new LineAAVertex(x, y));
}
public void MoveTo(double x, double y)
{
MoveTo(LineCoordSat.Convert(x), LineCoordSat.Convert(y));
}
public void LineTo(double x, double y)
{
LineTo(LineCoordSat.Convert(x), LineCoordSat.Convert(y));
}
public void Render(bool close_polygon)
{
_src_vertices.Close(close_polygon);
DrawVarsPart0 dv = new DrawVarsPart0();
DrawVarsPart1 dv1 = new DrawVarsPart1();
DrawVarsPart2 dv2 = new DrawVarsPart2();
LineAAVertex v;
int x1;
int y1;
int x2;
int y2;
int lprev;
LineParameters curr;
LineParameters next;
if (close_polygon)
{
if (_src_vertices.Count >= 3)
{
dv.idx = 2;
v = _src_vertices[_src_vertices.Count - 1];
x1 = v.x;
y1 = v.y;
lprev = v.len;
v = _src_vertices[0];
x2 = v.x;
y2 = v.y;
dv.lcurr = v.len;
LineParameters prev = new LineParameters(x1, y1, x2, y2, lprev);
v = _src_vertices[1];
dv1.x1 = v.x;
dv1.y1 = v.y;
dv.lnext = v.len;
curr = new LineParameters(x2, y2, dv1.x1, dv1.y1, dv.lcurr);
v = _src_vertices[dv.idx];
dv1.x2 = v.x;
dv1.y2 = v.y;
next = new LineParameters(dv1.x1, dv1.y1, dv1.x2, dv1.y2, dv.lnext);
dv2.xb1 = 0;
dv2.yb1 = 0;
dv2.xb2 = 0;
dv2.yb2 = 0;
switch (_line_join)
{
case OutlineJoin.NoJoin:
dv.flags = 3;
break;
case OutlineJoin.Mitter:
case OutlineJoin.Round:
dv.flags =
(prev.DiagonalQuadrant == curr.DiagonalQuadrant ? 1 : 0) |
((curr.DiagonalQuadrant == next.DiagonalQuadrant ? 1 : 0) << 1);
break;
case OutlineJoin.AccurateJoin:
dv.flags = 0;
break;
}
if (_line_join != OutlineJoin.Round)
{
if ((dv.flags & 1) == 0)
{
LineAA.Bisectrix(prev, curr, out dv2.xb1, out dv2.yb1);
}
if ((dv.flags & 2) == 0)
{
LineAA.Bisectrix(curr, next, out dv2.xb2, out dv2.yb2);
}
}
Draw(ref dv, ref dv1, ref dv2, ref curr, ref next, 0, _src_vertices.Count);
}
}
else
{
switch (_src_vertices.Count)
{
case 0:
case 1:
break;
case 2:
{
v = _src_vertices[0];
x1 = v.x;
y1 = v.y;
lprev = v.len;
v = _src_vertices[1];
x2 = v.x;
y2 = v.y;
LineParameters lp = new LineParameters(x1, y1, x2, y2, lprev);
if (RoundCap)
{
_ren.SemiDot(CompareDistStart, x1, y1, x1 + (y2 - y1), y1 - (x2 - x1));
}
_ren.Line3(lp,
x1 + (y2 - y1),
y1 - (x2 - x1),
x2 + (y2 - y1),
y2 - (x2 - x1));
if (RoundCap)
{
_ren.SemiDot(CompareDistEnd, x2, y2, x2 + (y2 - y1), y2 - (x2 - x1));
}
}
break;
case 3:
{
int x3, y3;
int lnext;
v = _src_vertices[0];
x1 = v.x;
y1 = v.y;
lprev = v.len;
v = _src_vertices[1];
x2 = v.x;
y2 = v.y;
lnext = v.len;
v = _src_vertices[2];
x3 = v.x;
y3 = v.y;
LineParameters lp1 = new LineParameters(x1, y1, x2, y2, lprev);
LineParameters lp2 = new LineParameters(x2, y2, x3, y3, lnext);
if (RoundCap)
{
_ren.SemiDot(CompareDistStart, x1, y1, x1 + (y2 - y1), y1 - (x2 - x1));
}
if (_line_join == OutlineJoin.Round)
{
_ren.Line3(lp1, x1 + (y2 - y1), y1 - (x2 - x1),
x2 + (y2 - y1), y2 - (x2 - x1));
_ren.Pie(x2, y2, x2 + (y2 - y1), y2 - (x2 - x1),
x2 + (y3 - y2), y2 - (x3 - x2));
_ren.Line3(lp2, x2 + (y3 - y2), y2 - (x3 - x2),
x3 + (y3 - y2), y3 - (x3 - x2));
}
else
{
LineAA.Bisectrix(lp1, lp2, out dv2.xb1, out dv2.yb1);
_ren.Line3(lp1, x1 + (y2 - y1), y1 - (x2 - x1),
dv2.xb1, dv2.yb1);
_ren.Line3(lp2, dv2.xb1, dv2.yb1,
x3 + (y3 - y2), y3 - (x3 - x2));
}
if (RoundCap)
{
_ren.SemiDot(CompareDistEnd, x3, y3, x3 + (y3 - y2), y3 - (x3 - x2));
}
}
break;
default:
{
dv.idx = 3;
v = _src_vertices[0];
x1 = v.x;
y1 = v.y;
lprev = v.len;
v = _src_vertices[1];
x2 = v.x;
y2 = v.y;
dv.lcurr = v.len;
var prev = new LineParameters(x1, y1, x2, y2, lprev);
v = _src_vertices[2];
dv1.x1 = v.x;
dv1.y1 = v.y;
dv.lnext = v.len;
curr = new LineParameters(x2, y2, dv1.x1, dv1.y1, dv.lcurr);
v = _src_vertices[dv.idx];
dv1.x2 = v.x;
dv1.y2 = v.y;
next = new LineParameters(dv1.x1, dv1.y1, dv1.x2, dv1.y2, dv.lnext);
dv2.xb1 = 0;
dv2.yb1 = 0;
dv2.xb2 = 0;
dv2.yb2 = 0;
switch (_line_join)
{
case OutlineJoin.NoJoin:
dv.flags = 3;
break;
case OutlineJoin.Mitter:
case OutlineJoin.Round:
dv.flags =
(prev.DiagonalQuadrant == curr.DiagonalQuadrant ? 1 : 0) |
((curr.DiagonalQuadrant == next.DiagonalQuadrant ? 1 : 0) << 1);
break;
case OutlineJoin.AccurateJoin:
dv.flags = 0;
break;
}
if (RoundCap)
{
_ren.SemiDot(CompareDistStart, x1, y1, x1 + (y2 - y1), y1 - (x2 - x1));
}
if ((dv.flags & 1) == 0)
{
if (_line_join == OutlineJoin.Round)
{
_ren.Line3(prev, x1 + (y2 - y1), y1 - (x2 - x1),
x2 + (y2 - y1), y2 - (x2 - x1));
_ren.Pie(prev.x2, prev.y2,
x2 + (y2 - y1), y2 - (x2 - x1),
curr.x1 + (curr.y2 - curr.y1),
curr.y1 - (curr.x2 - curr.x1));
}
else
{
LineAA.Bisectrix(prev, curr, out dv2.xb1, out dv2.yb1);
_ren.Line3(prev, x1 + (y2 - y1), y1 - (x2 - x1),
dv2.xb1, dv2.yb1);
}
}
else
{
_ren.Line1(prev,
x1 + (y2 - y1),
y1 - (x2 - x1));
}
if ((dv.flags & 2) == 0 && _line_join != OutlineJoin.Round)
{
LineAA.Bisectrix(curr, next, out dv2.xb2, out dv2.yb2);
}
Draw(ref dv, ref dv1, ref dv2, ref curr, ref next, 1, _src_vertices.Count - 2);
if ((dv.flags & 1) == 0)
{
if (_line_join == OutlineJoin.Round)
{
_ren.Line3(curr,
curr.x1 + (curr.y2 - curr.y1),
curr.y1 - (curr.x2 - curr.x1),
curr.x2 + (curr.y2 - curr.y1),
curr.y2 - (curr.x2 - curr.x1));
}
else
{
_ren.Line3(curr, dv2.xb1, dv2.yb1,
curr.x2 + (curr.y2 - curr.y1),
curr.y2 - (curr.x2 - curr.x1));
}
}
else
{
_ren.Line2(curr,
curr.x2 + (curr.y2 - curr.y1),
curr.y2 - (curr.x2 - curr.x1));
}
if (RoundCap)
{
_ren.SemiDot(CompareDistEnd, curr.x2, curr.y2,
curr.x2 + (curr.y2 - curr.y1),
curr.y2 - (curr.x2 - curr.x1));
}
}
break;
}
}
_src_vertices.Clear();
}
public void AddVertex(double x, double y, VertexCmd cmd)
{
switch (cmd)
{
case VertexCmd.NoMore:
//do nothing
return;
case VertexCmd.MoveTo:
Render(false);
MoveTo(x, y);
break;
case VertexCmd.Close:
Render(true);
MoveTo(_start_x, _start_y);
break;
default:
LineTo(x, y);
break;
}
}
#if DEBUG
static int dbugAddPathCount = 0;
#endif
void AddPath(VertexStore vxs)
{
VertexCmd cmd;
int index = 0;
while ((cmd = vxs.GetVertex(index++, out double x, out double y)) != VertexCmd.NoMore)
{
AddVertex(x, y, cmd);
}
Render(false);
}
public void RenderVertexSnap(VertexStore s, Drawing.Color c)
{
_ren.Color = c;
AddPath(s);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.StreamAnalytics
{
/// <summary>
/// Operations for managing the transformation definition of the stream
/// analytics job.
/// </summary>
internal partial class TransformationOperations : IServiceOperations<StreamAnalyticsManagementClient>, ITransformationOperations
{
/// <summary>
/// Initializes a new instance of the TransformationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TransformationOperations(StreamAnalyticsManagementClient client)
{
this._client = client;
}
private StreamAnalyticsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.StreamAnalytics.StreamAnalyticsManagementClient.
/// </summary>
public StreamAnalyticsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update a transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a
/// transformation for the stream analytics job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation create operation.
/// </returns>
public async Task<TransformationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Transformation != null)
{
if (parameters.Transformation.Name == null)
{
throw new ArgumentNullException("parameters.Transformation.Name");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
if (parameters.Transformation != null && parameters.Transformation.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Transformation.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject transformationCreateOrUpdateParametersValue = new JObject();
requestDoc = transformationCreateOrUpdateParametersValue;
if (parameters.Transformation != null)
{
transformationCreateOrUpdateParametersValue["name"] = parameters.Transformation.Name;
if (parameters.Transformation.Properties != null)
{
JObject propertiesValue = new JObject();
transformationCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Transformation.Properties.Etag != null)
{
propertiesValue["etag"] = parameters.Transformation.Properties.Etag;
}
if (parameters.Transformation.Properties.StreamingUnits != null)
{
propertiesValue["streamingUnits"] = parameters.Transformation.Properties.StreamingUnits.Value;
}
if (parameters.Transformation.Properties.Query != null)
{
propertiesValue["query"] = parameters.Transformation.Properties.Query;
}
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue2["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue2["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Transformation.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update a transformation for a stream analytics job. The
/// raw json content will be used.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a
/// transformation for the stream analytics job. It is in json format.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation create operation.
/// </returns>
public async Task<TransformationCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string jobName, string transformationName, TransformationCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Content == null)
{
throw new ArgumentNullException("parameters.Content");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
url = url + Uri.EscapeDataString(transformationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Content;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Transformation.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation get operation.
/// </returns>
public async Task<TransformationsGetResponse> GetAsync(string resourceGroupName, string jobName, string transformationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
url = url + Uri.EscapeDataString(transformationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Transformation.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update an transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to update an transformation for
/// the stream analytics job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation patch operation.
/// </returns>
public async Task<TransformationPatchResponse> PatchAsync(string resourceGroupName, string jobName, string transformationName, TransformationPatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
url = url + Uri.EscapeDataString(transformationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject transformationPatchParametersValue = new JObject();
requestDoc = transformationPatchParametersValue;
JObject propertiesValue = new JObject();
transformationPatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Etag != null)
{
propertiesValue["etag"] = parameters.Properties.Etag;
}
if (parameters.Properties.StreamingUnits != null)
{
propertiesValue["streamingUnits"] = parameters.Properties.StreamingUnits.Value;
}
if (parameters.Properties.Query != null)
{
propertiesValue["query"] = parameters.Properties.Query;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationPatchResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationPatchResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
result.Properties = propertiesInstance;
JToken etagValue = propertiesValue2["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue2["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
namespace EIDSS.Reports.Parameterized.Human.GG.Report
{
partial class MicrobiologyResearchCardReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MicrobiologyResearchCardReport));
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.tblSampleHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReceivedMonthCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReceivedDayCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReceivedYearCell = new DevExpress.XtraReports.UI.XRTableCell();
this.Cell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.CollectedMonthCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.CollectedDayCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.CollectedYearCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.OtherCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.PCRCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.MicroscopingCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.VirologyCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.BacteriologyCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.TestMonthCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.TestDayCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.TestYearCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.tblLines = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow24 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow25 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow26 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow27 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.spRepHumMicrobiologyResearchCardTableAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSetTableAdapters.spRepHumMicrobiologyResearchCardTableAdapter();
this.microbiologyResearchCardDataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSet();
this.HeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow28 = new DevExpress.XtraReports.UI.XRTableRow();
this.SiteNameCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow31 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow32 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow33 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.LogoPicture = new DevExpress.XtraReports.UI.XRPictureBox();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tblSampleHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tblLines)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.microbiologyResearchCardDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
resources.ApplyResources(this.cellLanguage, "cellLanguage");
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Multiline = true;
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.LogoPicture,
this.HeaderTable});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
resources.ApplyResources(this.ReportHeader, "ReportHeader");
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
this.cellBaseCountry.StylePriority.UseFont = false;
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1,
this.ReportHeader1,
this.ReportFooter});
this.DetailReport.DataAdapter = this.spRepHumMicrobiologyResearchCardTableAdapter;
this.DetailReport.DataMember = "spRepHumMicrobiologyResearchCard";
this.DetailReport.DataSource = this.microbiologyResearchCardDataSet;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
//
// Detail1
//
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
//
// ReportHeader1
//
this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tblSampleHeader,
this.tblLines});
resources.ApplyResources(this.ReportHeader1, "ReportHeader1");
this.ReportHeader1.Name = "ReportHeader1";
this.ReportHeader1.StylePriority.UseFont = false;
this.ReportHeader1.StylePriority.UseTextAlignment = false;
//
// tblSampleHeader
//
resources.ApplyResources(this.tblSampleHeader, "tblSampleHeader");
this.tblSampleHeader.Name = "tblSampleHeader";
this.tblSampleHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow3,
this.xrTableRow4,
this.xrTableRow5,
this.xrTableRow7,
this.xrTableRow6,
this.xrTableRow8,
this.xrTableRow9,
this.xrTableRow20,
this.xrTableRow13,
this.xrTableRow16,
this.xrTableRow17,
this.xrTableRow18,
this.xrTableRow15});
this.tblSampleHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell15,
this.xrTableCell2});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.StylePriority.UseTextAlignment = false;
this.xrTableRow1.Weight = 0.97059861322766183D;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseTextAlignment = false;
this.xrTableCell1.Weight = 1D;
//
// xrTableCell15
//
this.xrTableCell15.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strSampleId")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.StylePriority.UseBorders = false;
this.xrTableCell15.Weight = 1D;
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell2.StylePriority.UsePadding = false;
this.xrTableCell2.Weight = 1D;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.ReceivedMonthCell,
this.xrTableCell4,
this.ReceivedDayCell,
this.xrTableCell30,
this.ReceivedYearCell,
this.Cell1});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.StylePriority.UseTextAlignment = false;
this.xrTableRow2.Weight = 0.97059861322766183D;
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.Weight = 1D;
//
// ReceivedMonthCell
//
this.ReceivedMonthCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.ReceivedMonthCell, "ReceivedMonthCell");
this.ReceivedMonthCell.Name = "ReceivedMonthCell";
this.ReceivedMonthCell.StylePriority.UseBorders = false;
this.ReceivedMonthCell.StylePriority.UseTextAlignment = false;
this.ReceivedMonthCell.Weight = 0.11764705882352947D;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.Weight = 0.031372549019607926D;
//
// ReceivedDayCell
//
this.ReceivedDayCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.ReceivedDayCell, "ReceivedDayCell");
this.ReceivedDayCell.Name = "ReceivedDayCell";
this.ReceivedDayCell.StylePriority.UseBorders = false;
this.ReceivedDayCell.StylePriority.UseTextAlignment = false;
this.ReceivedDayCell.Weight = 0.11764705882352949D;
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.Weight = 0.031372549019607787D;
//
// ReceivedYearCell
//
this.ReceivedYearCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.ReceivedYearCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.datSampleReceived", "{0:yyyy}")});
resources.ApplyResources(this.ReceivedYearCell, "ReceivedYearCell");
this.ReceivedYearCell.Name = "ReceivedYearCell";
this.ReceivedYearCell.StylePriority.UseBorders = false;
this.ReceivedYearCell.StylePriority.UseTextAlignment = false;
this.ReceivedYearCell.Weight = 0.196078431372549D;
//
// Cell1
//
resources.ApplyResources(this.Cell1, "Cell1");
this.Cell1.Name = "Cell1";
this.Cell1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.Cell1.StylePriority.UsePadding = false;
this.Cell1.Weight = 1.5058823529411765D;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.CollectedMonthCell,
this.xrTableCell70,
this.CollectedDayCell,
this.xrTableCell72,
this.CollectedYearCell,
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22,
this.xrTableCell6});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.StylePriority.UseTextAlignment = false;
this.xrTableRow3.Weight = 0.970598600326849D;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Weight = 1D;
//
// CollectedMonthCell
//
this.CollectedMonthCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.CollectedMonthCell, "CollectedMonthCell");
this.CollectedMonthCell.Name = "CollectedMonthCell";
this.CollectedMonthCell.StylePriority.UseBorders = false;
this.CollectedMonthCell.StylePriority.UseTextAlignment = false;
this.CollectedMonthCell.Weight = 0.11764707378312178D;
//
// xrTableCell70
//
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
this.xrTableCell70.Name = "xrTableCell70";
this.xrTableCell70.Weight = 0.031372552759505956D;
//
// CollectedDayCell
//
this.CollectedDayCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.CollectedDayCell, "CollectedDayCell");
this.CollectedDayCell.Name = "CollectedDayCell";
this.CollectedDayCell.StylePriority.UseBorders = false;
this.CollectedDayCell.StylePriority.UseTextAlignment = false;
this.CollectedDayCell.Weight = 0.11764706069347845D;
//
// xrTableCell72
//
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
this.xrTableCell72.Name = "xrTableCell72";
this.xrTableCell72.Weight = 0.031372549954582357D;
//
// CollectedYearCell
//
this.CollectedYearCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.CollectedYearCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.datSampleCollected", "{0:yyyy}")});
resources.ApplyResources(this.CollectedYearCell, "CollectedYearCell");
this.CollectedYearCell.Name = "CollectedYearCell";
this.CollectedYearCell.StylePriority.UseBorders = false;
this.CollectedYearCell.StylePriority.UseTextAlignment = false;
this.CollectedYearCell.Weight = 0.19607843230752356D;
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.Weight = 0.50588230058258421D;
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell12.StylePriority.UsePadding = false;
this.xrTableCell12.Weight = 0.31372200499993769D;
//
// xrTableCell20
//
this.xrTableCell20.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseBorders = false;
this.xrTableCell20.Weight = 0.11764705862854005D;
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Weight = 0.03137254144231455D;
//
// xrTableCell22
//
this.xrTableCell22.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseBorders = false;
this.xrTableCell22.Weight = 0.11764705503488276D;
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.Weight = 0.41961136981352859D;
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell8});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.KeepTogether = false;
this.xrTableRow4.Name = "xrTableRow4";
this.xrTableRow4.Weight = 0.97059857767673963D;
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.Weight = 1D;
//
// xrTableCell16
//
this.xrTableCell16.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strNameSurname")});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseBorders = false;
this.xrTableCell16.Weight = 1D;
//
// xrTableCell17
//
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell17.StylePriority.UsePadding = false;
this.xrTableCell17.Weight = 0.31372151133307524D;
//
// xrTableCell8
//
this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strAge")});
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
this.xrTableCell8.Weight = 0.68627848866692476D;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell18});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
this.xrTableRow5.Weight = 0.97059861730851194D;
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.Weight = 1D;
//
// xrTableCell18
//
this.xrTableCell18.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strResearchedSample")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseBorders = false;
this.xrTableCell18.Weight = 2D;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell25,
this.xrTableCell31});
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
this.xrTableRow7.Name = "xrTableRow7";
this.xrTableRow7.Weight = 0.9705985628593965D;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.Weight = 1D;
//
// xrTableCell31
//
this.xrTableCell31.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard .strRequestedResearch")});
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseBorders = false;
this.xrTableCell31.Weight = 2D;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell13,
this.xrTableCell19});
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
this.xrTableRow6.Name = "xrTableRow6";
this.xrTableRow6.Weight = 0.9705986178566437D;
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.Weight = 1D;
//
// xrTableCell19
//
this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strSampleReceivedFrom")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
this.xrTableCell19.Weight = 2D;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell27});
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
this.xrTableRow8.Name = "xrTableRow8";
this.xrTableRow8.Weight = 0.57094034860697762D;
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.Weight = 3D;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23,
this.xrTableCell24});
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Name = "xrTableRow9";
this.xrTableRow9.Weight = 3.9109414808412044D;
//
// xrTableCell23
//
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseTextAlignment = false;
this.xrTableCell23.Weight = 1D;
//
// xrTableCell24
//
this.xrTableCell24.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1,
this.OtherCheckBox,
this.PCRCheckBox,
this.MicroscopingCheckBox,
this.VirologyCheckBox,
this.BacteriologyCheckBox});
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBorders = false;
this.xrTableCell24.Weight = 2D;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
//
// OtherCheckBox
//
resources.ApplyResources(this.OtherCheckBox, "OtherCheckBox");
this.OtherCheckBox.Name = "OtherCheckBox";
//
// PCRCheckBox
//
resources.ApplyResources(this.PCRCheckBox, "PCRCheckBox");
this.PCRCheckBox.Name = "PCRCheckBox";
//
// MicroscopingCheckBox
//
resources.ApplyResources(this.MicroscopingCheckBox, "MicroscopingCheckBox");
this.MicroscopingCheckBox.Name = "MicroscopingCheckBox";
//
// VirologyCheckBox
//
resources.ApplyResources(this.VirologyCheckBox, "VirologyCheckBox");
this.VirologyCheckBox.Name = "VirologyCheckBox";
//
// BacteriologyCheckBox
//
resources.ApplyResources(this.BacteriologyCheckBox, "BacteriologyCheckBox");
this.BacteriologyCheckBox.Name = "BacteriologyCheckBox";
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.xrTableCell29});
resources.ApplyResources(this.xrTableRow20, "xrTableRow20");
this.xrTableRow20.Name = "xrTableRow20";
this.xrTableRow20.Weight = 2.7690607572846524D;
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
this.xrTableCell26.StylePriority.UseTextAlignment = false;
this.xrTableCell26.Weight = 1D;
//
// xrTableCell29
//
this.xrTableCell29.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strResearchResult")});
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Multiline = true;
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseBorders = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
this.xrTableCell29.Weight = 2D;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell40,
this.xrTableCell48,
this.xrTableCell41});
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
this.xrTableRow13.Name = "xrTableRow13";
this.xrTableRow13.Weight = 1.1418806732046D;
//
// xrTableCell40
//
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.Weight = 0.77461757285922173D;
//
// xrTableCell48
//
this.xrTableCell48.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strResearchConductedBy")});
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseBorders = false;
this.xrTableCell48.Weight = 1.8057712629729628D;
//
// xrTableCell41
//
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.Weight = 0.41961116416781574D;
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell52,
this.xrTableCell53,
this.xrTableCell54});
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
this.xrTableRow16.Name = "xrTableRow16";
this.xrTableRow16.Weight = 0.45675225839201705D;
//
// xrTableCell52
//
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.Weight = 0.77461757285922173D;
//
// xrTableCell53
//
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
this.xrTableCell53.StylePriority.UseTextAlignment = false;
this.xrTableCell53.Weight = 1.8057712629729628D;
//
// xrTableCell54
//
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.Weight = 0.41961116416781574D;
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57});
resources.ApplyResources(this.xrTableRow17, "xrTableRow17");
this.xrTableRow17.Name = "xrTableRow17";
this.xrTableRow17.Weight = 1.1418807276537155D;
//
// xrTableCell55
//
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.Weight = 0.77625163957184429D;
//
// xrTableCell56
//
this.xrTableCell56.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell56.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.strDepartmentHead")});
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseBorders = false;
this.xrTableCell56.Weight = 1.8041371962603403D;
//
// xrTableCell57
//
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.Weight = 0.41961116416781569D;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell58,
this.xrTableCell59,
this.xrTableCell60});
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
this.xrTableRow18.Name = "xrTableRow18";
this.xrTableRow18.Weight = 0.45675231284113238D;
//
// xrTableCell58
//
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.Weight = 0.77625151989506724D;
//
// xrTableCell59
//
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseFont = false;
this.xrTableCell59.StylePriority.UseTextAlignment = false;
this.xrTableCell59.Weight = 1.8041371962603403D;
//
// xrTableCell60
//
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.Weight = 0.41961128384459273D;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell49,
this.TestMonthCell,
this.xrTableCell32,
this.TestDayCell,
this.xrTableCell37,
this.TestYearCell,
this.xrTableCell50,
this.xrTableCell51});
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
this.xrTableRow15.Name = "xrTableRow15";
this.xrTableRow15.Weight = 0.9705985666718695D;
//
// xrTableCell49
//
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseTextAlignment = false;
this.xrTableCell49.Weight = 0.7762517293294271D;
//
// TestMonthCell
//
this.TestMonthCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.TestMonthCell, "TestMonthCell");
this.TestMonthCell.Name = "TestMonthCell";
this.TestMonthCell.StylePriority.UseBorders = false;
this.TestMonthCell.StylePriority.UseTextAlignment = false;
this.TestMonthCell.Weight = 0.11764705882352944D;
//
// xrTableCell32
//
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.Weight = 0.031372549019607912D;
//
// TestDayCell
//
this.TestDayCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.TestDayCell, "TestDayCell");
this.TestDayCell.Name = "TestDayCell";
this.TestDayCell.StylePriority.UseBorders = false;
this.TestDayCell.StylePriority.UseTextAlignment = false;
this.TestDayCell.Weight = 0.11764706630332783D;
//
// xrTableCell37
//
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.Weight = 0.031372552759507261D;
//
// TestYearCell
//
this.TestYearCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.TestYearCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMicrobiologyResearchCard.datDateTested", "{0:yyyy}")});
resources.ApplyResources(this.TestYearCell, "TestYearCell");
this.TestYearCell.Name = "TestYearCell";
this.TestYearCell.StylePriority.UseBorders = false;
this.TestYearCell.StylePriority.UseTextAlignment = false;
this.TestYearCell.Weight = 0.1960784201528511D;
//
// xrTableCell50
//
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.Weight = 1.3100194594439341D;
//
// xrTableCell51
//
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
this.xrTableCell51.Name = "xrTableCell51";
this.xrTableCell51.Weight = 0.41961116416781569D;
//
// tblLines
//
this.tblLines.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.tblLines, "tblLines");
this.tblLines.Name = "tblLines";
this.tblLines.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow19,
this.xrTableRow23,
this.xrTableRow24,
this.xrTableRow25,
this.xrTableRow26,
this.xrTableRow27});
this.tblLines.StylePriority.UseBorders = false;
this.tblLines.StylePriority.UseTextAlignment = false;
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell33});
resources.ApplyResources(this.xrTableRow19, "xrTableRow19");
this.xrTableRow19.Name = "xrTableRow19";
this.xrTableRow19.Weight = 0.41796913146972647D;
//
// xrTableCell33
//
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseBorders = false;
this.xrTableCell33.Weight = 2.9999999999999996D;
//
// xrTableRow23
//
this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell34});
resources.ApplyResources(this.xrTableRow23, "xrTableRow23");
this.xrTableRow23.Name = "xrTableRow23";
this.xrTableRow23.Weight = 0.41796913146972647D;
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseBorders = false;
this.xrTableCell34.Weight = 2.9999999999999996D;
//
// xrTableRow24
//
this.xrTableRow24.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell61});
resources.ApplyResources(this.xrTableRow24, "xrTableRow24");
this.xrTableRow24.Name = "xrTableRow24";
this.xrTableRow24.Weight = 0.41796913146972647D;
//
// xrTableCell61
//
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseBorders = false;
this.xrTableCell61.Weight = 2.9999999999999996D;
//
// xrTableRow25
//
this.xrTableRow25.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell64});
resources.ApplyResources(this.xrTableRow25, "xrTableRow25");
this.xrTableRow25.Name = "xrTableRow25";
this.xrTableRow25.Weight = 0.41796913146972647D;
//
// xrTableCell64
//
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseBorders = false;
this.xrTableCell64.Weight = 2.9999999999999996D;
//
// xrTableRow26
//
this.xrTableRow26.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell66});
resources.ApplyResources(this.xrTableRow26, "xrTableRow26");
this.xrTableRow26.Name = "xrTableRow26";
this.xrTableRow26.Weight = 0.41796913146972647D;
//
// xrTableCell66
//
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
this.xrTableCell66.Name = "xrTableCell66";
this.xrTableCell66.Weight = 2.9999999999999996D;
//
// xrTableRow27
//
this.xrTableRow27.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell68});
resources.ApplyResources(this.xrTableRow27, "xrTableRow27");
this.xrTableRow27.Name = "xrTableRow27";
this.xrTableRow27.Weight = 0.41796913146972647D;
//
// xrTableCell68
//
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
this.xrTableCell68.Name = "xrTableCell68";
this.xrTableCell68.Weight = 2.9999999999999996D;
//
// ReportFooter
//
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.StylePriority.UseTextAlignment = false;
//
// spRepHumMicrobiologyResearchCardTableAdapter
//
this.spRepHumMicrobiologyResearchCardTableAdapter.ClearBeforeFill = true;
//
// microbiologyResearchCardDataSet
//
this.microbiologyResearchCardDataSet.DataSetName = "MicrobiologyResearchCardDataSet";
this.microbiologyResearchCardDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// HeaderTable
//
resources.ApplyResources(this.HeaderTable, "HeaderTable");
this.HeaderTable.Name = "HeaderTable";
this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow28,
this.xrTableRow31,
this.xrTableRow32,
this.xrTableRow33});
this.HeaderTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow28
//
this.xrTableRow28.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.SiteNameCell});
resources.ApplyResources(this.xrTableRow28, "xrTableRow28");
this.xrTableRow28.Name = "xrTableRow28";
this.xrTableRow28.StylePriority.UseTextAlignment = false;
this.xrTableRow28.Weight = 0.42352939655871596D;
//
// SiteNameCell
//
this.SiteNameCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.microbiologyResearchCardDataSet, "spRepHumMicrobiologyResearchCard .strSiteName")});
resources.ApplyResources(this.SiteNameCell, "SiteNameCell");
this.SiteNameCell.Name = "SiteNameCell";
this.SiteNameCell.StylePriority.UseFont = false;
this.SiteNameCell.Weight = 3D;
//
// xrTableRow31
//
this.xrTableRow31.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell10});
resources.ApplyResources(this.xrTableRow31, "xrTableRow31");
this.xrTableRow31.Name = "xrTableRow31";
this.xrTableRow31.Weight = 0.42352939655871591D;
//
// xrTableCell10
//
this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.microbiologyResearchCardDataSet, "spRepHumMicrobiologyResearchCard .strSiteAddress")});
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseTextAlignment = false;
this.xrTableCell10.Weight = 3D;
//
// xrTableRow32
//
this.xrTableRow32.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14});
resources.ApplyResources(this.xrTableRow32, "xrTableRow32");
this.xrTableRow32.Name = "xrTableRow32";
this.xrTableRow32.Weight = 0.42352939655871585D;
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.Weight = 3D;
//
// xrTableRow33
//
this.xrTableRow33.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell69});
resources.ApplyResources(this.xrTableRow33, "xrTableRow33");
this.xrTableRow33.Name = "xrTableRow33";
this.xrTableRow33.Weight = 0.56470586207828788D;
//
// xrTableCell69
//
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
this.xrTableCell69.Name = "xrTableCell69";
this.xrTableCell69.StylePriority.UseFont = false;
this.xrTableCell69.Weight = 3D;
//
// LogoPicture
//
resources.ApplyResources(this.LogoPicture, "LogoPicture");
this.LogoPicture.Image = ((System.Drawing.Image)(resources.GetObject("LogoPicture.Image")));
this.LogoPicture.Name = "LogoPicture";
//
// MicrobiologyResearchCardReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReport});
this.CanWorkWithArchive = true;
resources.ApplyResources(this, "$this");
this.Version = "11.1";
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tblSampleHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tblLines)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.microbiologyResearchCardDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTable tblSampleHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell Cell1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSet microbiologyResearchCardDataSet;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSetTableAdapters.spRepHumMicrobiologyResearchCardTableAdapter spRepHumMicrobiologyResearchCardTableAdapter;
private DevExpress.XtraReports.UI.XRTable tblLines;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRPictureBox LogoPicture;
private DevExpress.XtraReports.UI.XRTable HeaderTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow28;
private DevExpress.XtraReports.UI.XRTableCell SiteNameCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.XRTableCell ReceivedMonthCell;
private DevExpress.XtraReports.UI.XRTableCell ReceivedDayCell;
private DevExpress.XtraReports.UI.XRTableCell ReceivedYearCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell CollectedMonthCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableCell CollectedDayCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell CollectedYearCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRCheckBox OtherCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox PCRCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox MicroscopingCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox VirologyCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox BacteriologyCheckBox;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTableCell TestMonthCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell TestDayCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell TestYearCell;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Osp;
using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver;
using OpenSim.Region.CoreModules.World.Serialiser;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using OpenSim.Tests.Common.Setup;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
{
[TestFixture]
public class InventoryArchiverTests
{
protected ManualResetEvent mre = new ManualResetEvent(false);
private void InventoryReceived(UUID userId)
{
lock (this)
{
Monitor.PulseAll(this);
}
}
private void SaveCompleted(
Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream,
Exception reportedException)
{
mre.Set();
}
/// <summary>
/// Test saving a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet).
/// </summary>
// Commenting for now! The mock inventory service needs more beef, at least for
// GetFolderForType
[Test]
public void TestSaveIarV0_1()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
CommunicationsManager cm = scene.CommsManager;
// Create user
string userFirstName = "Jock";
string userLastName = "Stirrup";
UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
lock (this)
{
UserProfileTestUtils.CreateUserWithInventory(
cm, userFirstName, userLastName, userId, InventoryReceived);
Monitor.Wait(this, 60000);
}
// Create asset
SceneObjectGroup object1;
SceneObjectPart part1;
{
string partName = "My Little Dog Object";
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
Vector3 groupPosition = new Vector3(10, 20, 30);
Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
Vector3 offsetPosition = new Vector3(5, 10, 15);
part1
= new SceneObjectPart(
ownerId, shape, groupPosition, rotationOffset, offsetPosition);
part1.Name = partName;
object1 = new SceneObjectGroup(part1);
scene.AddNewSceneObject(object1, false);
}
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = new AssetBase();
asset1.FullID = asset1Id;
asset1.Data = Encoding.ASCII.GetBytes(SceneObjectSerializer.ToXml2Format(object1));
scene.AssetService.Store(asset1);
// Create item
UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = "My Little Dog";
item1.AssetID = asset1.FullID;
item1.ID = item1Id;
InventoryFolderBase objsFolder
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects");
item1.Folder = objsFolder.ID;
scene.AddInventoryItem(userId, item1);
MemoryStream archiveWriteStream = new MemoryStream();
archiverModule.OnInventoryArchiveSaved += SaveCompleted;
mre.Reset();
archiverModule.ArchiveInventory(
Guid.NewGuid(), userFirstName, userLastName, "Objects", "troll", archiveWriteStream);
mre.WaitOne(60000, false);
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
//bool gotControlFile = false;
bool gotObject1File = false;
//bool gotObject2File = false;
string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1);
string expectedObject1FilePath = string.Format(
"{0}{1}{2}",
ArchiveConstants.INVENTORY_PATH,
InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder),
expectedObject1FileName);
string filePath;
TarArchiveReader.TarEntryType tarEntryType;
Console.WriteLine("Reading archive");
while (tar.ReadEntry(out filePath, out tarEntryType) != null)
{
Console.WriteLine("Got {0}", filePath);
// if (ArchiveConstants.CONTROL_FILE_PATH == filePath)
// {
// gotControlFile = true;
// }
if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml"))
{
// string fileName = filePath.Remove(0, "Objects/".Length);
//
// if (fileName.StartsWith(part1.Name))
// {
Assert.That(expectedObject1FilePath, Is.EqualTo(filePath));
gotObject1File = true;
// }
// else if (fileName.StartsWith(part2.Name))
// {
// Assert.That(fileName, Is.EqualTo(expectedObject2FileName));
// gotObject2File = true;
// }
}
}
// Assert.That(gotControlFile, Is.True, "No control file in archive");
Assert.That(gotObject1File, Is.True, "No item1 file in archive");
// Assert.That(gotObject2File, Is.True, "No object2 file in archive");
// TODO: Test presence of more files and contents of files.
}
/// <summary>
/// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
/// an account exists with the creator name.
/// </summary>
///
/// This test also does some deeper probing of loading into nested inventory structures
[Test]
public void TestLoadIarV0_1ExistingUsers()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
string userFirstName = "Mr";
string userLastName = "Tiddles";
UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555");
string userItemCreatorFirstName = "Lord";
string userItemCreatorLastName = "Lucan";
UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
string itemName = "b.lsl";
string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = itemName;
item1.AssetID = UUID.Random();
item1.GroupID = UUID.Random();
item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
//item1.CreatorId = userUuid.ToString();
//item1.CreatorId = "00000000-0000-0000-0000-000000000444";
item1.Owner = UUID.Zero;
string item1FileName
= string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
tar.Close();
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
SerialiserModule serialiserModule = new SerialiserModule();
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
Scene scene = SceneSetupHelpers.SetupScene("inventory");
IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
userAdminService.AddUser(
userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
userAdminService.AddUser(
userItemCreatorFirstName, userItemCreatorLastName, "hampshire",
String.Empty, 1000, 1000, userItemCreatorUuid);
archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream);
CachedUserInfo userInfo
= scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
InventoryItemBase foundItem1
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName);
Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
Assert.That(
foundItem1.CreatorId, Is.EqualTo(item1.CreatorId),
"Loaded item non-uuid creator doesn't match original");
Assert.That(
foundItem1.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid),
"Loaded item uuid creator doesn't match original");
Assert.That(foundItem1.Owner, Is.EqualTo(userUuid),
"Loaded item owner doesn't match inventory reciever");
// Now try loading to a root child folder
UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xA");
archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream);
InventoryItemBase foundItem2
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + itemName);
Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2");
// Now try loading to a more deeply nested folder
UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC");
archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream);
InventoryItemBase foundItem3
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + itemName);
Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3");
}
/// <summary>
/// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
/// embedded creators do not exist in the system
/// </summary>
///
/// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature
/// (as tested in the a later commented out test)
[Test]
public void TestLoadIarV0_1AbsentUsers()
{
TestHelper.InMethod();
log4net.Config.XmlConfigurator.Configure();
string userFirstName = "Charlie";
string userLastName = "Chan";
UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999");
string userItemCreatorFirstName = "Bat";
string userItemCreatorLastName = "Man";
//UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888");
string itemName = "b.lsl";
string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = itemName;
item1.AssetID = UUID.Random();
item1.GroupID = UUID.Random();
item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
//item1.CreatorId = userUuid.ToString();
//item1.CreatorId = "00000000-0000-0000-0000-000000000444";
item1.Owner = UUID.Zero;
string item1FileName
= string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
tar.Close();
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
SerialiserModule serialiserModule = new SerialiserModule();
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
Scene scene = SceneSetupHelpers.SetupScene("inventory");
IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
userAdminService.AddUser(
userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream);
CachedUserInfo userInfo
= scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
InventoryItemBase foundItem1
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName);
Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
// Assert.That(
// foundItem1.CreatorId, Is.EqualTo(userUuid),
// "Loaded item non-uuid creator doesn't match that of the loading user");
Assert.That(
foundItem1.CreatorIdAsUuid, Is.EqualTo(userUuid),
"Loaded item uuid creator doesn't match that of the loading user");
}
/// <summary>
/// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
/// no account exists with the creator name
/// </summary>
/// Disabled since temporary profiles have not yet been implemented.
//[Test]
public void TestLoadIarV0_1TempProfiles()
{
TestHelper.InMethod();
log4net.Config.XmlConfigurator.Configure();
string userFirstName = "Dennis";
string userLastName = "Menace";
UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000aaa");
string user2FirstName = "Walter";
string user2LastName = "Mitty";
string itemName = "b.lsl";
string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = itemName;
item1.AssetID = UUID.Random();
item1.GroupID = UUID.Random();
item1.CreatorId = OspResolver.MakeOspa(user2FirstName, user2LastName);
item1.Owner = UUID.Zero;
string item1FileName
= string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
tar.Close();
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
SerialiserModule serialiserModule = new SerialiserModule();
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
Scene scene = SceneSetupHelpers.SetupScene();
IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
userAdminService.AddUser(
userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "troll", archiveReadStream);
// Check that a suitable temporary user profile has been created.
UserProfileData user2Profile
= scene.CommsManager.UserService.GetUserProfile(
OspResolver.HashName(user2FirstName + " " + user2LastName));
Assert.That(user2Profile, Is.Not.Null);
Assert.That(user2Profile.FirstName == user2FirstName);
Assert.That(user2Profile.SurName == user2LastName);
CachedUserInfo userInfo
= scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
userInfo.OnInventoryReceived += InventoryReceived;
lock (this)
{
userInfo.FetchInventory();
Monitor.Wait(this, 60000);
}
InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName);
Assert.That(foundItem.CreatorId, Is.EqualTo(item1.CreatorId));
Assert.That(
foundItem.CreatorIdAsUuid, Is.EqualTo(OspResolver.HashName(user2FirstName + " " + user2LastName)));
Assert.That(foundItem.Owner, Is.EqualTo(userUuid));
Console.WriteLine("### Successfully completed {0} ###", MethodBase.GetCurrentMethod());
}
/// <summary>
/// Test replication of an archive path to the user's inventory.
/// </summary>
[Test]
public void TestReplicateArchivePathToUserInventory()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
Scene scene = SceneSetupHelpers.SetupScene("inventory");
CommunicationsManager commsManager = scene.CommsManager;
CachedUserInfo userInfo;
lock (this)
{
userInfo = UserProfileTestUtils.CreateUserWithInventory(commsManager, InventoryReceived);
Monitor.Wait(this, 60000);
}
//Console.WriteLine("userInfo.RootFolder 1: {0}", userInfo.RootFolder);
Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>();
List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
string folder1Name = "a";
string folder2Name = "b";
string itemName = "c.lsl";
string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random());
string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random());
string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
string itemArchivePath
= string.Format(
"{0}{1}{2}{3}",
ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName);
//Console.WriteLine("userInfo.RootFolder 2: {0}", userInfo.RootFolder);
new InventoryArchiveReadRequest(scene, userInfo, null, (Stream)null)
.ReplicateArchivePathToUserInventory(
itemArchivePath, false, scene.InventoryService.GetRootFolder(userInfo.UserProfile.ID),
foldersCreated, nodesLoaded);
//Console.WriteLine("userInfo.RootFolder 3: {0}", userInfo.RootFolder);
//InventoryFolderImpl folder1 = userInfo.RootFolder.FindFolderByPath("a");
InventoryFolderBase folder1
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userInfo.UserProfile.ID, "a");
Assert.That(folder1, Is.Not.Null, "Could not find folder a");
InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b");
Assert.That(folder2, Is.Not.Null, "Could not find folder b");
}
}
}
| |
// ==========================================================================
// This software is subject to the provisions of the Zope Public License,
// Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
// WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
// FOR A PARTICULAR PURPOSE.
// ==========================================================================
using System;
using System.Runtime.InteropServices;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Threading;
namespace Python.Runtime {
//=======================================================================
// The TypeManager class is responsible for building binary-compatible
// Python type objects that are implemented in managed code.
//=======================================================================
internal class TypeManager {
static BindingFlags tbFlags;
static Dictionary<Type, IntPtr> cache;
static int obSize;
static TypeManager() {
tbFlags = BindingFlags.Public | BindingFlags.Static;
obSize = 5 * IntPtr.Size;
cache = new Dictionary<Type, IntPtr>(128);
}
//====================================================================
// Given a managed Type derived from ExtensionType, get the handle to
// a Python type object that delegates its implementation to the Type
// object. These Python type instances are used to implement internal
// descriptor and utility types like ModuleObject, PropertyObject, etc.
//====================================================================
internal static IntPtr GetTypeHandle(Type type) {
// Note that these types are cached with a refcount of 1, so they
// effectively exist until the CPython runtime is finalized.
IntPtr handle = IntPtr.Zero;
cache.TryGetValue(type, out handle);
if (handle != IntPtr.Zero) {
return handle;
}
handle = CreateType(type);
cache[type] = handle;
return handle;
}
//====================================================================
// Get the handle of a Python type that reflects the given CLR type.
// The given ManagedType instance is a managed object that implements
// the appropriate semantics in Python for the reflected managed type.
//====================================================================
internal static IntPtr GetTypeHandle(ManagedType obj, Type type) {
IntPtr handle = IntPtr.Zero;
cache.TryGetValue(type, out handle);
if (handle != IntPtr.Zero) {
return handle;
}
handle = CreateType(obj, type);
cache[type] = handle;
return handle;
}
//====================================================================
// The following CreateType implementations do the necessary work to
// create Python types to represent managed extension types, reflected
// types, subclasses of reflected types and the managed metatype. The
// dance is slightly different for each kind of type due to different
// behavior needed and the desire to have the existing Python runtime
// do as much of the allocation and initialization work as possible.
//====================================================================
internal static IntPtr CreateType(Type impl) {
IntPtr type = AllocateTypeObject(impl.Name);
// Set tp_basicsize to the size of our managed instance objects.
Marshal.WriteIntPtr(type, TypeOffset.tp_basicsize, (IntPtr)obSize);
IntPtr offset = (IntPtr)ObjectOffset.ob_dict;
Marshal.WriteIntPtr(type, TypeOffset.tp_dictoffset, offset);
InitializeSlots(type, impl);
int flags = TypeFlags.Default | TypeFlags.Managed |
TypeFlags.HeapType | TypeFlags.HaveGC;
Marshal.WriteIntPtr(type, TypeOffset.tp_flags, (IntPtr)flags);
Runtime.PyType_Ready(type);
IntPtr dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict);
IntPtr mod = Runtime.PyString_FromString("CLR");
Runtime.PyDict_SetItemString(dict, "__module__", mod);
InitMethods(type, impl);
return type;
}
internal static IntPtr CreateType(ManagedType impl, Type clrType) {
// Cleanup the type name to get rid of funny nested type names.
string name = "CLR." + clrType.FullName;
int i = name.LastIndexOf('+');
if (i > -1) {
name = name.Substring(i + 1);
}
i = name.LastIndexOf('.');
if (i > -1) {
name = name.Substring(i + 1);
}
IntPtr base_ = IntPtr.Zero;
// XXX Hack, use a different base class for System.Exception
// Python 2.5+ allows new style class exceptions but they *must*
// subclass BaseException (or better Exception).
#if (PYTHON25 || PYTHON26 || PYTHON27)
if (clrType == typeof(System.Exception)) {
base_ = Exceptions.Exception;
Runtime.Incref(base_);
} else
#endif
if (clrType.BaseType != null) {
ClassBase bc = ClassManager.GetClass(clrType.BaseType);
base_ = bc.pyHandle;
}
IntPtr type = AllocateTypeObject(name);
Marshal.WriteIntPtr(type,TypeOffset.ob_type,Runtime.PyCLRMetaType);
Runtime.Incref(Runtime.PyCLRMetaType);
Marshal.WriteIntPtr(type, TypeOffset.tp_basicsize, (IntPtr)obSize);
Marshal.WriteIntPtr(type, TypeOffset.tp_itemsize, IntPtr.Zero);
IntPtr offset = (IntPtr)ObjectOffset.ob_dict;
Marshal.WriteIntPtr(type, TypeOffset.tp_dictoffset, offset);
InitializeSlots(type, impl.GetType());
if (base_ != IntPtr.Zero) {
Marshal.WriteIntPtr(type, TypeOffset.tp_base, base_);
Runtime.Incref(base_);
}
int flags = TypeFlags.Default;
flags |= TypeFlags.Managed;
flags |= TypeFlags.HeapType;
flags |= TypeFlags.BaseType;
flags |= TypeFlags.HaveGC;
Marshal.WriteIntPtr(type, TypeOffset.tp_flags, (IntPtr)flags);
// Leverage followup initialization from the Python runtime. Note
// that the type of the new type must PyType_Type at the time we
// call this, else PyType_Ready will skip some slot initialization.
Runtime.PyType_Ready(type);
IntPtr dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict);
string mn = clrType.Namespace != null ? clrType.Namespace : "";
IntPtr mod = Runtime.PyString_FromString(mn);
Runtime.PyDict_SetItemString(dict, "__module__", mod);
// Hide the gchandle of the implementation in a magic type slot.
GCHandle gc = GCHandle.Alloc(impl);
Marshal.WriteIntPtr(type, TypeOffset.magic(), (IntPtr)gc);
// Set the handle attributes on the implementing instance.
impl.tpHandle = Runtime.PyCLRMetaType;
impl.gcHandle = gc;
impl.pyHandle = type;
//DebugUtil.DumpType(type);
return type;
}
internal static IntPtr CreateSubType(IntPtr args) {
IntPtr py_name = Runtime.PyTuple_GetItem(args, 0);
IntPtr bases = Runtime.PyTuple_GetItem(args, 1);
IntPtr dict = Runtime.PyTuple_GetItem(args, 2);
IntPtr base_ = Runtime.PyTuple_GetItem(bases, 0);
string name = Runtime.GetManagedString(py_name);
IntPtr type = AllocateTypeObject(name);
Marshal.WriteIntPtr(type,TypeOffset.ob_type,Runtime.PyCLRMetaType);
Runtime.Incref(Runtime.PyCLRMetaType);
Marshal.WriteIntPtr(type, TypeOffset.tp_basicsize, (IntPtr)obSize);
Marshal.WriteIntPtr(type, TypeOffset.tp_itemsize, IntPtr.Zero);
IntPtr offset = (IntPtr)ObjectOffset.ob_dict;
Marshal.WriteIntPtr(type, TypeOffset.tp_dictoffset, offset);
IntPtr dc = Runtime.PyDict_Copy(dict);
Marshal.WriteIntPtr(type, TypeOffset.tp_dict, dc);
Marshal.WriteIntPtr(type, TypeOffset.tp_base, base_);
Runtime.Incref(base_);
int flags = TypeFlags.Default;
flags |= TypeFlags.Managed;
flags |= TypeFlags.HeapType;
flags |= TypeFlags.BaseType;
flags |= TypeFlags.Subclass;
flags |= TypeFlags.HaveGC;
Marshal.WriteIntPtr(type, TypeOffset.tp_flags, (IntPtr)flags);
CopySlot(base_, type, TypeOffset.tp_traverse);
CopySlot(base_, type, TypeOffset.tp_clear);
CopySlot(base_, type, TypeOffset.tp_is_gc);
Runtime.PyType_Ready(type);
IntPtr tp_dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict);
IntPtr mod = Runtime.PyString_FromString("CLR");
Runtime.PyDict_SetItemString(tp_dict, "__module__", mod);
// for now, move up hidden handle...
IntPtr gc = Marshal.ReadIntPtr(base_, TypeOffset.magic());
Marshal.WriteIntPtr(type, TypeOffset.magic(), gc);
return type;
}
internal static IntPtr CreateMetaType(Type impl) {
// The managed metatype is functionally little different than the
// standard Python metatype (PyType_Type). It overrides certain of
// the standard type slots, and has to subclass PyType_Type for
// certain functions in the C runtime to work correctly with it.
IntPtr type = AllocateTypeObject("CLR Metatype");
IntPtr py_type = Runtime.PyTypeType;
Marshal.WriteIntPtr(type, TypeOffset.tp_base, py_type);
Runtime.Incref(py_type);
// Copy gc and other type slots from the base Python metatype.
CopySlot(py_type, type, TypeOffset.tp_basicsize);
CopySlot(py_type, type, TypeOffset.tp_itemsize);
CopySlot(py_type, type, TypeOffset.tp_dictoffset);
CopySlot(py_type, type, TypeOffset.tp_weaklistoffset);
CopySlot(py_type, type, TypeOffset.tp_traverse);
CopySlot(py_type, type, TypeOffset.tp_clear);
CopySlot(py_type, type, TypeOffset.tp_is_gc);
// Override type slots with those of the managed implementation.
InitializeSlots(type, impl);
int flags = TypeFlags.Default;
flags |= TypeFlags.Managed;
flags |= TypeFlags.HeapType;
flags |= TypeFlags.HaveGC;
Marshal.WriteIntPtr(type, TypeOffset.tp_flags, (IntPtr)flags);
Runtime.PyType_Ready(type);
IntPtr dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict);
IntPtr mod = Runtime.PyString_FromString("CLR");
Runtime.PyDict_SetItemString(dict, "__module__", mod);
//DebugUtil.DumpType(type);
return type;
}
internal static IntPtr BasicSubType(string name, IntPtr base_,
Type impl) {
// Utility to create a subtype of a std Python type, but with
// a managed type able to override implementation
IntPtr type = AllocateTypeObject(name);
//Marshal.WriteIntPtr(type, TypeOffset.tp_basicsize, (IntPtr)obSize);
//Marshal.WriteIntPtr(type, TypeOffset.tp_itemsize, IntPtr.Zero);
//IntPtr offset = (IntPtr)ObjectOffset.ob_dict;
//Marshal.WriteIntPtr(type, TypeOffset.tp_dictoffset, offset);
//IntPtr dc = Runtime.PyDict_Copy(dict);
//Marshal.WriteIntPtr(type, TypeOffset.tp_dict, dc);
Marshal.WriteIntPtr(type, TypeOffset.tp_base, base_);
Runtime.Incref(base_);
int flags = TypeFlags.Default;
flags |= TypeFlags.Managed;
flags |= TypeFlags.HeapType;
flags |= TypeFlags.HaveGC;
Marshal.WriteIntPtr(type, TypeOffset.tp_flags, (IntPtr)flags);
CopySlot(base_, type, TypeOffset.tp_traverse);
CopySlot(base_, type, TypeOffset.tp_clear);
CopySlot(base_, type, TypeOffset.tp_is_gc);
InitializeSlots(type, impl);
Runtime.PyType_Ready(type);
IntPtr tp_dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict);
IntPtr mod = Runtime.PyString_FromString("CLR");
Runtime.PyDict_SetItemString(tp_dict, "__module__", mod);
return type;
}
//====================================================================
// Utility method to allocate a type object & do basic initialization.
//====================================================================
internal static IntPtr AllocateTypeObject(string name) {
IntPtr type = Runtime.PyType_GenericAlloc(Runtime.PyTypeType, 0);
// Cheat a little: we'll set tp_name to the internal char * of
// the Python version of the type name - otherwise we'd have to
// allocate the tp_name and would have no way to free it.
IntPtr temp = Runtime.PyString_FromString(name);
IntPtr raw = Runtime.PyString_AS_STRING(temp);
Marshal.WriteIntPtr(type, TypeOffset.tp_name, raw);
Marshal.WriteIntPtr(type, TypeOffset.name, temp);
long ptr = type.ToInt64(); // 64-bit safe
temp = new IntPtr(ptr + TypeOffset.nb_add);
Marshal.WriteIntPtr(type, TypeOffset.tp_as_number, temp);
temp = new IntPtr(ptr + TypeOffset.sq_length);
Marshal.WriteIntPtr(type, TypeOffset.tp_as_sequence, temp);
temp = new IntPtr(ptr + TypeOffset.mp_length);
Marshal.WriteIntPtr(type, TypeOffset.tp_as_mapping, temp);
temp = new IntPtr(ptr + TypeOffset.bf_getreadbuffer);
Marshal.WriteIntPtr(type, TypeOffset.tp_as_buffer, temp);
return type;
}
//====================================================================
// Given a newly allocated Python type object and a managed Type that
// provides the implementation for the type, connect the type slots of
// the Python object to the managed methods of the implementing Type.
//====================================================================
internal static void InitializeSlots(IntPtr type, Type impl) {
Hashtable seen = new Hashtable(8);
Type offsetType = typeof(TypeOffset);
while (impl != null) {
MethodInfo[] methods = impl.GetMethods(tbFlags);
for (int i = 0; i < methods.Length; i++) {
MethodInfo method = methods[i];
string name = method.Name;
if (! (name.StartsWith("tp_") ||
name.StartsWith("nb_") ||
name.StartsWith("sq_") ||
name.StartsWith("mp_") ||
name.StartsWith("bf_")
) ) {
continue;
}
if (seen[name] != null) {
continue;
}
FieldInfo fi = offsetType.GetField(name);
int offset = (int)fi.GetValue(offsetType);
IntPtr slot = Interop.GetThunk(method);
Marshal.WriteIntPtr(type, offset, slot);
seen[name] = 1;
}
impl = impl.BaseType;
}
}
//====================================================================
// Given a newly allocated Python type object and a managed Type that
// implements it, initialize any methods defined by the Type that need
// to appear in the Python type __dict__ (based on custom attribute).
//====================================================================
private static void InitMethods(IntPtr pytype, Type type) {
IntPtr dict = Marshal.ReadIntPtr(pytype, TypeOffset.tp_dict);
Type marker = typeof(PythonMethodAttribute);
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
while (type != null) {
MethodInfo[] methods = type.GetMethods(flags);
for (int i = 0; i < methods.Length; i++) {
MethodInfo method = methods[i];
object[] attrs = method.GetCustomAttributes(marker, false);
if (attrs.Length > 0) {
string method_name = method.Name;
MethodInfo[] mi = new MethodInfo[1];
mi[0] = method;
MethodObject m = new TypeMethod(method_name, mi);
Runtime.PyDict_SetItemString(dict, method_name,
m.pyHandle);
}
}
type = type.BaseType;
}
}
//====================================================================
// Utility method to copy slots from a given type to another type.
//====================================================================
internal static void CopySlot(IntPtr from, IntPtr to, int offset) {
IntPtr fp = Marshal.ReadIntPtr(from, offset);
Marshal.WriteIntPtr(to, offset, fp);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// This file contains the IDN functions and implementation.
//
// This allows encoding of non-ASCII domain names in a "punycode" form,
// for example:
//
// \u5B89\u5BA4\u5948\u7F8E\u6075-with-SUPER-MONKEYS
//
// is encoded as:
//
// xn---with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n
//
// Additional options are provided to allow unassigned IDN characters and
// to validate according to the Std3ASCII Rules (like DNS names).
//
// There are also rules regarding bidirectionality of text and the length
// of segments.
//
// For additional rules see also:
// RFC 3490 - Internationalizing Domain Names in Applications (IDNA)
// RFC 3491 - Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)
// RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)
//
// ==--==
namespace System.Globalization
{
using System;
using System.Security;
using System.Globalization;
using System.Text;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
// IdnMapping class used to map names to Punycode
public sealed class IdnMapping
{
// Legal name lengths for domain names
const int M_labelLimit = 63; // Not including dots
const int M_defaultNameLimit = 255; // Including dots
// IDNA prefix
const String M_strAcePrefix = "xn--";
// Legal "dot" seperators (i.e: . in www.microsoft.com)
static char[] M_Dots =
{
'.', '\u3002', '\uFF0E', '\uFF61'
};
bool m_bAllowUnassigned;
bool m_bUseStd3AsciiRules;
public IdnMapping()
{
}
public bool AllowUnassigned
{
get
{
return this.m_bAllowUnassigned;
}
set
{
this.m_bAllowUnassigned = value;
}
}
public bool UseStd3AsciiRules
{
get
{
return this.m_bUseStd3AsciiRules;
}
set
{
this.m_bUseStd3AsciiRules = value;
}
}
// Gets ASCII (Punycode) version of the string
public String GetAscii(String unicode)
{
return GetAscii(unicode, 0);
}
public String GetAscii(String unicode, int index)
{
if (unicode==null) throw new ArgumentNullException("unicode");
Contract.EndContractBlock();
return GetAscii(unicode, index, unicode.Length - index);
}
public String GetAscii(String unicode, int index, int count)
{
if (unicode==null) throw new ArgumentNullException("unicode");
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (index > unicode.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (index > unicode.Length - count)
throw new ArgumentOutOfRangeException("unicode",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// We're only using part of the string
unicode = unicode.Substring(index, count);
if (Environment.IsWindows8OrAbove)
{
return GetAsciiUsingOS(unicode);
}
// Check for ASCII only string, which will be unchanged
if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, true))
{
return unicode;
}
// Cannot be null terminated (normalization won't help us with this one, and
// may have returned false before checking the whole string above)
Contract.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
if (unicode[unicode.Length - 1] <= 0x1f)
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length-1 ),
"unicode");
}
// Have to correctly IDNA normalize the string and Unassigned flags
bool bHasLastDot = (unicode.Length > 0) && IsDot(unicode[unicode.Length - 1]);
unicode = unicode.Normalize((NormalizationForm)(m_bAllowUnassigned ?
ExtendedNormalizationForms.FormIdna : ExtendedNormalizationForms.FormIdnaDisallowUnassigned));
// Make sure we didn't normalize away something after a last dot
if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1]))
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
}
// May need to check Std3 rules again for non-ascii
if (UseStd3AsciiRules)
{
ValidateStd3AndAscii(unicode, true, false);
}
// Go ahead and encode it
return punycode_encode(unicode);
}
[System.Security.SecuritySafeCritical]
private String GetAsciiUsingOS(String unicode)
{
#if MONO
throw new NotSupportedException ();
#else
if (unicode.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
}
if (unicode[unicode.Length - 1] == 0)
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 1),
"unicode");
}
uint flags = (uint) ((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
int length = IdnToAscii(flags, unicode, unicode.Length, null, 0);
int lastError;
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "unicode");
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), "unicode");
}
char [] output = new char[length];
length = IdnToAscii(flags, unicode, unicode.Length, output, length);
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "unicode");
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), "unicode");
}
return new String(output, 0, length);
#endif
}
// Gets Unicode version of the string. Normalized and limited to IDNA characters.
public String GetUnicode(String ascii)
{
return GetUnicode(ascii, 0);
}
public String GetUnicode(String ascii, int index)
{
if (ascii==null) throw new ArgumentNullException("ascii");
Contract.EndContractBlock();
return GetUnicode(ascii, index, ascii.Length - index);
}
public String GetUnicode(String ascii, int index, int count)
{
if (ascii==null) throw new ArgumentNullException("ascii");
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (index > ascii.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (index > ascii.Length - count)
throw new ArgumentOutOfRangeException("ascii",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
// This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ.
// The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null.
// The Win32 APIs fail on an embedded null, but not on a terminating null.
if (count > 0 && ascii[index + count - 1] == (char)0)
throw new ArgumentException("ascii",
Environment.GetResourceString("Argument_IdnBadPunycode"));
Contract.EndContractBlock();
// We're only using part of the string
ascii = ascii.Substring(index, count);
if (Environment.IsWindows8OrAbove)
{
return GetUnicodeUsingOS(ascii);
}
// Convert Punycode to Unicode
String strUnicode = punycode_decode(ascii);
// Output name MUST obey IDNA rules & round trip (casing differences are allowed)
if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnIllegalName"), "ascii");
return strUnicode;
}
[System.Security.SecuritySafeCritical]
private string GetUnicodeUsingOS(string ascii)
{
#if MONO
throw new NotSupportedException ();
#else
uint flags = (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
int length = IdnToUnicode(flags, ascii, ascii.Length, null, 0);
int lastError;
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "ascii");
}
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii");
}
char [] output = new char[length];
length = IdnToUnicode(flags, ascii, ascii.Length, output, length);
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "ascii");
}
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii");
}
return new String(output, 0, length);
#endif
}
public override bool Equals(Object obj)
{
IdnMapping that = obj as IdnMapping;
if (that != null)
{
return this.m_bAllowUnassigned == that.m_bAllowUnassigned &&
this.m_bUseStd3AsciiRules == that.m_bUseStd3AsciiRules;
}
return (false);
}
public override int GetHashCode()
{
return (this.m_bAllowUnassigned ? 100 : 200) + (this.m_bUseStd3AsciiRules ? 1000 : 2000);
}
// Helpers
static bool IsSupplementary(int cTest)
{
return cTest >= 0x10000;
}
// Is it a dot?
// are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or
// U+FF61 (halfwidth ideographic full stop).
// Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization
static bool IsDot(char c)
{
return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61';
}
// See if we're only ASCII
static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii)
{
// If its empty, then its too small
if (unicode.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
Contract.EndContractBlock();
int iLastDot = -1;
// Loop the whole string
for (int i = 0; i < unicode.Length; i++)
{
// Aren't allowing control chars (or 7f, but idn tables catch that, they don't catch \0 at end though)
if (unicode[i] <= 0x1f)
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", i ),
"unicode");
}
// If its Unicode or a control character, return false (non-ascii)
if (bCheckAscii && unicode[i] >= 0x7f)
return false;
// Check for dots
if (IsDot(unicode[i]))
{
// Can't have 2 dots in a row
if (i == iLastDot + 1)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
// If its too far between dots then fail
if (i - iLastDot > M_labelLimit + 1)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "Unicode");
// If validating Std3, then char before dot can't be - char
if (bUseStd3 && i > 0)
ValidateStd3(unicode[i-1], true);
// Remember where the last dot is
iLastDot = i;
continue;
}
// If necessary, make sure its a valid std3 character
if (bUseStd3)
{
ValidateStd3(unicode[i], (i == iLastDot + 1));
}
}
// If we never had a dot, then we need to be shorter than the label limit
if (iLastDot == -1 && unicode.Length > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
// Need to validate entire string length, 1 shorter if last char wasn't a dot
if (unicode.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1])? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
"unicode");
// If last char wasn't a dot we need to check for trailing -
if (bUseStd3 && !IsDot(unicode[unicode.Length-1]))
ValidateStd3(unicode[unicode.Length-1], true);
return true;
}
// Validate Std3 rules for a character
static void ValidateStd3(char c, bool bNextToDot)
{
// Check for illegal characters
if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed
(c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) ||
(c == '-' && bNextToDot))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadStd3", c), "Unicode");
}
//
// The following punycode implementation is ported from the sample punycode.c in RFC 3492
// Original sample code was written by Adam M. Costello.
//
// Return whether a punycode code point is flagged as being upper case.
static bool HasUpperCaseFlag(char punychar)
{
return (punychar >= 'A' && punychar <= 'Z');
}
/**********************************************************/
/* Implementation (would normally go in its own .c file): */
/*** Bootstring parameters for Punycode ***/
const int punycodeBase = 36;
const int tmin = 1;
const int tmax = 26;
const int skew = 38;
const int damp = 700;
const int initial_bias = 72;
const int initial_n = 0x80;
const char delimiter = '-';
/* basic(cp) tests whether cp is a basic code point: */
static bool basic(uint cp)
{
// Is it in ASCII range?
return cp < 0x80;
}
// decode_digit(cp) returns the numeric value of a basic code */
// point (for use in representing integers) in the range 0 to */
// punycodeBase-1, or <0 if cp is does not represent a value. */
static int decode_digit(char cp)
{
if (cp >= '0' && cp <= '9')
return cp - '0' + 26;
// Two flavors for case differences
if (cp >= 'a' && cp <= 'z')
return cp - 'a';
if (cp >= 'A' && cp <= 'Z')
return cp - 'A';
// Expected 0-9, A-Z or a-z, everything else is illegal
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
}
/* encode_digit(d,flag) returns the basic code point whose value */
/* (when used for representing integers) is d, which needs to be in */
/* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */
/* true, in which case the uppercase form is used. */
static char encode_digit(int d)
{
Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
// 26-35 map to ASCII 0-9
if (d > 25) return (char)(d - 26 + '0');
// 0-25 map to a-z or A-Z
return (char)(d + 'a');
}
/* encode_basic(bcp,flag) forces a basic code point to lowercase */
/* if flag is false, uppercase if flag is true, and returns */
/* the resulting code point. The code point is unchanged if it */
/* is caseless. The behavior is undefined if bcp is not a basic */
/* code point. */
static char encode_basic(char bcp)
{
if (HasUpperCaseFlag(bcp))
bcp += (char)('a' - 'A');
return bcp;
}
/*** Platform-specific constants ***/
/* maxint is the maximum value of a uint variable: */
const int maxint = 0x7ffffff;
/*** Bias adaptation function ***/
static int adapt(
int delta, int numpoints, bool firsttime )
{
uint k;
delta = firsttime ? delta / damp : delta / 2;
Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
delta += delta / numpoints;
for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
{
delta /= punycodeBase - tmin;
}
Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew));
}
/*** Main encode function ***/
/* punycode_encode() converts Unicode to Punycode. The input */
/* is represented as an array of Unicode code points (not code */
/* units; surrogate pairs are not allowed), and the output */
/* will be represented as an array of ASCII code points. The */
/* output string is *not* null-terminated; it will contain */
/* zeros if and only if the input contains zeros. (Of course */
/* the caller can leave room for a terminator and add one if */
/* needed.) The input_length is the number of code points in */
/* the input. The output_length is an in/out argument: the */
/* caller passes in the maximum number of code points that it */
/* can receive, and on successful return it will contain the */
/* number of code points actually output. The case_flags array */
/* holds input_length boolean values, where nonzero suggests that */
/* the corresponding Unicode character be forced to uppercase */
/* after being decoded (if possible), and zero suggests that */
/* it be forced to lowercase (if possible). ASCII code points */
/* are encoded literally, except that ASCII letters are forced */
/* to uppercase or lowercase according to the corresponding */
/* uppercase flags. If case_flags is a null pointer then ASCII */
/* letters are left as they are, and other code points are */
/* treated as if their uppercase flags were zero. The return */
/* value can be any of the punycode_status values defined above */
/* except punycode_bad_input; if not punycode_success, then */
/* output_size and output might contain garbage. */
static String punycode_encode(String unicode)
{
// 0 length strings aren't allowed
if (unicode.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
Contract.EndContractBlock();
StringBuilder output = new StringBuilder(unicode.Length);
int iNextDot = 0;
int iAfterLastDot = 0;
int iOutputAfterLastDot = 0;
// Find the next dot
while (iNextDot < unicode.Length)
{
// Find end of this segment
iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot);
Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
if (iNextDot < 0)
iNextDot = unicode.Length;
// Only allowed to have empty . section at end (www.microsoft.com.)
if (iNextDot == iAfterLastDot)
{
// Only allowed to have empty sections as trailing .
if (iNextDot != unicode.Length)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
// Last dot, stop
break;
}
// We'll need an Ace prefix
output.Append(M_strAcePrefix);
// Everything resets every segment.
bool bRightToLeft = false;
// Check for RTL. If right-to-left, then 1st & last chars must be RTL
BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iAfterLastDot);
if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)
{
// It has to be right to left.
bRightToLeft = true;
// Check last char
int iTest = iNextDot - 1;
if (Char.IsLowSurrogate(unicode, iTest))
{
iTest--;
}
eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iTest);
if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), "unicode");
}
}
// Handle the basic code points
int basicCount;
int numProcessed = 0; // Num code points that have been processed so far (this segment)
for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
{
// Can't be lonely surrogate because it would've thrown in normalization
Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
"[IdnMapping.punycode_encode]Unexpected low surrogate");
// Double check our bidi rules
BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount);
// If we're RTL, we can't have LTR chars
if (bRightToLeft && testBidi == BidiCategory.LeftToRight)
{
// Oops, throw error
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), "unicode");
}
// If we're not RTL we can't have RTL chars
if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft ||
testBidi == BidiCategory.RightToLeftArabic))
{
// Oops, throw error
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), "unicode");
}
// If its basic then add it
if (basic(unicode[basicCount]))
{
output.Append(encode_basic(unicode[basicCount]));
numProcessed++;
}
// If its a surrogate, skip the next since our bidi category tester doesn't handle it.
else if (Char.IsSurrogatePair(unicode, basicCount))
basicCount++;
}
int numBasicCodePoints = numProcessed; // number of basic code points
// Stop if we ONLY had basic code points
if (numBasicCodePoints == iNextDot - iAfterLastDot)
{
// Get rid of xn-- and this segments done
output.Remove(iOutputAfterLastDot, M_strAcePrefix.Length);
}
else
{
// If it has some non-basic code points the input cannot start with xn--
if (unicode.Length - iAfterLastDot >= M_strAcePrefix.Length &&
unicode.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "unicode");
// Need to do ACE encoding
int numSurrogatePairs = 0; // number of surrogate pairs so far
// Add a delimiter (-) if we had any basic code points (between basic and encoded pieces)
if (numBasicCodePoints > 0)
{
output.Append(delimiter);
}
// Initialize the state
int n = initial_n;
int delta = 0;
int bias = initial_bias;
// Main loop
while (numProcessed < (iNextDot - iAfterLastDot))
{
/* All non-basic code points < n have been */
/* handled already. Find the next larger one: */
int j;
int m;
int test = 0;
for (m = maxint, j = iAfterLastDot;
j < iNextDot;
j += IsSupplementary(test) ? 2 : 1)
{
test = Char.ConvertToUtf32(unicode, j);
if (test >= n && test < m) m = test;
}
/* Increase delta enough to advance the decoder's */
/* <n,i> state to <m,0>, but guard against overflow: */
delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1));
Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
n = m;
for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1)
{
// Make sure we're aware of surrogates
test = Char.ConvertToUtf32(unicode, j);
// Adjust for character position (only the chars in our string already, some
// haven't been processed.
if (test < n)
{
delta++;
Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
}
if (test == n)
{
// Represent delta as a generalized variable-length integer:
int q, k;
for (q = delta, k = punycodeBase; ; k += punycodeBase)
{
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (q < t) break;
Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
output.Append(encode_digit(t + (q - t) % (punycodeBase - t)));
q = (q - t) / (punycodeBase - t);
}
output.Append(encode_digit(q));
bias = adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints);
delta = 0;
numProcessed++;
if (IsSupplementary(m))
{
numProcessed++;
numSurrogatePairs++;
}
}
}
++delta;
++n;
Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
}
}
// Make sure its not too big
if (output.Length - iOutputAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "unicode");
// Done with this segment, add dot if necessary
if (iNextDot != unicode.Length)
output.Append('.');
iAfterLastDot = iNextDot + 1;
iOutputAfterLastDot = output.Length;
}
// Throw if we're too long
if (output.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
"unicode");
// Return our output string
return output.ToString();
}
/*** Main decode function ***/
/* punycode_decode() converts Punycode to Unicode. The input is */
/* represented as an array of ASCII code points, and the output */
/* will be represented as an array of Unicode code points. The */
/* input_length is the number of code points in the input. The */
/* output_length is an in/out argument: the caller passes in */
/* the maximum number of code points that it can receive, and */
/* on successful return it will contain the actual number of */
/* code points output. The case_flags array needs room for at */
/* least output_length values, or it can be a null pointer if the */
/* case information is not needed. A nonzero flag suggests that */
/* the corresponding Unicode character be forced to uppercase */
/* by the caller (if possible), while zero suggests that it be */
/* forced to lowercase (if possible). ASCII code points are */
/* output already in the proper case, but their flags will be set */
/* appropriately so that applying the flags would be harmless. */
/* The return value can be any of the punycode_status values */
/* defined above; if not punycode_success, then output_length, */
/* output, and case_flags might contain garbage. On success, the */
/* decoder will never need to write an output_length greater than */
/* input_length, because of how the encoding is defined. */
static String punycode_decode( String ascii )
{
// 0 length strings aren't allowed
if (ascii.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "ascii");
Contract.EndContractBlock();
// Throw if we're too long
if (ascii.Length > M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), "ascii");
// output stringbuilder
StringBuilder output = new StringBuilder(ascii.Length);
// Dot searching
int iNextDot = 0;
int iAfterLastDot = 0;
int iOutputAfterLastDot = 0;
while (iNextDot < ascii.Length)
{
// Find end of this segment
iNextDot = ascii.IndexOf('.', iAfterLastDot);
if (iNextDot < 0 || iNextDot > ascii.Length)
iNextDot = ascii.Length;
// Only allowed to have empty . section at end (www.microsoft.com.)
if (iNextDot == iAfterLastDot)
{
// Only allowed to have empty sections as trailing .
if (iNextDot != ascii.Length)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "ascii");
// Last dot, stop
break;
}
// In either case it can't be bigger than segment size
if (iNextDot - iAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "ascii");
// See if this section's ASCII or ACE
if (ascii.Length < M_strAcePrefix.Length + iAfterLastDot ||
!ascii.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
{
// Its supposed to be just ASCII
// Actually, for non xn-- stuff do we want to allow Unicode?
// for (int i = iAfterLastDot; i < iNextDot; i++)
// {
// // Only ASCII is allowed
// if (ascii[i] >= 0x80)
// throw new ArgumentException(Environment.GetResourceString(
// "Argument_IdnBadPunycode"), "ascii");
// }
// Its ASCII, copy it
output.Append(ascii.Substring(iAfterLastDot, iNextDot - iAfterLastDot));
// ASCII doesn't have BIDI issues
}
else
{
// Not ASCII, bump up iAfterLastDot to be after ACE Prefix
iAfterLastDot += M_strAcePrefix.Length;
// Get number of basic code points (where delimiter is)
// numBasicCodePoints < 0 if there're no basic code points
int iTemp = ascii.LastIndexOf(delimiter, iNextDot - 1);
// Trailing - not allowed
if (iTemp == iNextDot - 1)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
int numBasicCodePoints;
if (iTemp <= iAfterLastDot)
numBasicCodePoints = 0;
else
{
numBasicCodePoints = iTemp - iAfterLastDot;
// Copy all the basic code points, making sure they're all in the allowed range,
// and losing the casing for all of them.
for (int copyAscii = iAfterLastDot;
copyAscii < iAfterLastDot + numBasicCodePoints;
copyAscii++)
{
// Make sure we don't allow unicode in the ascii part
if (ascii[copyAscii] > 0x7f)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
// When appending make sure they get lower cased
output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ?
ascii[copyAscii] - 'A' + 'a' :
ascii[copyAscii]));
}
}
// Get ready for main loop. Start at beginning if we didn't have any
// basic code points, otherwise start after the -.
// asciiIndex will be next character to read from ascii
int asciiIndex = iAfterLastDot +
( numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
// initialize our state
int n = initial_n;
int bias = initial_bias;
int i = 0;
int w, k;
// no Supplementary characters yet
int numSurrogatePairs = 0;
// Main loop, read rest of ascii
while (asciiIndex < iNextDot)
{
/* Decode a generalized variable-length integer into delta, */
/* which gets added to i. The overflow checking is easier */
/* if we increase i as we go, then subtract off its starting */
/* value at the end to obtain delta. */
int oldi = i;
for (w = 1, k = punycodeBase; ; k += punycodeBase)
{
// Check to make sure we aren't overrunning our ascii string
if (asciiIndex >= iNextDot)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
// decode the digit from the next char
int digit = decode_digit(ascii[asciiIndex++]);
Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
if (digit > (maxint - i) / w)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
i += (int)(digit * w);
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (digit < t) break;
Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
if (w > maxint / (punycodeBase - t))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
w *= (punycodeBase - t);
}
bias = adapt(i - oldi,
(output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0);
/* i was supposed to wrap around from output.Length to 0, */
/* incrementing n each time, so we'll fix that now: */
Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
"[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1));
i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1);
// If it was flagged it needs to be capitalized
// if (HasUpperCaseFlag(ascii[asciiIndex - 1]))
// {
// /* Case of last character determines uppercase flag: */
// // Any casing stuff need to happen last.
// If we wanted to reverse the IDNA casing data
// n = MakeNUpperCase(n)
// }
// Make sure n is legal
if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
// insert n at position i of the output: Really tricky if we have surrogates
int iUseInsertLocation;
String strTemp = Char.ConvertFromUtf32(n);
// If we have supplimentary characters
if (numSurrogatePairs > 0)
{
// Hard way, we have supplimentary characters
int iCount;
for (iCount = i, iUseInsertLocation = iOutputAfterLastDot;
iCount > 0;
iCount--, iUseInsertLocation++)
{
// If its a surrogate, we have to go one more
if (iUseInsertLocation >= output.Length)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
if (Char.IsSurrogate(output[iUseInsertLocation]))
iUseInsertLocation++;
}
}
else
{
// No Supplementary chars yet, just add i
iUseInsertLocation = iOutputAfterLastDot + i;
}
// Insert it
output.Insert(iUseInsertLocation, strTemp);
// If it was a surrogate increment our counter
if (IsSupplementary(n))
numSurrogatePairs++;
// Index gets updated
i++;
}
// Do BIDI testing
bool bRightToLeft = false;
// Check for RTL. If right-to-left, then 1st & last chars must be RTL
BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iOutputAfterLastDot);
if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)
{
// It has to be right to left.
bRightToLeft = true;
}
// Check the rest of them to make sure RTL/LTR is consistent
for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++)
{
// This might happen if we run into a pair
if (Char.IsLowSurrogate(output.ToString(), iTest)) continue;
// Check to see if its LTR
eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iTest);
if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) ||
(!bRightToLeft && (eBidi == BidiCategory.RightToLeft ||
eBidi == BidiCategory.RightToLeftArabic)))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), "ascii");
// Make it lower case if we must (so we can test IsNormalized later)
// if (output[iTest] >= 'A' && output[iTest] <= 'Z')
// output[iTest] = (char)(output[iTest] + (char)('a' - 'A'));
}
// Its also a requirement that the last one be RTL if 1st is RTL
if (bRightToLeft && eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), "ascii");
}
}
// See if this label was too long
if (iNextDot - iAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), "ascii");
// Done with this segment, add dot if necessary
if (iNextDot != ascii.Length)
output.Append('.');
iAfterLastDot = iNextDot + 1;
iOutputAfterLastDot = output.Length;
}
// Throw if we're too long
if (output.Length > M_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), "ascii");
// Return our output string
return output.ToString();
}
/*
The previous punycode implimentation is based on the sample code in RFC 3492
Full Copyright Statement
Copyright (C) The Internet Society (2003). All Rights Reserved.
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published
and distributed, in whole or in part, without restriction of any
kind, provided that the above copyright notice and this paragraph are
included on all such copies and derivative works. However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English.
The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*/
#if !MONO
private const int IDN_ALLOW_UNASSIGNED = 0x1;
private const int IDN_USE_STD3_ASCII_RULES = 0x2;
private const int ERROR_INVALID_NAME = 123;
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToAscii(
uint dwFlags,
[InAttribute()]
[MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
String lpUnicodeCharStr,
int cchUnicodeChar,
[System.Runtime.InteropServices.OutAttribute()]
char [] lpASCIICharStr,
int cchASCIIChar);
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToUnicode(
uint dwFlags,
[InAttribute()]
[MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
string lpASCIICharStr,
int cchASCIIChar,
[System.Runtime.InteropServices.OutAttribute()]
char [] lpUnicodeCharStr,
int cchUnicodeChar);
#endif
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetS3TargetBucketNamesSpectraS3Request : Ds3Request
{
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _targetId;
public string TargetId
{
get { return _targetId; }
set { WithTargetId(value); }
}
public GetS3TargetBucketNamesSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithTargetId(Guid? targetId)
{
this._targetId = targetId.ToString();
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId.ToString());
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request WithTargetId(string targetId)
{
this._targetId = targetId;
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId);
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetS3TargetBucketNamesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/s3_target_bucket_name";
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: System.Text.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace System.Text
{
/// <summary>
/// <para>A modifiable sequence of characters for use in creating strings. This class is intended as a direct replacement of StringBuffer for non-concurrent use; unlike <c> StringBuffer </c> this class is not synchronized.</para><para>For particularly complex string-building needs, consider java.util.Formatter.</para><para>The majority of the modification methods on this class return <c> this </c> so that method calls can be chained together. For example: <c> new StringBuilder("a").append("b").append("c").toString() </c> .</para><para><para>CharSequence </para><simplesectsep></simplesectsep><para>Appendable </para><simplesectsep></simplesectsep><para>StringBuffer </para><simplesectsep></simplesectsep><para>String </para><simplesectsep></simplesectsep><para>String::format </para><para>1.5 </para></para>
/// </summary>
/// <java-name>
/// java/lang/StringBuilder
/// </java-name>
[Dot42.DexImport("java/lang/StringBuilder", AccessFlags = 49)]
public sealed partial class StringBuilder : global::Java.Lang.IAppendable, global::Java.Lang.ICharSequence, global::Java.Io.ISerializable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs an instance with an initial capacity of <c> 16 </c> .</para><para><para>#capacity() </para></para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public StringBuilder() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs an instance with the specified capacity.</para><para><para>#capacity() </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)]
public StringBuilder(int capacity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs an instance with the specified capacity.</para><para><para>#capacity() </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/CharSequence;)V", AccessFlags = 1)]
public StringBuilder(global::Java.Lang.ICharSequence capacity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs an instance with the specified capacity.</para><para><para>#capacity() </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public StringBuilder(string capacity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Z)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(bool b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(C)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(char b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(I)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(int b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(J)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(long b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(F)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(float b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(D)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(double b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(object b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(string b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/StringBuffer;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(global::Java.Lang.StringBuffer b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([C)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(char[] b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified subset of the <c> char[] </c> . The <c> char[] </c> value is converted to a String according to the rule defined by String#valueOf(char[],int,int).</para><para><para>String::valueOf(char[],int,int) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([CII)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(char[] str, int offset, int len) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified <c> boolean </c> value. The <c> boolean </c> value is converted to a String according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/CharSequence;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Append(global::Java.Lang.ICharSequence b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the string representation of the specified subset of the <c> char[] </c> . The <c> char[] </c> value is converted to a String according to the rule defined by String#valueOf(char[],int,int).</para><para><para>String::valueOf(char[],int,int) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/CharSequence;II)Ljava/lang/StringBuilder;", AccessFlags = 1)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public global::System.Text.StringBuilder JavaAppend(global::Java.Lang.ICharSequence str, int offset, int len) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Appends the encoded Unicode code point. The code point is converted to a <c> char[] </c> as defined by Character#toChars(int).</para><para><para>Character::toChars(int) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// appendCodePoint
/// </java-name>
[Dot42.DexImport("appendCodePoint", "(I)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder AppendCodePoint(int codePoint) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Deletes a sequence of characters specified by <c> start </c> and <c> end </c> . Shifts any remaining characters to the left.</para><para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// delete
/// </java-name>
[Dot42.DexImport("delete", "(II)Ljava/lang/StringBuilder;", AccessFlags = 1)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public global::System.Text.StringBuilder JavaDelete(int start, int end) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Deletes the character at the specified index. shifts any remaining characters to the left.</para><para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// deleteCharAt
/// </java-name>
[Dot42.DexImport("deleteCharAt", "(I)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder DeleteCharAt(int index) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(IZ)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, bool b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(IC)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, char b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(II)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, int b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(IJ)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, long b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(IF)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, float b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(ID)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, double b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(ILjava/lang/Object;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, object b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(ILjava/lang/String;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, string b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(I[C)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, char[] b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified subsequence of the <c> char[] </c> at the specified <c> offset </c> . The <c> char[] </c> value is converted to a String according to the rule defined by String#valueOf(char[],int,int).</para><para><para>String::valueOf(char[],int,int) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(I[CII)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, char[] str, int strOffset, int strLen) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified <c> boolean </c> value at the specified <c> offset </c> . The <c> boolean </c> value is converted to a string according to the rule defined by String#valueOf(boolean).</para><para><para>String::valueOf(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(ILjava/lang/CharSequence;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Insert(int offset, global::Java.Lang.ICharSequence b) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Inserts the string representation of the specified subsequence of the <c> char[] </c> at the specified <c> offset </c> . The <c> char[] </c> value is converted to a String according to the rule defined by String#valueOf(char[],int,int).</para><para><para>String::valueOf(char[],int,int) </para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// insert
/// </java-name>
[Dot42.DexImport("insert", "(ILjava/lang/CharSequence;II)Ljava/lang/StringBuilder;", AccessFlags = 1)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public global::System.Text.StringBuilder JavaInsert(int offset, global::Java.Lang.ICharSequence str, int strOffset, int strLen) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Replaces the specified subsequence in this builder with the specified string.</para><para></para>
/// </summary>
/// <returns>
/// <para>this builder. </para>
/// </returns>
/// <java-name>
/// replace
/// </java-name>
[Dot42.DexImport("replace", "(IILjava/lang/String;)Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Replace(int start, int end, string @string) /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Reverses the order of characters in this builder.</para><para></para>
/// </summary>
/// <returns>
/// <para>this buffer. </para>
/// </returns>
/// <java-name>
/// reverse
/// </java-name>
[Dot42.DexImport("reverse", "()Ljava/lang/StringBuilder;", AccessFlags = 1)]
public global::System.Text.StringBuilder Reverse() /* MethodBuilder.Create */
{
return default(global::System.Text.StringBuilder);
}
/// <summary>
/// <para>Returns the contents of this builder.</para><para></para>
/// </summary>
/// <returns>
/// <para>the string representation of the data in this builder. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// capacity
/// </java-name>
[Dot42.DexImport("capacity", "()I", AccessFlags = 1)]
public int GetCapacity() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// charAt
/// </java-name>
[Dot42.DexImport("charAt", "(I)C", AccessFlags = 1)]
public char CharAt(int int32) /* MethodBuilder.Create */
{
return default(char);
}
/// <java-name>
/// ensureCapacity
/// </java-name>
[Dot42.DexImport("ensureCapacity", "(I)V", AccessFlags = 1)]
public void EnsureCapacity(int int32) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getChars
/// </java-name>
[Dot42.DexImport("getChars", "(II[CI)V", AccessFlags = 1)]
public void GetChars(int int32, int int321, char[] @char, int int322) /* MethodBuilder.Create */
{
}
/// <java-name>
/// length
/// </java-name>
[Dot42.DexImport("length", "()I", AccessFlags = 1)]
public int GetLength() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setCharAt
/// </java-name>
[Dot42.DexImport("setCharAt", "(IC)V", AccessFlags = 1)]
public void SetCharAt(int int32, char @char) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setLength
/// </java-name>
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
public void SetLength(int int32) /* MethodBuilder.Create */
{
}
/// <java-name>
/// substring
/// </java-name>
[Dot42.DexImport("substring", "(I)Ljava/lang/String;", AccessFlags = 1)]
public string Substring(int int32) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// substring
/// </java-name>
[Dot42.DexImport("substring", "(II)Ljava/lang/String;", AccessFlags = 1)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public string JavaSubstring(int int32, int int321) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// subSequence
/// </java-name>
[Dot42.DexImport("subSequence", "(II)Ljava/lang/CharSequence;", AccessFlags = 1)]
public global::Java.Lang.ICharSequence SubSequence(int int32, int int321) /* MethodBuilder.Create */
{
return default(global::Java.Lang.ICharSequence);
}
/// <java-name>
/// indexOf
/// </java-name>
[Dot42.DexImport("indexOf", "(Ljava/lang/String;)I", AccessFlags = 1)]
public int IndexOf(string @string) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// indexOf
/// </java-name>
[Dot42.DexImport("indexOf", "(Ljava/lang/String;I)I", AccessFlags = 1)]
public int IndexOf(string @string, int int32) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// lastIndexOf
/// </java-name>
[Dot42.DexImport("lastIndexOf", "(Ljava/lang/String;)I", AccessFlags = 1)]
public int LastIndexOf(string @string) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// lastIndexOf
/// </java-name>
[Dot42.DexImport("lastIndexOf", "(Ljava/lang/String;I)I", AccessFlags = 1)]
public int LastIndexOf(string @string, int int32) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// trimToSize
/// </java-name>
[Dot42.DexImport("trimToSize", "()V", AccessFlags = 1)]
public void TrimToSize() /* MethodBuilder.Create */
{
}
/// <java-name>
/// codePointAt
/// </java-name>
[Dot42.DexImport("codePointAt", "(I)I", AccessFlags = 1)]
public int CodePointAt(int int32) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// codePointBefore
/// </java-name>
[Dot42.DexImport("codePointBefore", "(I)I", AccessFlags = 1)]
public int CodePointBefore(int int32) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// codePointCount
/// </java-name>
[Dot42.DexImport("codePointCount", "(II)I", AccessFlags = 1)]
public int CodePointCount(int int32, int int321) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// offsetByCodePoints
/// </java-name>
[Dot42.DexImport("offsetByCodePoints", "(II)I", AccessFlags = 1)]
public int OffsetByCodePoints(int int32, int int321) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/lang/Appendable", "append", "(C)Ljava/lang/Appendable;", AccessFlags = 1025)]
global::Java.Lang.IAppendable global::Java.Lang.IAppendable.Append(char c) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Java.Lang.IAppendable);
}
[Dot42.DexImport("java/lang/Appendable", "append", "(Ljava/lang/CharSequence;)Ljava/lang/Appendable;", AccessFlags = 1025)]
global::Java.Lang.IAppendable global::Java.Lang.IAppendable.Append(global::Java.Lang.ICharSequence c) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Java.Lang.IAppendable);
}
[Dot42.DexImport("java/lang/Appendable", "append", "(Ljava/lang/CharSequence;II)Ljava/lang/Appendable;", AccessFlags = 1025)]
global::Java.Lang.IAppendable global::Java.Lang.IAppendable.JavaAppend(global::Java.Lang.ICharSequence csq, int start, int end) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Java.Lang.IAppendable);
}
/// <java-name>
/// capacity
/// </java-name>
public int Capacity
{
[Dot42.DexImport("capacity", "()I", AccessFlags = 1)]
get{ return GetCapacity(); }
}
/// <java-name>
/// length
/// </java-name>
public int Length
{
[Dot42.DexImport("length", "()I", AccessFlags = 1)]
get{ return GetLength(); }
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
set{ SetLength(value); }
}
}
}
| |
// <copyright file="FirefoxDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium.Firefox
{
/// <summary>
/// Provides a way to access Firefox to run tests.
/// </summary>
/// <remarks>
/// When the FirefoxDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and
/// start your test.
/// <para>
/// In the case of the FirefoxDriver, you can specify a named profile to be used, or you can let the
/// driver create a temporary, anonymous profile. A custom extension allowing the driver to communicate
/// to the browser will be installed into the profile.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// [TestFixture]
/// public class Testing
/// {
/// private IWebDriver driver;
/// <para></para>
/// [SetUp]
/// public void SetUp()
/// {
/// driver = new FirefoxDriver();
/// }
/// <para></para>
/// [Test]
/// public void TestGoogle()
/// {
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// /*
/// * Rest of the test
/// */
/// }
/// <para></para>
/// [TearDown]
/// public void TearDown()
/// {
/// driver.Quit();
/// }
/// }
/// </code>
/// </example>
public class FirefoxDriver : RemoteWebDriver
{
private const string SetContextCommand = "setContext";
private const string InstallAddOnCommand = "installAddOn";
private const string UninstallAddOnCommand = "uninstallAddOn";
private const string GetFullPageScreenshotCommand = "fullPageScreenshot";
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class.
/// </summary>
public FirefoxDriver()
: this(new FirefoxOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options. Uses the Mozilla-provided Marionette driver implementation.
/// </summary>
/// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param>
public FirefoxDriver(FirefoxOptions options)
: this(CreateService(options), options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified driver service. Uses the Mozilla-provided Marionette driver implementation.
/// </summary>
/// <param name="service">The <see cref="FirefoxDriverService"/> used to initialize the driver.</param>
public FirefoxDriver(FirefoxDriverService service)
: this(service, new FirefoxOptions(), RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path
/// to the directory containing geckodriver.exe.
/// </summary>
/// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param>
public FirefoxDriver(string geckoDriverDirectory)
: this(geckoDriverDirectory, new FirefoxOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path
/// to the directory containing geckodriver.exe and options.
/// </summary>
/// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param>
/// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param>
public FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options)
: this(geckoDriverDirectory, options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path
/// to the directory containing geckodriver.exe, options, and command timeout.
/// </summary>
/// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param>
/// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options, TimeSpan commandTimeout)
: this(FirefoxDriverService.CreateDefaultService(geckoDriverDirectory), options, commandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options, driver service, and timeout. Uses the Mozilla-provided Marionette driver implementation.
/// </summary>
/// <param name="service">The <see cref="FirefoxDriverService"/> to use.</param>
/// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param>
public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options)
: this(service, options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options, driver service, and timeout. Uses the Mozilla-provided Marionette driver implementation.
/// </summary>
/// <param name="service">The <see cref="FirefoxDriverService"/> to use.</param>
/// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options, TimeSpan commandTimeout)
: base(new DriverServiceCommandExecutor(service, commandTimeout), ConvertOptionsToCapabilities(options))
{
// Add the custom commands unique to Firefox
this.AddCustomFirefoxCommand(SetContextCommand, CommandInfo.PostCommand, "/session/{sessionId}/moz/context");
this.AddCustomFirefoxCommand(InstallAddOnCommand, CommandInfo.PostCommand, "/session/{sessionId}/moz/addon/install");
this.AddCustomFirefoxCommand(UninstallAddOnCommand, CommandInfo.PostCommand, "/session/{sessionId}/moz/addon/uninstall");
this.AddCustomFirefoxCommand(GetFullPageScreenshotCommand, CommandInfo.GetCommand, "/session/{sessionId}/moz/screenshot/full");
}
/// <summary>
/// Gets or sets the <see cref="IFileDetector"/> responsible for detecting
/// sequences of keystrokes representing file paths and names.
/// </summary>
/// <remarks>The Firefox driver does not allow a file detector to be set,
/// as the server component of the Firefox driver only allows uploads from
/// the local computer environment. Attempting to set this property has no
/// effect, but does not throw an exception. If you are attempting to run
/// the Firefox driver remotely, use <see cref="RemoteWebDriver"/> in
/// conjunction with a standalone WebDriver server.</remarks>
public override IFileDetector FileDetector
{
get { return base.FileDetector; }
set { }
}
/// <summary>
/// Sets the command context used when issuing commands to geckodriver.
/// </summary>
/// <param name="context">The <see cref="FirefoxCommandContext"/> value to which to set the context.</param>
public void SetContext(FirefoxCommandContext context)
{
string contextValue = context.ToString().ToLowerInvariant();
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["context"] = contextValue;
Response response = this.Execute(SetContextCommand, parameters);
}
/// <summary>
/// Installs a Firefox add-on from a file, typically a .xpi file.
/// </summary>
/// <param name="addOnFileToInstall">Full path and file name of the add-on to install.</param>
public void InstallAddOnFromFile(string addOnFileToInstall)
{
if (string.IsNullOrEmpty(addOnFileToInstall))
{
throw new ArgumentNullException("addOnFileToInstall", "Add-on file name must not be null or the empty string");
}
if (!File.Exists(addOnFileToInstall))
{
throw new ArgumentException("File " + addOnFileToInstall + " does not exist", "addOnFileToInstall");
}
// Implementation note: There is a version of the install add-on
// command that can be used with a file name directly, by passing
// a "path" property in the parameters object of the command. If
// delegating to the "use the base64-encoded blob" version causes
// issues, we can change this method to use the file name directly
// instead.
byte[] addOnBytes = File.ReadAllBytes(addOnFileToInstall);
string base64AddOn = Convert.ToBase64String(addOnBytes);
this.InstallAddOn(base64AddOn);
}
/// <summary>
/// Installs a Firefox add-on.
/// </summary>
/// <param name="base64EncodedAddOn">The base64-encoded string representation of the add-on binary.</param>
public void InstallAddOn(string base64EncodedAddOn)
{
if (string.IsNullOrEmpty(base64EncodedAddOn))
{
throw new ArgumentNullException("base64EncodedAddOn", "Base64 encoded add-on must not be null or the empty string");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["addon"] = base64EncodedAddOn;
this.Execute(InstallAddOnCommand, parameters);
}
/// <summary>
/// Uninstalls a Firefox add-on.
/// </summary>
/// <param name="addOnId">The ID of the add-on to uninstall.</param>
public void UninstallAddOn(string addOnId)
{
if (string.IsNullOrEmpty(addOnId))
{
throw new ArgumentNullException("addOnId", "Base64 encoded add-on must not be null or the empty string");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["id"] = addOnId;
this.Execute(UninstallAddOnCommand, parameters);
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the full page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetFullPageScreenshot()
{
Response screenshotResponse = this.Execute(GetFullPageScreenshotCommand, null);
string base64 = screenshotResponse.Value.ToString();
return new Screenshot(base64);
}
/// <summary>
/// In derived classes, the <see cref="PrepareEnvironment"/> method prepares the environment for test execution.
/// </summary>
protected virtual void PrepareEnvironment()
{
// Does nothing, but provides a hook for subclasses to do "stuff"
}
private static ICapabilities ConvertOptionsToCapabilities(FirefoxOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options", "options must not be null");
}
return options.ToCapabilities();
}
private static FirefoxDriverService CreateService(FirefoxOptions options)
{
return FirefoxDriverService.CreateDefaultService();
}
private void AddCustomFirefoxCommand(string commandName, string method, string resourcePath)
{
CommandInfo commandInfoToAdd = new CommandInfo(method, resourcePath);
this.CommandExecutor.CommandInfoRepository.TryAddCommand(commandName, commandInfoToAdd);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
using System.Collections;
internal class XLRows : IXLRows, IXLStylized
{
public Boolean StyleChanged { get; set; }
private readonly List<XLRow> _rows = new List<XLRow>();
private readonly XLWorksheet _worksheet;
internal IXLStyle style;
public XLRows(XLWorksheet worksheet)
{
_worksheet = worksheet;
style = new XLStyle(this, XLWorkbook.DefaultStyle);
}
#region IXLRows Members
public IEnumerator<IXLRow> GetEnumerator()
{
return _rows.Cast<IXLRow>().OrderBy(r=>r.RowNumber()).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IXLStyle Style
{
get { return style; }
set
{
style = new XLStyle(this, value);
if (_worksheet != null)
_worksheet.Style = value;
else
{
foreach (XLRow row in _rows)
row.Style = value;
}
}
}
public double Height
{
set
{
_rows.ForEach(c => c.Height = value);
if (_worksheet == null) return;
_worksheet.RowHeight = value;
_worksheet.Internals.RowsCollection.ForEach(r => r.Value.Height = value);
}
}
public void Delete()
{
if (_worksheet != null)
{
_worksheet.Internals.RowsCollection.Clear();
_worksheet.Internals.CellsCollection.Clear();
}
else
{
var toDelete = new Dictionary<IXLWorksheet, List<Int32>>();
foreach (XLRow r in _rows)
{
if (!toDelete.ContainsKey(r.Worksheet))
toDelete.Add(r.Worksheet, new List<Int32>());
toDelete[r.Worksheet].Add(r.RowNumber());
}
foreach (KeyValuePair<IXLWorksheet, List<int>> kp in toDelete)
{
foreach (int r in kp.Value.OrderByDescending(r => r))
kp.Key.Row(r).Delete();
}
}
}
public IXLRows AdjustToContents()
{
_rows.ForEach(r => r.AdjustToContents());
return this;
}
public IXLRows AdjustToContents(Int32 startColumn)
{
_rows.ForEach(r => r.AdjustToContents(startColumn));
return this;
}
public IXLRows AdjustToContents(Int32 startColumn, Int32 endColumn)
{
_rows.ForEach(r => r.AdjustToContents(startColumn, endColumn));
return this;
}
public IXLRows AdjustToContents(Double minHeight, Double maxHeight)
{
_rows.ForEach(r => r.AdjustToContents(minHeight, maxHeight));
return this;
}
public IXLRows AdjustToContents(Int32 startColumn, Double minHeight, Double maxHeight)
{
_rows.ForEach(r => r.AdjustToContents(startColumn, minHeight, maxHeight));
return this;
}
public IXLRows AdjustToContents(Int32 startColumn, Int32 endColumn, Double minHeight, Double maxHeight)
{
_rows.ForEach(r => r.AdjustToContents(startColumn, endColumn, minHeight, maxHeight));
return this;
}
public void Hide()
{
_rows.ForEach(r => r.Hide());
}
public void Unhide()
{
_rows.ForEach(r => r.Unhide());
}
public void Group()
{
Group(false);
}
public void Group(Int32 outlineLevel)
{
Group(outlineLevel, false);
}
public void Ungroup()
{
Ungroup(false);
}
public void Group(Boolean collapse)
{
_rows.ForEach(r => r.Group(collapse));
}
public void Group(Int32 outlineLevel, Boolean collapse)
{
_rows.ForEach(r => r.Group(outlineLevel, collapse));
}
public void Ungroup(Boolean ungroupFromAll)
{
_rows.ForEach(r => r.Ungroup(ungroupFromAll));
}
public void Collapse()
{
_rows.ForEach(r => r.Collapse());
}
public void Expand()
{
_rows.ForEach(r => r.Expand());
}
public IXLCells Cells()
{
var cells = new XLCells(false, false);
foreach (XLRow container in _rows)
cells.Add(container.RangeAddress);
return cells;
}
public IXLCells CellsUsed()
{
var cells = new XLCells(true, false);
foreach (XLRow container in _rows)
cells.Add(container.RangeAddress);
return cells;
}
public IXLCells CellsUsed(Boolean includeFormats)
{
var cells = new XLCells(true, includeFormats);
foreach (XLRow container in _rows)
cells.Add(container.RangeAddress);
return cells;
}
public IXLRows AddHorizontalPageBreaks()
{
foreach (XLRow row in _rows)
row.Worksheet.PageSetup.AddHorizontalPageBreak(row.RowNumber());
return this;
}
public IXLRows SetDataType(XLDataType dataType)
{
_rows.ForEach(c => c.DataType = dataType);
return this;
}
#endregion
#region IXLStylized Members
public IEnumerable<IXLStyle> Styles
{
get
{
UpdatingStyle = true;
yield return style;
if (_worksheet != null)
yield return _worksheet.Style;
else
{
foreach (IXLStyle s in _rows.SelectMany(row => row.Styles))
{
yield return s;
}
}
UpdatingStyle = false;
}
}
public Boolean UpdatingStyle { get; set; }
public IXLStyle InnerStyle
{
get { return style; }
set { style = new XLStyle(this, value); }
}
public IXLRanges RangesUsed
{
get
{
var retVal = new XLRanges();
this.ForEach(c => retVal.Add(c.AsRange()));
return retVal;
}
}
#endregion
public void Add(XLRow row)
{
_rows.Add(row);
}
public IXLRows Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats)
{
_rows.ForEach(c => c.Clear(clearOptions));
return this;
}
public void Dispose()
{
if (_rows != null)
_rows.ForEach(r => r.Dispose());
}
public void Select()
{
foreach (var range in this)
range.Select();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Components.Server
{
public class CircuitDisconnectMiddlewareTest
{
[Theory]
[InlineData("GET")]
[InlineData("PUT")]
[InlineData("DELETE")]
[InlineData("HEAD")]
public async Task DisconnectMiddleware_OnlyAccepts_PostRequests(string httpMethod)
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
var context = new DefaultHttpContext();
context.Request.Method = httpMethod;
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status405MethodNotAllowed, context.Response.StatusCode);
}
[Theory]
[InlineData(null)]
[InlineData("application/json")]
public async Task Returns400BadRequest_ForInvalidContentTypes(string contentType)
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
var context = new DefaultHttpContext();
context.Request.Method = HttpMethods.Post;
context.Request.ContentType = contentType;
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
}
[Fact]
public async Task Returns400BadRequest_IfNoCircuitIdOnForm()
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
var context = new DefaultHttpContext();
context.Request.Method = HttpMethods.Post;
context.Request.ContentType = "application/x-www-form-urlencoded";
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
}
[Fact]
public async Task Returns400BadRequest_InvalidCircuitId()
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
using var memory = new MemoryStream();
await new FormUrlEncodedContent(new Dictionary<string, string> { ["circuitId"] = "1234" }).CopyToAsync(memory);
memory.Seek(0, SeekOrigin.Begin);
var context = new DefaultHttpContext();
context.Request.Method = HttpMethods.Post;
context.Request.ContentType = "application/x-www-form-urlencoded";
context.Request.Body = memory;
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
}
[Fact]
public async Task Returns200OK_NonExistingCircuit()
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var circuitId = circuitIdFactory.CreateCircuitId();
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
using var memory = new MemoryStream();
await new FormUrlEncodedContent(new Dictionary<string, string> { ["circuitId"] = circuitId.Secret, }).CopyToAsync(memory);
memory.Seek(0, SeekOrigin.Begin);
var context = new DefaultHttpContext();
context.Request.Method = HttpMethods.Post;
context.Request.ContentType = "application/x-www-form-urlencoded";
context.Request.Body = memory;
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
}
[Fact]
public async Task GracefullyTerminates_ConnectedCircuit()
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var circuitId = circuitIdFactory.CreateCircuitId();
var testCircuitHost = TestCircuitHost.Create(circuitId);
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
registry.Register(testCircuitHost);
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
using var memory = new MemoryStream();
await new FormUrlEncodedContent(new Dictionary<string, string> { ["circuitId"] = circuitId.Secret, }).CopyToAsync(memory);
memory.Seek(0, SeekOrigin.Begin);
var context = new DefaultHttpContext();
context.Request.Method = HttpMethods.Post;
context.Request.ContentType = "application/x-www-form-urlencoded";
context.Request.Body = memory;
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
}
[Fact]
public async Task GracefullyTerminates_DisconnectedCircuit()
{
// Arrange
var circuitIdFactory = TestCircuitIdFactory.CreateTestFactory();
var circuitId = circuitIdFactory.CreateCircuitId();
var circuitHost = TestCircuitHost.Create(circuitId);
var registry = new CircuitRegistry(
Options.Create(new CircuitOptions()),
NullLogger<CircuitRegistry>.Instance,
circuitIdFactory);
registry.Register(circuitHost);
await registry.DisconnectAsync(circuitHost, "1234");
var middleware = new CircuitDisconnectMiddleware(
NullLogger<CircuitDisconnectMiddleware>.Instance,
registry,
circuitIdFactory,
(ctx) => Task.CompletedTask);
using var memory = new MemoryStream();
await new FormUrlEncodedContent(new Dictionary<string, string> { ["circuitId"] = circuitId.Secret }).CopyToAsync(memory);
memory.Seek(0, SeekOrigin.Begin);
var context = new DefaultHttpContext();
context.Request.Method = HttpMethods.Post;
context.Request.ContentType = "application/x-www-form-urlencoded";
context.Request.Body = memory;
// Act
await middleware.Invoke(context);
// Assert
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Cursor used to aide in near finger interactions.
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/FingerCursor")]
public class FingerCursor : BaseCursor
{
[Header("Ring Motion")]
[SerializeField]
[Tooltip("Should the cursor react to near grabbables.")]
private bool checkForGrabbables = false;
[SerializeField]
[Tooltip("Positional offset from the finger's skin surface.")]
private float skinSurfaceOffset = 0.01f;
[SerializeField]
[Tooltip("At what distance should the cursor align with the surface. (Should be < alignWithFingerDistance)")]
private float alignWithSurfaceDistance = 0.1f;
[Header("Ring Visualization")]
[SerializeField]
[Tooltip("Renderer representing the ring attached to the index finger using an MRTK/Standard material with the round corner feature enabled.")]
protected Renderer indexFingerRingRenderer;
private MaterialPropertyBlock materialPropertyBlock;
private int proximityDistanceID;
private readonly Quaternion fingerPadRotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);
private const float MinVisibleRingDistance = 0.1f;
protected virtual void Awake()
{
materialPropertyBlock = new MaterialPropertyBlock();
proximityDistanceID = Shader.PropertyToID("_Proximity_Distance_");
}
/// <summary>
/// Override base behavior to align the cursor with the finger, else perform normal cursor transformations.
/// </summary>
protected override void UpdateCursorTransform()
{
IMixedRealityNearPointer nearPointer = (IMixedRealityNearPointer)Pointer;
// When the pointer has a IMixedRealityNearPointer interface we don't call base.UpdateCursorTransform because we handle
// cursor transformation a bit differently.
if (nearPointer != null)
{
float deltaTime = UseUnscaledTime
? Time.unscaledDeltaTime
: Time.deltaTime;
Vector3 indexFingerPosition;
Quaternion indexFingerRotation;
if (!TryGetJoint(TrackedHandJoint.IndexTip, out indexFingerPosition, out indexFingerRotation))
{
indexFingerPosition = transform.position;
indexFingerRotation = transform.rotation;
}
Vector3 indexKnucklePosition;
if (!TryGetJoint(TrackedHandJoint.IndexKnuckle, out indexKnucklePosition, out _)) // knuckle rotation not used
{
indexKnucklePosition = transform.position;
}
float distance = float.MaxValue;
Vector3 surfaceNormal = Vector3.zero;
bool surfaceNormalFound = false;
bool showVisual = true;
bool nearPokeable = nearPointer.IsNearObject;
// Show the cursor if we are deemed to be near an object or if it is near a grabbable object
if (nearPokeable)
{
// If the pointer is near an object translate the primary ring to the index finger tip and rotate to surface normal if close.
// The secondary ring should be hidden.
if (!nearPointer.TryGetDistanceToNearestSurface(out distance))
{
distance = float.MaxValue;
}
surfaceNormalFound = nearPointer.TryGetNormalToNearestSurface(out surfaceNormal);
}
else
{
// If the pointer is near a grabbable object position and rotate the ring to the default,
// else hide it.
bool nearGrabbable = checkForGrabbables && IsNearGrabbableObject();
// There is no good way to get the distance of the nearest grabbable object at the moment, so we either return the MinVisibleRingDistance or 1 (invisible).
distance = nearGrabbable ? MinVisibleRingDistance : 1.0f;
// Only show the visual if we are near a grabbable
showVisual = nearGrabbable;
surfaceNormalFound = false;
}
if (indexFingerRingRenderer != null)
{
TranslateToFinger(indexFingerRingRenderer.transform, deltaTime, indexFingerPosition, indexKnucklePosition);
if ((distance < alignWithSurfaceDistance) && surfaceNormalFound)
{
RotateToSurfaceNormal(indexFingerRingRenderer.transform, surfaceNormal, indexFingerRotation, distance);
TranslateFromTipToPad(indexFingerRingRenderer.transform, indexFingerPosition, indexKnucklePosition, surfaceNormal, distance);
}
else
{
RotateToFinger(indexFingerRingRenderer.transform, deltaTime, indexFingerRotation);
}
UpdateVisuals(indexFingerRingRenderer, distance, showVisual);
}
}
else
{
base.UpdateCursorTransform();
}
}
/// <summary>
/// Applies material overrides to a ring renderer.
/// </summary>
/// <param name="ringRenderer">Renderer using an MRTK/Standard material with the round corner feature enabled.</param>
/// <param name="distance">Distance between the ring and surface.</param>
/// <param name="visible">Should the ring be visible?</param>
protected virtual void UpdateVisuals(Renderer ringRenderer, float distance, bool visible)
{
ringRenderer.GetPropertyBlock(materialPropertyBlock);
materialPropertyBlock.SetFloat(proximityDistanceID, visible ? distance : 1.0f);
ringRenderer.SetPropertyBlock(materialPropertyBlock);
}
/// <summary>
/// Gets if the associated sphere pointer on this controller is near any grabbable objects.
/// </summary>
/// <returns>True if associated sphere pointer is near any grabbable objects, else false.</returns>
/// <param name="dist">Out parameter gets the distance to the grabbable.</param>
protected virtual bool IsNearGrabbableObject()
{
var focusProvider = CoreServices.InputSystem?.FocusProvider;
if (focusProvider != null)
{
var spherePointers = focusProvider.GetPointers<SpherePointer>();
foreach (var spherePointer in spherePointers)
{
if (spherePointer.Controller == Pointer.Controller)
{
return spherePointer.IsNearObject;
}
}
}
return false;
}
/// <summary>
/// Tries and get's hand joints based on the current pointer.
/// </summary>
/// <param name="joint">The joint type to get.</param>
/// <param name="position">Out parameter filled with joint position, otherwise
/// <see href="https://docs.unity3d.com/ScriptReference/Vector3-zero.html">Vector3.zero</see></param>
/// <param name="rotation">Out parameter filled with joint rotation, otherwise
/// <see href="https://docs.unity3d.com/ScriptReference/Quaternion-identity.html">Quaternion.identity</see></param>
protected bool TryGetJoint(TrackedHandJoint joint, out Vector3 position, out Quaternion rotation)
{
if (Pointer != null)
{
if (Pointer.Controller is IMixedRealityHand hand)
{
if (hand.TryGetJoint(joint, out MixedRealityPose handJoint))
{
position = handJoint.Position;
rotation = handJoint.Rotation;
return true;
}
}
}
position = Vector3.zero;
rotation = Quaternion.identity;
return false;
}
private void TranslateToFinger(Transform target, float deltaTime, Vector3 fingerPosition, Vector3 knucklePosition)
{
var targetPosition = fingerPosition + (fingerPosition - knucklePosition).normalized * skinSurfaceOffset;
target.position = Vector3.Lerp(target.position, targetPosition, deltaTime / PositionLerpTime);
}
private void RotateToFinger(Transform target, float deltaTime, Quaternion pointerRotation)
{
target.rotation = Quaternion.Lerp(target.rotation, pointerRotation, deltaTime / RotationLerpTime);
}
private void RotateToSurfaceNormal(Transform target, Vector3 surfaceNormal, Quaternion pointerRotation, float distance)
{
var t = distance / alignWithSurfaceDistance;
var targetRotation = Quaternion.LookRotation(-surfaceNormal);
target.rotation = Quaternion.Slerp(targetRotation, pointerRotation, t);
}
private void TranslateFromTipToPad(Transform target, Vector3 fingerPosition, Vector3 knucklePosition, Vector3 surfaceNormal, float distance)
{
var t = distance / alignWithSurfaceDistance;
Vector3 tipNormal = (fingerPosition - knucklePosition).normalized;
Vector3 tipPosition = fingerPosition + tipNormal * skinSurfaceOffset;
Vector3 tipOffset = tipPosition - fingerPosition;
// Check how perpendicular the finger normal is to the surface, so that the cursor will
// not translate to the finger pad if the user is poking with a horizontal finger
float fingerSurfaceDot = Vector3.Dot(tipNormal, -surfaceNormal);
// Lerping an angular measurement from 0 degrees (default cursor position at tip of finger) to
// 90 degrees (a new position on the fingertip pad) around the fingertip's X axis.
Quaternion degreesRelative = Quaternion.AngleAxis((1f - t) * 90f * (1f - fingerSurfaceDot), indexFingerRingRenderer.transform.right);
Vector3 tipToPadPosition = fingerPosition + degreesRelative * tipOffset;
indexFingerRingRenderer.transform.position = tipToPadPosition;
}
}
}
| |
using Signum.Utilities.Reflection;
using Signum.Engine.Linq;
using Signum.Entities.Basics;
using Signum.Engine.Basics;
using Signum.Utilities.DataStructures;
using Signum.Entities.DynamicQuery;
namespace Signum.Engine.Maps;
public class SchemaBuilder
{
Schema schema;
public SchemaSettings Settings
{
get { return schema.Settings; }
}
public SchemaBuilder(bool isDefault)
{
schema = new Schema(new SchemaSettings());
if (isDefault)
{
if (TypeEntity.AlreadySet)
throw new InvalidOperationException("Only one default SchemaBuilder per application allowed");
TypeEntity.SetTypeNameCallbacks(
t => schema.TypeToName.GetOrThrow(t, "Type {0} not found in the schema"),
cleanName => schema.NameToType.TryGetC(cleanName));
FromEnumMethodExpander.miQuery = ReflectionTools.GetMethodInfo(() => Database.Query<Entity>()).GetGenericMethodDefinition();
MListElementPropertyToken.miMListElementsLite = ReflectionTools.GetMethodInfo(() => Database.MListElementsLite<Entity, Entity>(null!, null!)).GetGenericMethodDefinition();
MListElementPropertyToken.HasAttribute = (pr, type) => this.Settings.FieldAttributes(pr)?.Any(a => a.GetType() == type) ?? false;
}
Settings.AssertNotIncluded = MixinDeclarations.AssertNotIncluded = t =>
{
if (schema.Tables.ContainsKey(t))
throw new InvalidOperationException("{0} is already included in the Schema".FormatWith(t.TypeName()));
};
}
protected SchemaBuilder(Schema schema)
{
this.schema = schema;
}
public SchemaBuilder(SchemaSettings settings)
{
schema = new Schema(settings);
}
public Schema Schema
{
get { return schema; }
}
public UniqueTableIndex AddUniqueIndex<T>(Expression<Func<T, object?>> fields, Expression<Func<T, bool>>? where = null, Expression<Func<T, object?>>? includeFields = null) where T : Entity
{
var table = Schema.Table<T>();
IColumn[] columns = IndexKeyColumns.Split(table, fields);
var index = AddUniqueIndex(table, columns);
if (where != null)
index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table);
if (includeFields != null)
{
index.IncludeColumns = IndexKeyColumns.Split(table, includeFields);
if (table.SystemVersioned != null)
{
index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray();
}
}
return index;
}
public TableIndex AddIndex<T>(Expression<Func<T, object?>> fields,
Expression<Func<T, bool>>? where = null,
Expression<Func<T, object>>? includeFields = null) where T : Entity
{
var table = Schema.Table<T>();
IColumn[] columns = IndexKeyColumns.Split(table, fields);
var index = new TableIndex(table, columns);
if (where != null)
index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table);
if (includeFields != null)
{
index.IncludeColumns = IndexKeyColumns.Split(table, includeFields);
if (table.SystemVersioned != null)
{
index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray();
}
}
AddIndex(index);
return index;
}
public UniqueTableIndex AddUniqueIndexMList<T, V>(Expression<Func<T, MList<V>>> toMList,
Expression<Func<MListElement<T, V>, object>> fields,
Expression<Func<MListElement<T, V>, bool>>? where = null,
Expression<Func<MListElement<T, V>, object>>? includeFields = null)
where T : Entity
{
TableMList table = ((FieldMList)Schema.FindField(Schema.Table(typeof(T)), Reflector.GetMemberList(toMList))).TableMList;
IColumn[] columns = IndexKeyColumns.Split(table, fields);
var index = AddUniqueIndex(table, columns);
if (where != null)
index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table);
if (includeFields != null)
{
index.IncludeColumns = IndexKeyColumns.Split(table, includeFields);
if (table.SystemVersioned != null)
{
index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray();
}
}
return index;
}
public TableIndex AddIndexMList<T, V>(Expression<Func<T, MList<V>>> toMList,
Expression<Func<MListElement<T, V>, object>> fields,
Expression<Func<MListElement<T, V>, bool>>? where = null,
Expression<Func<MListElement<T, V>, object>>? includeFields = null)
where T : Entity
{
TableMList table = ((FieldMList)Schema.FindField(Schema.Table(typeof(T)), Reflector.GetMemberList(toMList))).TableMList;
IColumn[] columns = IndexKeyColumns.Split(table, fields);
var index = AddIndex(table, columns);
if (where != null)
index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table);
if (includeFields != null)
{
index.IncludeColumns = IndexKeyColumns.Split(table, includeFields);
if (table.SystemVersioned != null)
{
index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray();
}
}
return index;
}
public UniqueTableIndex AddUniqueIndex(ITable table, Field[] fields)
{
var index = new UniqueTableIndex(table, TableIndex.GetColumnsFromFields(fields));
AddIndex(index);
return index;
}
public UniqueTableIndex AddUniqueIndex(ITable table, IColumn[] columns)
{
var index = new UniqueTableIndex(table, columns);
AddIndex(index);
return index;
}
public TableIndex AddIndex(ITable table, Field[] fields)
{
var index = new TableIndex(table, TableIndex.GetColumnsFromFields(fields));
AddIndex(index);
return index;
}
public TableIndex AddIndex(ITable table, IColumn[] columns)
{
var index = new TableIndex(table, columns);
AddIndex(index);
return index;
}
public void AddIndex(TableIndex index)
{
ITable table = index.Table;
if (table.MultiColumnIndexes == null)
table.MultiColumnIndexes = new List<TableIndex>();
table.MultiColumnIndexes.Add(index);
}
public FluentInclude<T> Include<T>() where T : Entity
{
var table = Include(typeof(T), null);
return new FluentInclude<T>(table, this);
}
public virtual Table Include(Type type)
{
return Include(type, null);
}
internal protected virtual Table Include(Type type, PropertyRoute? route)
{
if (schema.Tables.TryGetValue(type, out var result))
return result;
if (this.Schema.IsCompleted) //Below for nop includes of Views referencing lites or entities
throw new InvalidOperationException("Schema already completed");
using (HeavyProfiler.LogNoStackTrace("Include", () => type.TypeName()))
{
if (type.IsAbstract)
throw new InvalidOperationException(ErrorIncluding(route) + $"Impossible to include in the Schema the type {type} because is abstract");
if (!Reflector.IsEntity(type))
throw new InvalidOperationException(ErrorIncluding(route) + $"Impossible to include in the Schema the type {type} because is not and Entity");
string cleanName = schema.Settings.desambiguatedNames?.TryGetC(type) ?? Reflector.CleanTypeName(EnumEntity.Extract(type) ?? type);
if (schema.NameToType.ContainsKey(cleanName))
throw new InvalidOperationException(ErrorIncluding(route) + @$"Two types have the same cleanName '{cleanName}', desambiguate using Schema.Current.Settings.Desambiguate method:
{schema.NameToType[cleanName].FullName}
{type.FullName}");
try
{
result = new Table(type);
schema.Tables.Add(type, result);
schema.NameToType[cleanName] = type;
schema.TypeToName[type] = cleanName;
Complete(result);
return result;
}
catch (Exception) //Avoid half-cooked tables
{
schema.Tables.Remove(type);
schema.NameToType.Remove(cleanName);
schema.TypeToName.Remove(type);
throw;
}
}
}
private static string? ErrorIncluding(PropertyRoute? route)
{
return route?.Let(r => $"Error including {r}: ");
}
void Complete(Table table)
{
using (HeavyProfiler.LogNoStackTrace("Complete", () => table.Type.Name))
using (var tr = HeavyProfiler.LogNoStackTrace("GetPrimaryKeyAttribute", () => table.Type.Name))
{
Type type = table.Type;
table.IdentityBehaviour = GetPrimaryKeyAttribute(type).IdentityBehaviour;
tr.Switch("GenerateTableName");
table.Name = GenerateTableName(type, Settings.TypeAttribute<TableNameAttribute>(type));
tr.Switch("GenerateCleanTypeName");
table.CleanTypeName = GenerateCleanTypeName(type);
tr.Switch("GenerateFields");
table.Fields = GenerateFields(PropertyRoute.Root(type), table, NameSequence.Void, forceNull: false, inMList: false);
tr.Switch("GenerateMixins");
table.Mixins = GenerateMixins(PropertyRoute.Root(type), table, NameSequence.Void);
tr.Switch("GenerateTemporal");
table.SystemVersioned = ToSystemVersionedInfo(Settings.TypeAttribute<SystemVersionedAttribute>(type), table.Name);
tr.Switch("GenerateColumns");
table.GenerateColumns();
}
}
public SystemVersionedInfo? ToSystemVersionedInfo(SystemVersionedAttribute? att, ObjectName tableName)
{
if (att == null)
return null;
var isPostgres = this.schema.Settings.IsPostgres;
var tn = att.TemporalTableName != null ? ObjectName.Parse(att.TemporalTableName, isPostgres) :
new ObjectName(tableName.Schema, tableName.Name + "_History", isPostgres);
if (isPostgres)
return new SystemVersionedInfo(tn, att.PostgreeSysPeriodColumname);
return new SystemVersionedInfo(tn, att.StartDateColumnName, att.EndDateColumnName);
}
private Dictionary<Type, FieldMixin>? GenerateMixins(PropertyRoute propertyRoute, ITable table, NameSequence nameSequence)
{
Dictionary<Type, FieldMixin>? mixins = null;
foreach (var t in MixinDeclarations.GetMixinDeclarations(propertyRoute.Type))
{
if (mixins == null)
mixins = new Dictionary<Type, FieldMixin>();
mixins.Add(t, this.GenerateFieldMixin(propertyRoute.Add(t), nameSequence, table));
}
return mixins;
}
public HeavyProfiler.Tracer? Tracer { get; set; }
public HashSet<(Type type, string method)> LoadedModules = new HashSet<(Type type, string method)>();
public bool NotDefined(MethodBase? methodBase)
{
this.Tracer.Switch(methodBase!.DeclaringType!.Name);
var methods = methodBase.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => !m.HasAttribute<MethodExpanderAttribute>())
.Select(m => m.GetCustomAttribute<ExpressionFieldAttribute>()?.Name)
.NotNull()
.ToHashSet();
var fields = methodBase.DeclaringType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Where(f => f.Name.EndsWith("Expression") && f.FieldType.IsInstantiationOf(typeof(Expression<>)));
foreach (var f in fields)
{
if (!methods.Contains(f.Name))
throw new InvalidOperationException($"No Method found for expression '{f.Name}' in '{methodBase.DeclaringType.Name}'");
}
return LoadedModules.Add((type: methodBase.DeclaringType, method: methodBase.Name));
}
public void AssertDefined(MethodBase methodBase)
{
var tulpe = (methodBase.DeclaringType!, methodBase.Name);
if (!LoadedModules.Contains(tulpe))
throw new ApplicationException("Call {0} first".FormatWith(tulpe));
}
#region Field Generator
protected Dictionary<string, EntityField> GenerateFields(PropertyRoute root, ITable table, NameSequence preName, bool forceNull, bool inMList)
{
using (HeavyProfiler.LogNoStackTrace("SB.GenerateFields", () => root.ToString()))
{
Dictionary<string, EntityField> result = new Dictionary<string, EntityField>();
var type = root.Type;
if (type.IsEntity())
{
{
PropertyRoute route = root.Add(fiId);
Field field = GenerateField(table, route, preName, forceNull, inMList);
result.Add(fiId.Name, new EntityField(type, fiId, field));
}
TicksColumnAttribute? t = type.GetCustomAttribute<TicksColumnAttribute>();
if (t == null || t.HasTicks)
{
PropertyRoute route = root.Add(fiTicks);
Field field = GenerateField(table, route, preName, forceNull, inMList);
result.Add(fiTicks.Name, new EntityField(type, fiTicks, field));
}
Expression? exp = ExpressionCleaner.GetFieldExpansion(type, EntityExpression.ToStringMethod);
if (exp == null)
{
PropertyRoute route = root.Add(fiToStr);
Field field = GenerateField(table, route, preName, forceNull, inMList);
if (result.ContainsKey(fiToStr.Name))
throw new InvalidOperationException("Duplicated field with name {0} on {1}, shadowing not supported".FormatWith(fiToStr.Name, type.TypeName()));
result.Add(fiToStr.Name, new EntityField(type, fiToStr, field));
}
}
foreach (FieldInfo fi in Reflector.InstanceFieldsInOrder(type))
{
PropertyRoute route = root.Add(fi);
if (Settings.FieldAttribute<IgnoreAttribute>(route) == null)
{
if (Reflector.TryFindPropertyInfo(fi) == null && !fi.IsPublic && !fi.HasAttribute<FieldWithoutPropertyAttribute>())
throw new InvalidOperationException("Field '{0}' of type '{1}' has no property".FormatWith(fi.Name, type.Name));
Field field = GenerateField(table, route, preName, forceNull, inMList);
if (result.ContainsKey(fi.Name))
throw new InvalidOperationException("Duplicated field with name '{0}' on '{1}', shadowing not supported".FormatWith(fi.Name, type.TypeName()));
var ef = new EntityField(type, fi, field);
if (field is FieldMList fml)
fml.TableMList.PropertyRoute = route;
result.Add(fi.Name, ef);
}
}
return result;
}
}
static readonly FieldInfo fiToStr = ReflectionTools.GetFieldInfo((Entity o) => o.toStr);
static readonly FieldInfo fiTicks = ReflectionTools.GetFieldInfo((Entity o) => o.ticks);
static readonly FieldInfo fiId = ReflectionTools.GetFieldInfo((Entity o) => o.id);
protected virtual Field GenerateField(ITable table, PropertyRoute route, NameSequence preName, bool forceNull, bool inMList)
{
using (HeavyProfiler.LogNoStackTrace("GenerateField", () => route.ToString()))
{
KindOfField kof = GetKindOfField(route);
if (kof == KindOfField.MList && inMList)
throw new InvalidOperationException("Field {0} of type {1} can not be nested in another MList".FormatWith(route, route.Type.TypeName(), kof));
//field name generation
NameSequence name;
ColumnNameAttribute? vc = Settings.FieldAttribute<ColumnNameAttribute>(route);
if (vc != null && vc.Name.HasText())
name = NameSequence.Void.Add(vc.Name);
else if (route.PropertyRouteType != PropertyRouteType.MListItems)
name = preName.Add(GenerateFieldName(route, kof));
else if (kof == KindOfField.Enum || kof == KindOfField.Reference)
name = preName.Add(GenerateMListFieldName(route, kof));
else
name = preName;
switch (kof)
{
case KindOfField.PrimaryKey:
return GenerateFieldPrimaryKey((Table)table, route, name);
case KindOfField.Ticks:
return GenerateFieldTicks((Table)table, route, name);
case KindOfField.Value:
return GenerateFieldValue(table, route, name, forceNull);
case KindOfField.Reference:
{
Implementations at = Settings.GetImplementations(route);
if (at.IsByAll)
return GenerateFieldImplementedByAll(route, table, name, forceNull);
else if (at.Types.Only() == route.Type.CleanType())
return GenerateFieldReference(table, route, name, forceNull);
else
return GenerateFieldImplementedBy(table, route, name, forceNull, at.Types);
}
case KindOfField.Enum:
return GenerateFieldEnum(table, route, name, forceNull);
case KindOfField.Embedded:
return GenerateFieldEmbedded(table, route, name, forceNull, inMList);
case KindOfField.MList:
return GenerateFieldMList((Table)table, route, name);
default:
throw new NotSupportedException(EngineMessage.NoWayOfMappingType0Found.NiceToString().FormatWith(route.Type));
}
}
}
public enum KindOfField
{
PrimaryKey,
Ticks,
Value,
Reference,
Enum,
Embedded,
MList,
}
protected virtual KindOfField GetKindOfField(PropertyRoute route)
{
if (route.FieldInfo != null && ReflectionTools.FieldEquals(route.FieldInfo, fiId))
return KindOfField.PrimaryKey;
if (route.FieldInfo != null && ReflectionTools.FieldEquals(route.FieldInfo, fiTicks))
return KindOfField.Ticks;
if (Settings.TryGetSqlDbType(Settings.FieldAttribute<DbTypeAttribute>(route), route.Type) != null)
return KindOfField.Value;
if (route.Type.UnNullify().IsEnum)
return KindOfField.Enum;
if (Reflector.IsIEntity(Lite.Extract(route.Type) ?? route.Type))
return KindOfField.Reference;
if (Reflector.IsEmbeddedEntity(route.Type))
return KindOfField.Embedded;
if (Reflector.IsMList(route.Type))
return KindOfField.MList;
if (Settings.IsPostgres && route.Type.IsArray)
{
if (Settings.TryGetSqlDbType(Settings.FieldAttribute<DbTypeAttribute>(route), route.Type.ElementType()!) != null)
return KindOfField.Value;
}
throw new InvalidOperationException($"Field {route} of type {route.Type.Name} has no database representation");
}
protected virtual Field GenerateFieldPrimaryKey(Table table, PropertyRoute route, NameSequence name)
{
var attr = GetPrimaryKeyAttribute(table.Type);
PrimaryKey.PrimaryKeyType.Add(table.Type, attr.Type);
DbTypePair pair = Settings.GetSqlDbType(attr, attr.Type);
return table.PrimaryKey = new FieldPrimaryKey(route, table, attr.Name, attr.Type)
{
DbType = pair.DbType,
Collation = Settings.GetCollate(attr),
UserDefinedTypeName = pair.UserDefinedTypeName,
Default = attr.GetDefault(Settings.IsPostgres),
Identity = attr.Identity,
Size = attr.HasSize ? attr.Size : (int?)null,
};
}
private PrimaryKeyAttribute GetPrimaryKeyAttribute(Type type)
{
var attr = Settings.TypeAttribute<PrimaryKeyAttribute>(type);
if (attr != null)
return attr;
if (type.IsEnumEntity())
return new PrimaryKeyAttribute(Enum.GetUnderlyingType(type.GetGenericArguments().Single())) { Identity = false, IdentityBehaviour = false };
return Settings.DefaultPrimaryKeyAttribute;
}
protected virtual FieldValue GenerateFieldTicks(Table table, PropertyRoute route, NameSequence name)
{
var ticksAttr = Settings.TypeAttribute<TicksColumnAttribute>(table.Type);
if (ticksAttr != null && !ticksAttr.HasTicks)
throw new InvalidOperationException("HastTicks is false");
Type type = ticksAttr?.Type ?? route.Type;
DbTypePair pair = Settings.GetSqlDbType(ticksAttr, type);
string ticksName = ticksAttr?.Name ?? name.ToString();
return table.Ticks = new FieldTicks(route, type, ticksName)
{
DbType = pair.DbType,
Collation = Settings.GetCollate(ticksAttr),
UserDefinedTypeName = pair.UserDefinedTypeName,
Nullable = IsNullable.No,
Size = Settings.GetSqlSize(ticksAttr, null, pair.DbType),
Precision = Settings.GetSqlPrecision(ticksAttr, null, pair.DbType),
Scale = Settings.GetSqlScale(ticksAttr, null, pair.DbType),
Default = ticksAttr?.GetDefault(Settings.IsPostgres),
};
}
protected virtual FieldValue GenerateFieldValue(ITable table, PropertyRoute route, NameSequence name, bool forceNull)
{
var att = Settings.FieldAttribute<DbTypeAttribute>(route);
DbTypePair pair = Settings.IsPostgres && route.Type.IsArray && route.Type != typeof(byte[]) ?
Settings.GetSqlDbType(att, route.Type.ElementType()!) :
Settings.GetSqlDbType(att, route.Type);
return new FieldValue(route, null, name.ToString())
{
DbType = pair.DbType,
Collation = Settings.GetCollate(att),
UserDefinedTypeName = pair.UserDefinedTypeName,
Nullable = Settings.GetIsNullable(route, forceNull),
Size = Settings.GetSqlSize(att, route, pair.DbType),
Precision = Settings.GetSqlPrecision(att, route, pair.DbType),
Scale = Settings.GetSqlScale(att, route, pair.DbType),
Default = att?.GetDefault(Settings.IsPostgres),
}.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route)));
}
protected virtual FieldEnum GenerateFieldEnum(ITable table, PropertyRoute route, NameSequence name, bool forceNull)
{
var att = Settings.FieldAttribute<DbTypeAttribute>(route);
Type cleanEnum = route.Type.UnNullify();
var referenceTable = Include(EnumEntity.Generate(cleanEnum), route);
return new FieldEnum(route, name.ToString(), referenceTable)
{
Nullable = Settings.GetIsNullable(route, forceNull),
IsLite = false,
AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null,
Default = att?.GetDefault(Settings.IsPostgres),
}.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route)));
}
protected virtual FieldReference GenerateFieldReference(ITable table, PropertyRoute route, NameSequence name, bool forceNull)
{
var referenceTable = Include(Lite.Extract(route.Type) ?? route.Type, route);
var nullable = Settings.GetIsNullable(route, forceNull);
return new FieldReference(route, null, name.ToString(), referenceTable)
{
Nullable = nullable,
IsLite = route.Type.IsLite(),
AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null,
AvoidExpandOnRetrieving = Settings.FieldAttribute<AvoidExpandQueryAttribute>(route) != null,
Default = Settings.FieldAttribute<DbTypeAttribute>(route)?.GetDefault(Settings.IsPostgres)
}.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route)));
}
protected virtual FieldImplementedBy GenerateFieldImplementedBy(ITable table, PropertyRoute route, NameSequence name, bool forceNull, IEnumerable<Type> types)
{
Type cleanType = Lite.Extract(route.Type) ?? route.Type;
string errors = types.Where(t => !cleanType.IsAssignableFrom(t)).ToString(t => t.TypeName(), ", ");
if (errors.Length != 0)
throw new InvalidOperationException("Type {0} do not implement {1}".FormatWith(errors, cleanType));
var nullable = Settings.GetIsNullable(route, forceNull);
if (types.Count() > 1 && nullable == IsNullable.No)
nullable = IsNullable.Forced;
CombineStrategy strategy = Settings.FieldAttribute<CombineStrategyAttribute>(route)?.Strategy ?? CombineStrategy.Case;
bool avoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null;
var implementations = types.ToDictionary<Type, Type, ImplementationColumn>(t => t, t =>
{
var rt = Include(t, route);
string impName = name.Add(TypeLogic.GetCleanName(t)).ToString();
return new ImplementationColumn(impName, referenceTable: rt)
{
Nullable = nullable,
AvoidForeignKey = avoidForeignKey,
};
});
return new FieldImplementedBy(route, implementations)
{
SplitStrategy = strategy,
IsLite = route.Type.IsLite(),
AvoidExpandOnRetrieving = Settings.FieldAttribute<AvoidExpandQueryAttribute>(route) != null
}.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route)));
}
protected virtual FieldImplementedByAll GenerateFieldImplementedByAll(PropertyRoute route, ITable table, NameSequence preName, bool forceNull)
{
var nullable = Settings.GetIsNullable(route, forceNull);
var column = new ImplementationStringColumn(preName.ToString())
{
Nullable = nullable,
Size = Settings.DefaultImplementedBySize,
};
var columnType = new ImplementationColumn(preName.Add("Type").ToString(), Include(typeof(TypeEntity), route))
{
Nullable = nullable,
AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null,
};
return new FieldImplementedByAll(route, column, columnType)
{
IsLite = route.Type.IsLite(),
AvoidExpandOnRetrieving = Settings.FieldAttribute<AvoidExpandQueryAttribute>(route) != null
}.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route)));
}
protected virtual FieldMList GenerateFieldMList(Table table, PropertyRoute route, NameSequence name)
{
Type elementType = route.Type.ElementType()!;
if (table.Ticks == null)
throw new InvalidOperationException("Type '{0}' has field '{1}' but does not Ticks. MList requires concurrency control.".FormatWith(route.Parent!.Type.TypeName(), route.FieldInfo!.FieldName()));
var orderAttr = Settings.FieldAttribute<PreserveOrderAttribute>(route);
FieldValue? order = null;
if (orderAttr != null)
{
var pair = Settings.GetSqlDbTypePair(typeof(int));
order = new FieldValue(route: null!, fieldType: typeof(int), orderAttr.Name ?? "Order")
{
DbType = pair.DbType,
Collation = Settings.GetCollate(orderAttr),
UserDefinedTypeName = pair.UserDefinedTypeName,
Nullable = IsNullable.No,
Size = Settings.GetSqlSize(orderAttr, null, pair.DbType),
Precision = Settings.GetSqlPrecision(orderAttr, null, pair.DbType),
Scale = Settings.GetSqlScale(orderAttr, null, pair.DbType),
};
}
var keyAttr = Settings.FieldAttribute<PrimaryKeyAttribute>(route) ?? Settings.DefaultPrimaryKeyAttribute;
TableMList.PrimaryKeyColumn primaryKey;
{
PrimaryKey.MListPrimaryKeyType.Add(route, keyAttr.Type);
var pair = Settings.GetSqlDbType(keyAttr, keyAttr.Type);
primaryKey = new TableMList.PrimaryKeyColumn(keyAttr.Type, keyAttr.Name)
{
DbType = pair.DbType,
Collation = Settings.GetCollate(orderAttr),
UserDefinedTypeName = pair.UserDefinedTypeName,
Default = keyAttr.GetDefault(Settings.IsPostgres),
Identity = keyAttr.Identity,
};
}
var tableName = GenerateTableNameCollection(table, name, Settings.FieldAttribute<TableNameAttribute>(route));
var backReference = new FieldReference(route: null!, fieldType: table.Type,
name: GenerateBackReferenceName(table.Type, Settings.FieldAttribute<BackReferenceColumnNameAttribute>(route)),
referenceTable: table
)
{
AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null,
};
TableMList mlistTable = new TableMList(route.Type, tableName, primaryKey, backReference)
{
Order = order,
};
mlistTable.Field = GenerateField(mlistTable, route.Add("Item"), NameSequence.Void, forceNull: false, inMList: true);
var sysAttribute = Settings.FieldAttribute<SystemVersionedAttribute>(route) ??
(Settings.TypeAttribute<SystemVersionedAttribute>(table.Type) != null ? new SystemVersionedAttribute() : null);
mlistTable.SystemVersioned = ToSystemVersionedInfo(sysAttribute, mlistTable.Name);
mlistTable.GenerateColumns();
return new FieldMList(route, mlistTable)
{
TableMList = mlistTable,
};
}
protected virtual FieldEmbedded GenerateFieldEmbedded(ITable table, PropertyRoute route, NameSequence name, bool forceNull, bool inMList)
{
var nullable = Settings.GetIsNullable(route, false);
var hasValue = nullable.ToBool() ? new FieldEmbedded.EmbeddedHasValueColumn(name.Add("HasValue").ToString()) : null;
var embeddedFields = GenerateFields(route, table, name, forceNull: nullable.ToBool() || forceNull, inMList: inMList);
var mixins = GenerateMixins(route, table, name);
return new FieldEmbedded(route, hasValue, embeddedFields, mixins);
}
protected virtual FieldMixin GenerateFieldMixin(PropertyRoute route, NameSequence name, ITable table)
{
return new FieldMixin(route, table, GenerateFields(route, table, name, forceNull: false, inMList: false));
}
#endregion
#region Names
public virtual string GenerateCleanTypeName(Type type)
{
type = CleanType(type);
var ctn = type.GetCustomAttribute<CleanTypeNameAttribute>();
if (ctn != null)
return ctn.Name;
return Reflector.CleanTypeName(type);
}
protected static Type CleanType(Type type)
{
type = Lite.Extract(type) ?? type;
type = EnumEntity.Extract(type) ?? type;
return type;
}
public virtual ObjectName GenerateTableName(Type type, TableNameAttribute? tn)
{
var isPostgres = Schema.Settings.IsPostgres;
SchemaName sn = tn != null ? GetSchemaName(tn) : SchemaName.Default(isPostgres);
string name = tn?.Name ?? EnumEntity.Extract(type)?.Name ?? Reflector.CleanTypeName(type);
return new ObjectName(sn, name, isPostgres);
}
private SchemaName GetSchemaName(TableNameAttribute tn)
{
var isPostgres = Schema.Settings.IsPostgres;
ServerName? server = tn.ServerName == null ? null : new ServerName(tn.ServerName, isPostgres);
DatabaseName? dataBase = tn.DatabaseName == null && server == null ? null : new DatabaseName(server, tn.DatabaseName!, isPostgres);
SchemaName schema = tn.SchemaName == null && dataBase == null ? (tn.Name.StartsWith("#") && isPostgres ? null! : SchemaName.Default(isPostgres)) : new SchemaName(dataBase, tn.SchemaName!, isPostgres);
return schema;
}
public virtual ObjectName GenerateTableNameCollection(Table table, NameSequence name, TableNameAttribute? tn)
{
var isPostgres = Schema.Settings.IsPostgres;
SchemaName sn = tn != null ? GetSchemaName(tn) : SchemaName.Default(isPostgres);
return new ObjectName(sn, tn?.Name ?? (table.Name.Name + name.ToString()), isPostgres);
}
public virtual string GenerateMListFieldName(PropertyRoute route, KindOfField kindOfField)
{
Type type = Lite.Extract(route.Type) ?? route.Type;
switch (kindOfField)
{
case KindOfField.Value:
case KindOfField.Embedded:
return type.Name;
case KindOfField.Enum:
case KindOfField.Reference:
return (EnumEntity.Extract(type)?.Name ?? Reflector.CleanTypeName(type)) + "ID";
default:
throw new InvalidOperationException("No field name for type {0} defined".FormatWith(type));
}
}
public virtual string GenerateFieldName(PropertyRoute route, KindOfField kindOfField)
{
string name = route.PropertyInfo != null ? (route.PropertyInfo.Name.TryAfterLast('.') ?? route.PropertyInfo.Name)
: route.FieldInfo!.Name;
switch (kindOfField)
{
case KindOfField.PrimaryKey:
case KindOfField.Ticks:
case KindOfField.Value:
case KindOfField.Embedded:
case KindOfField.MList: //se usa solo para el nombre de la tabla
return name;
case KindOfField.Reference:
case KindOfField.Enum:
return name + "ID";
default:
throw new InvalidOperationException("No name for {0} defined".FormatWith(route.FieldInfo!.Name));
}
}
public virtual string GenerateBackReferenceName(Type type, BackReferenceColumnNameAttribute? attribute)
{
return attribute?.Name ?? "ParentID";
}
#endregion
GlobalLazyManager GlobalLazyManager = new GlobalLazyManager();
public void SwitchGlobalLazyManager(GlobalLazyManager manager)
{
GlobalLazyManager.AsserNotUsed();
GlobalLazyManager = manager;
}
public ResetLazy<T> GlobalLazy<T>(Func<T> func, InvalidateWith invalidateWith,
Action? onInvalidated = null,
LazyThreadSafetyMode mode = LazyThreadSafetyMode.ExecutionAndPublication) where T : class
{
var result = Signum.Engine.GlobalLazy.WithoutInvalidations(() =>
{
GlobalLazyManager.OnLoad(this, invalidateWith);
return func();
});
GlobalLazyManager.AttachInvalidations(this, invalidateWith, (sender, args) =>
{
result.Reset();
onInvalidated?.Invoke();
});
return result;
}
}
public class GlobalLazyManager
{
bool isUsed = false;
public void AsserNotUsed()
{
if (isUsed)
throw new InvalidOperationException("GlobalLazyManager has already been used");
}
public virtual void AttachInvalidations(SchemaBuilder sb, InvalidateWith invalidateWith, EventHandler invalidate)
{
isUsed = true;
Action onInvalidation = () =>
{
if (Transaction.InTestTransaction)
{
invalidate(this, EventArgs.Empty);
Transaction.Rolledback += dic => invalidate(this, EventArgs.Empty);
}
Transaction.PostRealCommit += dic => invalidate(this, EventArgs.Empty);
};
Schema schema = sb.Schema;
foreach (var type in invalidateWith.Types)
{
giAttachInvalidations.GetInvoker(type)(schema, onInvalidation);
}
var dependants = DirectedGraph<Table>.Generate(invalidateWith.Types.Select(t => schema.Table(t)), t => t.DependentTables().Select(kvp => kvp.Key)).Select(t => t.Type).ToHashSet();
dependants.ExceptWith(invalidateWith.Types);
foreach (var type in dependants)
{
giAttachInvalidationsDependant.GetInvoker(type)(schema, onInvalidation);
}
}
static readonly GenericInvoker<Action<Schema, Action>> giAttachInvalidationsDependant = new((s, a) => AttachInvalidationsDependant<Entity>(s, a));
static void AttachInvalidationsDependant<T>(Schema s, Action action) where T : Entity
{
var ee = s.EntityEvents<T>();
ee.Saving += e =>
{
if (!e.IsNew && e.IsGraphModified)
action();
};
ee.PreUnsafeUpdate += (u, q) => { action(); return null; };
}
static readonly GenericInvoker<Action<Schema, Action>> giAttachInvalidations = new((s, a) => AttachInvalidations<Entity>(s, a));
static void AttachInvalidations<T>(Schema s, Action action) where T : Entity
{
var ee = s.EntityEvents<T>();
ee.Saving += e =>
{
if (e.IsGraphModified)
action();
};
ee.PreUnsafeUpdate += (u, eq) => { action(); return null; };
ee.PreUnsafeDelete += (q) => { action(); return null; };
}
public virtual void OnLoad(SchemaBuilder sb, InvalidateWith invalidateWith)
{
}
}
public class ViewBuilder : SchemaBuilder
{
public ViewBuilder(Schema schema)
: base(schema)
{
}
public override Table Include(Type type)
{
return Schema.Table(type);
}
public Table NewView(Type type)
{
Table table = new Table(type)
{
Name = GenerateTableName(type, Settings.TypeAttribute<TableNameAttribute>(type)),
IsView = true
};
table.Fields = GenerateFields(PropertyRoute.Root(type), table, NameSequence.Void, forceNull: false, inMList: false);
table.GenerateColumns();
return table;
}
public override ObjectName GenerateTableName(Type type, TableNameAttribute? tn)
{
var name = base.GenerateTableName(type, tn);
return Administrator.ReplaceViewName(name);
}
protected override FieldReference GenerateFieldReference(ITable table, PropertyRoute route, NameSequence name, bool forceNull)
{
var result = base.GenerateFieldReference(table, route, name, forceNull);
if (Settings.FieldAttribute<ViewPrimaryKeyAttribute>(route) != null)
result.PrimaryKey = true;
return result;
}
protected override FieldValue GenerateFieldValue(ITable table, PropertyRoute route, NameSequence name, bool forceNull)
{
var result = base.GenerateFieldValue(table, route, name, forceNull);
if (Settings.FieldAttribute<ViewPrimaryKeyAttribute>(route) != null)
result.PrimaryKey = true;
return result;
}
protected override FieldEnum GenerateFieldEnum(ITable table, PropertyRoute route, NameSequence name, bool forceNull)
{
var att = Settings.FieldAttribute<DbTypeAttribute>(route);
Type cleanEnum = route.Type.UnNullify();
//var referenceTable = Include(EnumEntity.Generate(cleanEnum), route);
return new FieldEnum(route, name.ToString(), null! /*referenceTable*/)
{
Nullable = Settings.GetIsNullable(route, forceNull),
IsLite = false,
AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null,
Default = att?.GetDefault(Settings.IsPostgres),
}.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route)));
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Xml.XPath;
namespace System.Xml.Xsl.Runtime
{
/// <summary>
/// Iterate over all descendant content nodes according to XPath descendant axis rules.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct DescendantIterator
{
private XmlNavigatorFilter _filter;
private XPathNavigator _navCurrent, _navEnd;
private bool _hasFirst;
/// <summary>
/// Initialize the DescendantIterator (no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator input, XmlNavigatorFilter filter, bool orSelf)
{
// Save input node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
_filter = filter;
// Position navEnd to the node at which the descendant scan should terminate
if (input.NodeType == XPathNodeType.Root)
{
_navEnd = null;
}
else
{
_navEnd = XmlQueryRuntime.SyncToNavigator(_navEnd, input);
_navEnd.MoveToNonDescendant();
}
// If self node matches, then return it first
_hasFirst = (orSelf && !_filter.IsFiltered(_navCurrent));
}
/// <summary>
/// Position this iterator to the next descendant node. Return false if there are no more descendant nodes.
/// Return true if the Current property is set to the next node in the iteration.
/// </summary>
public bool MoveNext()
{
if (_hasFirst)
{
_hasFirst = false;
return true;
}
return (_filter.MoveToFollowing(_navCurrent, _navEnd));
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over all descendant content nodes according to XPath descendant axis rules. Eliminate duplicates by not
/// querying over nodes that are contained in the subtree of the previous node.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct DescendantMergeIterator
{
private XmlNavigatorFilter _filter;
private XPathNavigator _navCurrent, _navRoot, _navEnd;
private IteratorState _state;
private bool _orSelf;
private enum IteratorState
{
NoPrevious = 0,
NeedCurrent,
NeedDescendant,
}
/// <summary>
/// Initialize the DescendantIterator (merge multiple sets of descendant nodes in document order and remove duplicates).
/// </summary>
public void Create(XmlNavigatorFilter filter, bool orSelf)
{
_filter = filter;
_state = IteratorState.NoPrevious;
_orSelf = orSelf;
}
/// <summary>
/// Position this iterator to the next descendant node. Return IteratorResult.NoMoreNodes if there are no more
/// descendant nodes. Return IteratorResult.NeedInputNode if the next input node needs to be fetched.
/// Return IteratorResult.HaveCurrent if the Current property is set to the next node in the iteration.
/// </summary>
public IteratorResult MoveNext(XPathNavigator input)
{
if (_state != IteratorState.NeedDescendant)
{
if (input == null)
return IteratorResult.NoMoreNodes;
// Descendants of the input node will be duplicates if the input node is in the subtree
// of the previous root.
if (_state != IteratorState.NoPrevious && _navRoot.IsDescendant(input))
return IteratorResult.NeedInputNode;
// Save input node as current node and end of input's tree in navEnd
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
_navRoot = XmlQueryRuntime.SyncToNavigator(_navRoot, input);
_navEnd = XmlQueryRuntime.SyncToNavigator(_navEnd, input);
_navEnd.MoveToNonDescendant();
_state = IteratorState.NeedDescendant;
// If self node matches, then return it
if (_orSelf && !_filter.IsFiltered(input))
return IteratorResult.HaveCurrentNode;
}
if (_filter.MoveToFollowing(_navCurrent, _navEnd))
return IteratorResult.HaveCurrentNode;
// No more descendants, so transition to NeedCurrent state and get the next input node
_state = IteratorState.NeedCurrent;
return IteratorResult.NeedInputNode;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true or IteratorResult.HaveCurrentNode.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over matching parent node according to XPath parent axis rules.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct ParentIterator
{
private XPathNavigator _navCurrent;
private bool _haveCurrent;
/// <summary>
/// Initialize the ParentIterator.
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter)
{
// Save context node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context);
// Attempt to find a matching parent node
_haveCurrent = (_navCurrent.MoveToParent()) && (!filter.IsFiltered(_navCurrent));
}
/// <summary>
/// Return true if a matching parent node exists and set Current property. Otherwise, return false
/// (Current property is undefined).
/// </summary>
public bool MoveNext()
{
if (_haveCurrent)
{
_haveCurrent = false;
return true;
}
// Iteration is complete
return false;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over all ancestor nodes according to XPath ancestor axis rules, returning nodes in reverse
/// document order.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct AncestorIterator
{
private XmlNavigatorFilter _filter;
private XPathNavigator _navCurrent;
private bool _haveCurrent;
/// <summary>
/// Initialize the AncestorIterator.
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter, bool orSelf)
{
_filter = filter;
// Save context node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context);
// If self node matches, then next call to MoveNext() should return it
// Otherwise, MoveNext() will fetch next ancestor
_haveCurrent = (orSelf && !_filter.IsFiltered(_navCurrent));
}
/// <summary>
/// Position the iterator on the next matching ancestor node. Return true if such a node exists and
/// set Current property. Otherwise, return false (Current property is undefined).
/// </summary>
public bool MoveNext()
{
if (_haveCurrent)
{
_haveCurrent = false;
return true;
}
while (_navCurrent.MoveToParent())
{
if (!_filter.IsFiltered(_navCurrent))
return true;
}
// Iteration is complete
return false;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over all ancestor nodes according to XPath ancestor axis rules, but return the nodes in document order.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct AncestorDocOrderIterator
{
private XmlNavigatorStack _stack;
private XPathNavigator _navCurrent;
/// <summary>
/// Initialize the AncestorDocOrderIterator (return ancestor nodes in document order, no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter, bool orSelf)
{
AncestorIterator wrapped = new AncestorIterator();
wrapped.Create(context, filter, orSelf);
_stack.Reset();
// Fetch all ancestor nodes in reverse document order and push them onto the stack
while (wrapped.MoveNext())
_stack.Push(wrapped.Current.Clone());
}
/// <summary>
/// Return true if the Current property is set to the next Ancestor node in document order.
/// </summary>
public bool MoveNext()
{
if (_stack.IsEmpty)
return false;
_navCurrent = _stack.Pop();
return true;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over all following nodes according to XPath following axis rules. These rules specify that
/// descendants are not included, even though they follow the starting node in document order. For the
/// "true" following axis, see FollowingIterator.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct XPathFollowingIterator
{
private XmlNavigatorFilter _filter;
private XPathNavigator _navCurrent;
private bool _needFirst;
/// <summary>
/// Initialize the XPathFollowingIterator (no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator input, XmlNavigatorFilter filter)
{
// Save input node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
_filter = filter;
_needFirst = true;
}
/// <summary>
/// Position this iterator to the next following node. Return false if there are no more following nodes.
/// Return true if the Current property is set to the next node in the iteration.
/// </summary>
public bool MoveNext()
{
if (_needFirst)
{
if (!MoveFirst(_filter, _navCurrent))
return false;
_needFirst = false;
return true;
}
return _filter.MoveToFollowing(_navCurrent, null);
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
/// <summary>
/// Position "nav" to the matching node which follows it in document order but is not a descendant node.
/// Return false if this is no such matching node.
/// </summary>
internal static bool MoveFirst(XmlNavigatorFilter filter, XPathNavigator nav)
{
// Attributes and namespace nodes include descendants of their owner element in the set of following nodes
if (nav.NodeType == XPathNodeType.Attribute || nav.NodeType == XPathNodeType.Namespace)
{
if (!nav.MoveToParent())
{
// Floating attribute or namespace node that has no following nodes
return false;
}
if (!filter.MoveToFollowing(nav, null))
{
// No matching following nodes
return false;
}
}
else
{
// XPath spec doesn't include descendants of the input node in the following axis
if (!nav.MoveToNonDescendant())
// No following nodes
return false;
// If the sibling does not match the node-test, find the next following node that does
if (filter.IsFiltered(nav))
{
if (!filter.MoveToFollowing(nav, null))
{
// No matching following nodes
return false;
}
}
}
// Success
return true;
}
}
/// <summary>
/// Iterate over all following nodes according to XPath following axis rules. Merge multiple sets of following nodes
/// in document order and remove duplicates.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct XPathFollowingMergeIterator
{
private XmlNavigatorFilter _filter;
private IteratorState _state;
private XPathNavigator _navCurrent, _navNext;
private enum IteratorState
{
NeedCandidateCurrent = 0,
HaveCandidateCurrent,
HaveCurrentNeedNext,
HaveCurrentHaveNext,
HaveCurrentNoNext,
};
/// <summary>
/// Initialize the XPathFollowingMergeIterator (merge multiple sets of following nodes in document order and remove duplicates).
/// </summary>
public void Create(XmlNavigatorFilter filter)
{
_filter = filter;
_state = IteratorState.NeedCandidateCurrent;
}
/// <summary>
/// Position this iterator to the next following node. Prune by finding the first input node in
/// document order that has no other input nodes in its subtree. All other input nodes should be
/// discarded. Return IteratorResult.NeedInputNode if the next input node needs to be fetched
/// first. Return IteratorResult.HaveCurrent if the Current property is set to the next node in the
/// iteration.
/// </summary>
public IteratorResult MoveNext(XPathNavigator input)
{
switch (_state)
{
case IteratorState.NeedCandidateCurrent:
// If there are no more input nodes, then iteration is complete
if (input == null)
return IteratorResult.NoMoreNodes;
// Save input node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
// Still must check next input node to see if is a descendant of this one
_state = IteratorState.HaveCandidateCurrent;
return IteratorResult.NeedInputNode;
case IteratorState.HaveCandidateCurrent:
// If there are no more input nodes,
if (input == null)
{
// Then candidate node has been selected, and there are no further input nodes
_state = IteratorState.HaveCurrentNoNext;
return MoveFirst();
}
// If input node is in the subtree of the candidate node, then use the input node instead
if (_navCurrent.IsDescendant(input))
goto case IteratorState.NeedCandidateCurrent;
// Found node on which to perform following scan. Now skip past all input nodes in the same document.
_state = IteratorState.HaveCurrentNeedNext;
goto case IteratorState.HaveCurrentNeedNext;
case IteratorState.HaveCurrentNeedNext:
// If there are no more input nodes,
if (input == null)
{
// Then candidate node has been selected, and there are no further input nodes
_state = IteratorState.HaveCurrentNoNext;
return MoveFirst();
}
// Skip input node unless it's in a different document than the node on which the following scan was performed
if (_navCurrent.ComparePosition(input) != XmlNodeOrder.Unknown)
return IteratorResult.NeedInputNode;
// Next node is in a different document, so save it
_navNext = XmlQueryRuntime.SyncToNavigator(_navNext, input);
_state = IteratorState.HaveCurrentHaveNext;
return MoveFirst();
}
if (!_filter.MoveToFollowing(_navCurrent, null))
return MoveFailed();
return IteratorResult.HaveCurrentNode;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true or IteratorResult.HaveCurrentNode.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
/// <summary>
/// Called when an attempt to move to a following node failed. If a Next node exists, then make that the new
/// candidate current node. Otherwise, iteration is complete.
/// </summary>
private IteratorResult MoveFailed()
{
XPathNavigator navTemp;
Debug.Assert(_state == IteratorState.HaveCurrentHaveNext || _state == IteratorState.HaveCurrentNoNext);
if (_state == IteratorState.HaveCurrentNoNext)
{
// No more nodes, so iteration is complete
_state = IteratorState.NeedCandidateCurrent;
return IteratorResult.NoMoreNodes;
}
// Make next node the new candidate node
_state = IteratorState.HaveCandidateCurrent;
// Swap navigators in order to sometimes avoid creating clones
navTemp = _navCurrent;
_navCurrent = _navNext;
_navNext = navTemp;
return IteratorResult.NeedInputNode;
}
/// <summary>
/// Position this.navCurrent to the node which follows it in document order but is not a descendant node.
/// </summary>
private IteratorResult MoveFirst()
{
Debug.Assert(_state == IteratorState.HaveCurrentHaveNext || _state == IteratorState.HaveCurrentNoNext);
if (!XPathFollowingIterator.MoveFirst(_filter, _navCurrent))
return MoveFailed();
return IteratorResult.HaveCurrentNode;
}
}
/// <summary>
/// Iterate over all content-typed nodes which precede the starting node in document order. Return nodes
/// in reverse document order.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct PrecedingIterator
{
private XmlNavigatorStack _stack;
private XPathNavigator _navCurrent;
/// <summary>
/// Initialize the PrecedingIterator (no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter)
{
// Start at root, which is always first node in the document
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context);
_navCurrent.MoveToRoot();
_stack.Reset();
// If root node is not the ending node,
if (!_navCurrent.IsSamePosition(context))
{
// Push root onto the stack if it is not filtered
if (!filter.IsFiltered(_navCurrent))
_stack.Push(_navCurrent.Clone());
// Push all matching nodes onto stack
while (filter.MoveToFollowing(_navCurrent, context))
_stack.Push(_navCurrent.Clone());
}
}
/// <summary>
/// Return true if the Current property is set to the next Preceding node in reverse document order.
/// </summary>
public bool MoveNext()
{
if (_stack.IsEmpty)
return false;
_navCurrent = _stack.Pop();
return true;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over all preceding nodes according to XPath preceding axis rules, returning nodes in reverse
/// document order. These rules specify that ancestors are not included, even though they precede the
/// starting node in document order. For the "true" preceding axis, see PrecedingIterator.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct XPathPrecedingIterator
{
private XmlNavigatorStack _stack;
private XPathNavigator _navCurrent;
/// <summary>
/// Initialize the XPathPrecedingIterator (no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter)
{
XPathPrecedingDocOrderIterator wrapped = new XPathPrecedingDocOrderIterator();
wrapped.Create(context, filter);
_stack.Reset();
// Fetch all preceding nodes in document order and push them onto the stack
while (wrapped.MoveNext())
_stack.Push(wrapped.Current.Clone());
}
/// <summary>
/// Return true if the Current property is set to the next Preceding node in reverse document order.
/// </summary>
public bool MoveNext()
{
if (_stack.IsEmpty)
return false;
_navCurrent = _stack.Pop();
return true;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
/// <summary>
/// Iterate over all preceding nodes according to XPath preceding axis rules, returning nodes in document order.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct XPathPrecedingDocOrderIterator
{
private XmlNavigatorFilter _filter;
private XPathNavigator _navCurrent;
private XmlNavigatorStack _navStack;
/// <summary>
/// Initialize the XPathPrecedingDocOrderIterator (return preceding nodes in document order, no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator input, XmlNavigatorFilter filter)
{
// Save input node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
_filter = filter;
PushAncestors();
}
/// <summary>
/// Position this iterator to the next preceding node. Return false if there are no more preceding nodes.
/// Return true if the Current property is set to the next node in the iteration.
/// </summary>
public bool MoveNext()
{
if (!_navStack.IsEmpty)
{
while (true)
{
// Move to the next matching node that is before the top node on the stack in document order
if (_filter.MoveToFollowing(_navCurrent, _navStack.Peek()))
// Found match
return true;
// Do not include ancestor nodes as part of the preceding axis
_navCurrent.MoveTo(_navStack.Pop());
// No more preceding matches possible
if (_navStack.IsEmpty)
break;
}
}
return false;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true or
/// IteratorResult.HaveCurrentNode.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
/// <summary>
/// Push all ancestors of this.navCurrent onto a stack. The set of preceding nodes should not contain any of these
/// ancestors.
/// </summary>
private void PushAncestors()
{
_navStack.Reset();
do
{
_navStack.Push(_navCurrent.Clone());
}
while (_navCurrent.MoveToParent());
// Pop the root of the tree, since MoveToFollowing calls will never return it
_navStack.Pop();
}
}
/// <summary>
/// Iterate over all preceding nodes according to XPath preceding axis rules, except that nodes are always
/// returned in document order. Merge multiple sets of preceding nodes in document order and remove duplicates.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct XPathPrecedingMergeIterator
{
private XmlNavigatorFilter _filter;
private IteratorState _state;
private XPathNavigator _navCurrent, _navNext;
private XmlNavigatorStack _navStack;
private enum IteratorState
{
NeedCandidateCurrent = 0,
HaveCandidateCurrent,
HaveCurrentHaveNext,
HaveCurrentNoNext,
}
/// <summary>
/// Initialize the XPathPrecedingMergeIterator (merge multiple sets of preceding nodes in document order and remove duplicates).
/// </summary>
public void Create(XmlNavigatorFilter filter)
{
_filter = filter;
_state = IteratorState.NeedCandidateCurrent;
}
/// <summary>
/// Position this iterator to the next preceding node in document order. Discard all input nodes
/// that are followed by another input node in the same document. This leaves one node per document from
/// which the complete set of preceding nodes can be derived without possibility of duplicates.
/// Return IteratorResult.NeedInputNode if the next input node needs to be fetched first. Return
/// IteratorResult.HaveCurrent if the Current property is set to the next node in the iteration.
/// </summary>
public IteratorResult MoveNext(XPathNavigator input)
{
switch (_state)
{
case IteratorState.NeedCandidateCurrent:
// If there are no more input nodes, then iteration is complete
if (input == null)
return IteratorResult.NoMoreNodes;
// Save input node as current node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
// Scan for additional input nodes within the same document (since they are after navCurrent in docorder)
_state = IteratorState.HaveCandidateCurrent;
return IteratorResult.NeedInputNode;
case IteratorState.HaveCandidateCurrent:
// If there are no more input nodes,
if (input == null)
{
// Then candidate node has been selected, and there are no further input nodes
_state = IteratorState.HaveCurrentNoNext;
}
else
{
// If the input node is in the same document as the current node,
if (_navCurrent.ComparePosition(input) != XmlNodeOrder.Unknown)
{
// Then update the current node and get the next input node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input);
return IteratorResult.NeedInputNode;
}
// Save the input node as navNext
_navNext = XmlQueryRuntime.SyncToNavigator(_navNext, input);
_state = IteratorState.HaveCurrentHaveNext;
}
PushAncestors();
break;
}
if (!_navStack.IsEmpty)
{
while (true)
{
// Move to the next matching node that is before the top node on the stack in document order
if (_filter.MoveToFollowing(_navCurrent, _navStack.Peek()))
// Found match
return IteratorResult.HaveCurrentNode;
// Do not include ancestor nodes as part of the preceding axis
_navCurrent.MoveTo(_navStack.Pop());
// No more preceding matches possible
if (_navStack.IsEmpty)
break;
}
}
if (_state == IteratorState.HaveCurrentNoNext)
{
// No more nodes, so iteration is complete
_state = IteratorState.NeedCandidateCurrent;
return IteratorResult.NoMoreNodes;
}
// Make next node the current node and start trying to find input node greatest in docorder
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, _navNext);
_state = IteratorState.HaveCandidateCurrent;
return IteratorResult.HaveCurrentNode;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true or
/// IteratorResult.HaveCurrentNode.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
/// <summary>
/// Push all ancestors of this.navCurrent onto a stack. The set of preceding nodes should not contain any of these
/// ancestors.
/// </summary>
private void PushAncestors()
{
Debug.Assert(_state == IteratorState.HaveCurrentHaveNext || _state == IteratorState.HaveCurrentNoNext);
_navStack.Reset();
do
{
_navStack.Push(_navCurrent.Clone());
}
while (_navCurrent.MoveToParent());
// Pop the root of the tree, since MoveToFollowing calls will never return it
_navStack.Pop();
}
}
/// <summary>
/// Iterate over these nodes in document order (filtering out those that do not match the filter test):
/// 1. Starting node
/// 2. All content-typed nodes which follow the starting node until the ending node is reached
/// 3. Ending node
///
/// If the starting node is the same node as the ending node, iterate over the singleton node.
/// If the starting node is after the ending node, or is in a different document, iterate to the
/// end of the document.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct NodeRangeIterator
{
private XmlNavigatorFilter _filter;
private XPathNavigator _navCurrent, _navEnd;
private IteratorState _state;
private enum IteratorState
{
HaveCurrent,
NeedCurrent,
HaveCurrentNoNext,
NoNext,
}
/// <summary>
/// Initialize the NodeRangeIterator (no possibility of duplicates).
/// </summary>
public void Create(XPathNavigator start, XmlNavigatorFilter filter, XPathNavigator end)
{
// Save start node as current node and save ending node
_navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, start);
_navEnd = XmlQueryRuntime.SyncToNavigator(_navEnd, end);
_filter = filter;
if (start.IsSamePosition(end))
{
// Start is end, so only return node if it is not filtered
_state = !filter.IsFiltered(start) ? IteratorState.HaveCurrentNoNext : IteratorState.NoNext;
}
else
{
// Return nodes until end is reached
_state = !filter.IsFiltered(start) ? IteratorState.HaveCurrent : IteratorState.NeedCurrent;
}
}
/// <summary>
/// Position this iterator to the next following node. Return false if there are no more following nodes,
/// or if the end node has been reached. Return true if the Current property is set to the next node in
/// the iteration.
/// </summary>
public bool MoveNext()
{
switch (_state)
{
case IteratorState.HaveCurrent:
_state = IteratorState.NeedCurrent;
return true;
case IteratorState.NeedCurrent:
// Move to next following node which matches
if (!_filter.MoveToFollowing(_navCurrent, _navEnd))
{
// No more nodes unless ending node matches
if (_filter.IsFiltered(_navEnd))
{
_state = IteratorState.NoNext;
return false;
}
_navCurrent.MoveTo(_navEnd);
_state = IteratorState.NoNext;
}
return true;
case IteratorState.HaveCurrentNoNext:
_state = IteratorState.NoNext;
return true;
}
Debug.Assert(_state == IteratorState.NoNext, "Illegal state: " + _state);
return false;
}
/// <summary>
/// Return the current result navigator. This is only defined after MoveNext() has returned true.
/// </summary>
public XPathNavigator Current
{
get { return _navCurrent; }
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.Owin.FileSystems
{
/// <summary>
/// Looks up files using the on-disk file system
/// </summary>
public class PhysicalFileSystem : IFileSystem
{
// These are restricted file names on Windows, regardless of extension.
private static readonly Dictionary<string, string> RestrictedFileNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "con", string.Empty },
{ "prn", string.Empty },
{ "aux", string.Empty },
{ "nul", string.Empty },
{ "com1", string.Empty },
{ "com2", string.Empty },
{ "com3", string.Empty },
{ "com4", string.Empty },
{ "com5", string.Empty },
{ "com6", string.Empty },
{ "com7", string.Empty },
{ "com8", string.Empty },
{ "com9", string.Empty },
{ "lpt1", string.Empty },
{ "lpt2", string.Empty },
{ "lpt3", string.Empty },
{ "lpt4", string.Empty },
{ "lpt5", string.Empty },
{ "lpt6", string.Empty },
{ "lpt7", string.Empty },
{ "lpt8", string.Empty },
{ "lpt9", string.Empty },
{ "clock$", string.Empty },
};
/// <summary>
/// Creates a new instance of a PhysicalFileSystem at the given root directory.
/// </summary>
/// <param name="root">The root directory</param>
public PhysicalFileSystem(string root)
{
Root = GetFullRoot(root);
if (!Directory.Exists(Root))
{
throw new DirectoryNotFoundException(Root);
}
}
/// <summary>
/// The root directory for this instance.
/// </summary>
public string Root { get; private set; }
private static string GetFullRoot(string root)
{
var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var fullRoot = Path.GetFullPath(Path.Combine(applicationBase, root));
if (!fullRoot.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
// When we do matches in GetFullPath, we want to only match full directory names.
fullRoot += Path.DirectorySeparatorChar;
}
return fullRoot;
}
private string GetFullPath(string path)
{
var fullPath = Path.GetFullPath(Path.Combine(Root, path));
if (!fullPath.StartsWith(Root, StringComparison.OrdinalIgnoreCase))
{
return null;
}
return fullPath;
}
/// <summary>
/// Locate a file at the given path by directly mapping path segments to physical directories.
/// </summary>
/// <param name="subpath">A path under the root directory</param>
/// <param name="fileInfo">The discovered file, if any</param>
/// <returns>True if a file was discovered at the given path</returns>
public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
{
try
{
if (subpath.StartsWith("/", StringComparison.Ordinal))
{
subpath = subpath.Substring(1);
}
var fullPath = GetFullPath(subpath);
if (fullPath != null)
{
var info = new FileInfo(fullPath);
if (info.Exists && !IsRestricted(info))
{
fileInfo = new PhysicalFileInfo(info);
return true;
}
}
}
catch (ArgumentException)
{
}
fileInfo = null;
return false;
}
/// <summary>
/// Enumerate a directory at the given path, if any.
/// </summary>
/// <param name="subpath">A path under the root directory</param>
/// <param name="contents">The discovered directories, if any</param>
/// <returns>True if a directory was discovered at the given path</returns>
public bool TryGetDirectoryContents(string subpath, out IEnumerable<IFileInfo> contents)
{
try
{
if (subpath.StartsWith("/", StringComparison.Ordinal))
{
subpath = subpath.Substring(1);
}
var fullPath = GetFullPath(subpath);
if (fullPath != null)
{
var directoryInfo = new DirectoryInfo(fullPath);
if (!directoryInfo.Exists)
{
contents = null;
return false;
}
FileSystemInfo[] physicalInfos = directoryInfo.GetFileSystemInfos();
var virtualInfos = new IFileInfo[physicalInfos.Length];
for (int index = 0; index != physicalInfos.Length; ++index)
{
var fileInfo = physicalInfos[index] as FileInfo;
if (fileInfo != null)
{
virtualInfos[index] = new PhysicalFileInfo(fileInfo);
}
else
{
virtualInfos[index] = new PhysicalDirectoryInfo((DirectoryInfo)physicalInfos[index]);
}
}
contents = virtualInfos;
return true;
}
}
catch (ArgumentException)
{
}
catch (DirectoryNotFoundException)
{
}
catch (IOException)
{
}
contents = null;
return false;
}
private bool IsRestricted(FileInfo fileInfo)
{
string fileName = Path.GetFileNameWithoutExtension(fileInfo.Name);
return RestrictedFileNames.ContainsKey(fileName);
}
private class PhysicalFileInfo : IFileInfo
{
private readonly FileInfo _info;
public PhysicalFileInfo(FileInfo info)
{
_info = info;
}
public long Length
{
get { return _info.Length; }
}
public string PhysicalPath
{
get { return _info.FullName; }
}
public string Name
{
get { return _info.Name; }
}
public DateTime LastModified
{
get { return _info.LastWriteTime; }
}
public bool IsDirectory
{
get { return false; }
}
public Stream CreateReadStream()
{
// Note: Buffer size must be greater than zero, even if the file size is zero.
return new FileStream(PhysicalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1024 * 64,
FileOptions.Asynchronous | FileOptions.SequentialScan);
}
}
private class PhysicalDirectoryInfo : IFileInfo
{
private readonly DirectoryInfo _info;
public PhysicalDirectoryInfo(DirectoryInfo info)
{
_info = info;
}
public long Length
{
get { return -1; }
}
public string PhysicalPath
{
get { return _info.FullName; }
}
public string Name
{
get { return _info.Name; }
}
public DateTime LastModified
{
get { return _info.LastWriteTime; }
}
public bool IsDirectory
{
get { return true; }
}
public Stream CreateReadStream()
{
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using sep24images.Areas.HelpPage.Models;
namespace sep24images.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using C5;
using Manos.Collections;
using Manos.Http;
namespace Manos.Routing
{
public class RouteHandler : IEnumerable<RouteHandler>
{
private IMatchOperation[] match_ops;
private List<HttpMethod> methods;
public RouteHandler()
{
SetupChildrenCollection();
}
public RouteHandler(IMatchOperation op, HttpMethod[] methods) : this(new[] {op}, methods)
{
}
public RouteHandler(IMatchOperation op, HttpMethod[] methods, IManosTarget target)
: this(new[] {op}, methods, target)
{
}
public RouteHandler(IMatchOperation op, HttpMethod method) : this(new[] {op}, new[] {method})
{
}
public RouteHandler(IMatchOperation op, HttpMethod method, IManosTarget target)
: this(new[] {op}, new[] {method}, target)
{
}
public RouteHandler(IMatchOperation[] ops, HttpMethod[] methods) : this(ops, methods, null)
{
}
public RouteHandler(IMatchOperation[] ops, HttpMethod[] methods, IManosTarget target)
{
Target = target;
match_ops = ops;
this.methods = new List<HttpMethod>(methods);
SetupChildrenCollection();
}
public bool IsImplicit { get; internal set; }
public IMatchOperation[] MatchOps
{
get { return match_ops; }
set { match_ops = value; }
}
public System.Collections.Generic.IList<HttpMethod> Methods
{
get { return methods; }
set
{
if (value == null)
methods = null;
else
methods = new List<HttpMethod>(value);
}
}
public IManosTarget Target { get; set; }
//
// TODO: These also need to be an observable collection
// so we can throw an exception if someone tries to add
// a child when we already have a Target
//
public System.Collections.Generic.IList<RouteHandler> Children { get; private set; }
public bool HasPatterns
{
get { return match_ops != null && match_ops.Length > 0; }
}
#region IEnumerable<RouteHandler> Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<RouteHandler> GetEnumerator()
{
yield return this;
foreach (RouteHandler child in Children)
{
foreach (RouteHandler subchild in child)
{
yield return subchild;
}
}
}
#endregion
private void HandleChildrenCollectionChanged(object sender, EventArgs e)
{
if (Target != null)
throw new InvalidOperationException("Can not add Children to a RouteHandler that has a Target set.");
}
private void SetupChildrenCollection()
{
var children = new ArrayList<RouteHandler>();
children.ItemInserted += HandleChildrenCollectionChanged;
children.ItemsAdded += HandleChildrenCollectionChanged;
children.ItemRemovedAt += HandleChildrenCollectionChanged;
children.ItemsRemoved += HandleChildrenCollectionChanged;
Children = children;
}
public void Add(RouteHandler child)
{
Children.Add(child);
}
public IManosTarget Find(IHttpRequest request)
{
return Find(request, 0);
}
private IManosTarget Find(IHttpRequest request, int uri_start)
{
if (!IsMethodMatch(request))
return null;
DataDictionary uri_data = null;
if (HasPatterns)
{
int end;
if (!FindPatternMatch(request.Path, uri_start, out uri_data, out end))
{
return null;
}
if (Target != null)
{
if (uri_data != null)
request.UriData.Children.Add(uri_data);
return Target;
}
uri_start = end;
}
foreach (RouteHandler handler in Children)
{
IManosTarget res = handler.Find(request, uri_start);
if (res != null)
{
if (uri_data != null)
request.UriData.Children.Add(uri_data);
return res;
}
}
return null;
}
public bool FindPatternMatch(string input, int start, out DataDictionary uri_data, out int end)
{
if (match_ops == null)
{
uri_data = null;
end = start;
return false;
}
foreach (IMatchOperation op in match_ops)
{
if (op.IsMatch(input, start, out uri_data, out end))
{
if (Children.Count() > 0 || end == input.Length)
{
return true;
}
}
}
uri_data = null;
end = start;
return false;
}
public bool IsMethodMatch(IHttpRequest request)
{
if (methods != null)
return methods.Contains(request.Method);
return true;
}
}
}
| |
//
// WindowsSecureMimeContext.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Pkix;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.X509.Store;
using RealCmsSigner = System.Security.Cryptography.Pkcs.CmsSigner;
using RealCmsRecipient = System.Security.Cryptography.Pkcs.CmsRecipient;
using RealCmsRecipientCollection = System.Security.Cryptography.Pkcs.CmsRecipientCollection;
using RealX509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags;
using MimeKit.IO;
namespace MimeKit.Cryptography {
/// <summary>
/// An S/MIME cryptography context that uses Windows' <see cref="System.Security.Cryptography.X509Certificates.X509Store"/>.
/// </summary>
/// <remarks>
/// An S/MIME cryptography context that uses Windows' <see cref="System.Security.Cryptography.X509Certificates.X509Store"/>.
/// </remarks>
public class WindowsSecureMimeContext : SecureMimeContext
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.WindowsSecureMimeContext"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="WindowsSecureMimeContext"/>.
/// </remarks>
/// <param name="location">The X.509 store location.</param>
public WindowsSecureMimeContext (StoreLocation location)
{
StoreLocation = location;
// System.Security does not support Camellia...
Disable (EncryptionAlgorithm.Camellia256);
Disable (EncryptionAlgorithm.Camellia192);
Disable (EncryptionAlgorithm.Camellia192);
// ...or CAST5...
Disable (EncryptionAlgorithm.Cast5);
// ...or IDEA...
Disable (EncryptionAlgorithm.Idea);
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.WindowsSecureMimeContext"/> class.
/// </summary>
/// <remarks>
/// Constructs an S/MIME context using the current user's X.509 store location.
/// </remarks>
public WindowsSecureMimeContext () : this (StoreLocation.CurrentUser)
{
}
/// <summary>
/// Gets the X.509 store location.
/// </summary>
/// <remarks>
/// Gets the X.509 store location.
/// </remarks>
/// <value>The store location.</value>
public StoreLocation StoreLocation {
get; private set;
}
#region implemented abstract members of SecureMimeContext
/// <summary>
/// Gets the X.509 certificate based on the selector.
/// </summary>
/// <remarks>
/// Gets the X.509 certificate based on the selector.
/// </remarks>
/// <returns>The certificate on success; otherwise <c>null</c>.</returns>
/// <param name="selector">The search criteria for the certificate.</param>
protected override Org.BouncyCastle.X509.X509Certificate GetCertificate (IX509Selector selector)
{
var storeNames = new [] { StoreName.My, StoreName.AddressBook, StoreName.TrustedPeople, StoreName.Root };
foreach (var storeName in storeNames) {
var store = new X509Store (storeName, StoreLocation);
store.Open (OpenFlags.ReadOnly);
try {
foreach (var certificate in store.Certificates) {
var cert = DotNetUtilities.FromX509Certificate (certificate);
if (selector == null || selector.Match (cert))
return cert;
}
} finally {
store.Close ();
}
}
return null;
}
/// <summary>
/// Gets the private key based on the provided selector.
/// </summary>
/// <remarks>
/// Gets the private key based on the provided selector.
/// </remarks>
/// <returns>The private key on success; otherwise <c>null</c>.</returns>
/// <param name="selector">The search criteria for the private key.</param>
protected override AsymmetricKeyParameter GetPrivateKey (IX509Selector selector)
{
var store = new X509Store (StoreName.My, StoreLocation);
store.Open (OpenFlags.ReadOnly);
try {
foreach (var certificate in store.Certificates) {
if (!certificate.HasPrivateKey)
continue;
var cert = DotNetUtilities.FromX509Certificate (certificate);
if (selector == null || selector.Match (cert)) {
var pair = DotNetUtilities.GetKeyPair (certificate.PrivateKey);
return pair.Private;
}
}
} finally {
store.Close ();
}
return null;
}
/// <summary>
/// Gets the trusted anchors.
/// </summary>
/// <remarks>
/// Gets the trusted anchors.
/// </remarks>
/// <returns>The trusted anchors.</returns>
protected override Org.BouncyCastle.Utilities.Collections.HashSet GetTrustedAnchors ()
{
var storeNames = new StoreName[] { StoreName.TrustedPeople, StoreName.Root };
var anchors = new Org.BouncyCastle.Utilities.Collections.HashSet ();
foreach (var storeName in storeNames) {
var store = new X509Store (storeName, StoreLocation);
store.Open (OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates) {
var cert = DotNetUtilities.FromX509Certificate (certificate);
anchors.Add (new TrustAnchor (cert, null));
}
store.Close ();
}
return anchors;
}
/// <summary>
/// Gets the intermediate certificates.
/// </summary>
/// <remarks>
/// Gets the intermediate certificates.
/// </remarks>
/// <returns>The intermediate certificates.</returns>
protected override IX509Store GetIntermediateCertificates ()
{
var storeNames = new [] { StoreName.My, StoreName.AddressBook, StoreName.TrustedPeople, StoreName.Root };
var intermediate = new X509CertificateStore ();
foreach (var storeName in storeNames) {
var store = new X509Store (storeName, StoreLocation);
store.Open (OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates) {
var cert = DotNetUtilities.FromX509Certificate (certificate);
intermediate.Add (cert);
}
store.Close ();
}
return intermediate;
}
/// <summary>
/// Gets the certificate revocation lists.
/// </summary>
/// <remarks>
/// Gets the certificate revocation lists.
/// </remarks>
/// <returns>The certificate revocation lists.</returns>
protected override IX509Store GetCertificateRevocationLists ()
{
// TODO: figure out how other Windows apps keep track of CRLs...
var crls = new List<X509Crl> ();
return X509StoreFactory.Create ("Crl/Collection", new X509CollectionStoreParameters (crls));
}
X509Certificate2 GetCmsRecipientCertificate (MailboxAddress mailbox)
{
var store = new X509Store (StoreName.My, StoreLocation);
var secure = mailbox as SecureMailboxAddress;
var now = DateTime.Now;
store.Open (OpenFlags.ReadOnly);
try {
foreach (var certificate in store.Certificates) {
if (certificate.NotBefore > now || certificate.NotAfter < now)
continue;
var usage = certificate.Extensions[X509Extensions.KeyUsage.Id] as X509KeyUsageExtension;
if (usage != null && (usage.KeyUsages & RealX509KeyUsageFlags.KeyEncipherment) == 0)
continue;
if (secure != null) {
if (certificate.Thumbprint != secure.Fingerprint)
continue;
} else {
if (certificate.GetNameInfo (X509NameType.EmailName, false) != mailbox.Address)
continue;
}
return certificate;
}
} finally {
store.Close ();
}
throw new CertificateNotFoundException (mailbox, "A valid certificate could not be found.");
}
static EncryptionAlgorithm[] DecodeEncryptionAlgorithms (byte[] rawData)
{
using (var memory = new MemoryStream (rawData, false)) {
using (var asn1 = new Asn1InputStream (memory)) {
var algorithms = new List<EncryptionAlgorithm> ();
var sequence = asn1.ReadObject () as Asn1Sequence;
if (sequence == null)
return null;
for (int i = 0; i < sequence.Count; i++) {
var identifier = Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier.GetInstance (sequence[i]);
EncryptionAlgorithm algorithm;
if (TryGetEncryptionAlgorithm (identifier, out algorithm))
algorithms.Add (algorithm);
}
return algorithms.ToArray ();
}
}
}
/// <summary>
/// Gets the X.509 certificate associated with the <see cref="MimeKit.MailboxAddress"/>.
/// </summary>
/// <remarks>
/// Gets the X.509 certificate associated with the <see cref="MimeKit.MailboxAddress"/>.
/// </remarks>
/// <returns>The certificate.</returns>
/// <param name="mailbox">The mailbox.</param>
/// <exception cref="CertificateNotFoundException">
/// A certificate for the specified <paramref name="mailbox"/> could not be found.
/// </exception>
protected override CmsRecipient GetCmsRecipient (MailboxAddress mailbox)
{
var certificate = GetCmsRecipientCertificate (mailbox);
var cert = DotNetUtilities.FromX509Certificate (certificate);
var recipient = new CmsRecipient (cert);
foreach (var extension in certificate.Extensions) {
if (extension.Oid.Value == "1.2.840.113549.1.9.15") {
var algorithms = DecodeEncryptionAlgorithms (extension.RawData);
if (algorithms != null)
recipient.EncryptionAlgorithms = algorithms;
break;
}
}
return recipient;
}
RealCmsRecipient GetRealCmsRecipient (MailboxAddress mailbox)
{
return new RealCmsRecipient (GetCmsRecipientCertificate (mailbox));
}
RealCmsRecipientCollection GetRealCmsRecipients (IEnumerable<MailboxAddress> mailboxes)
{
var recipients = new RealCmsRecipientCollection ();
foreach (var mailbox in mailboxes)
recipients.Add (GetRealCmsRecipient (mailbox));
return recipients;
}
X509Certificate2 GetCmsSignerCertificate (MailboxAddress mailbox)
{
var store = new X509Store (StoreName.My, StoreLocation);
var secure = mailbox as SecureMailboxAddress;
var now = DateTime.Now;
store.Open (OpenFlags.ReadOnly);
try {
foreach (var certificate in store.Certificates) {
if (certificate.NotBefore > now || certificate.NotAfter < now)
continue;
var usage = certificate.Extensions[X509Extensions.KeyUsage.Id] as X509KeyUsageExtension;
if (usage != null && (usage.KeyUsages & (RealX509KeyUsageFlags.DigitalSignature | RealX509KeyUsageFlags.NonRepudiation)) == 0)
continue;
if (!certificate.HasPrivateKey)
continue;
if (secure != null) {
if (certificate.Thumbprint != secure.Fingerprint)
continue;
} else {
if (certificate.GetNameInfo (X509NameType.EmailName, false) != mailbox.Address)
continue;
}
return certificate;
}
} finally {
store.Close ();
}
throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found.");
}
/// <summary>
/// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
/// </summary>
/// <remarks>
/// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
/// </remarks>
/// <returns>The cms signer.</returns>
/// <param name="mailbox">The mailbox.</param>
/// <param name="digestAlgo">The preferred digest algorithm.</param>
/// <exception cref="CertificateNotFoundException">
/// A certificate for the specified <paramref name="mailbox"/> could not be found.
/// </exception>
protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
{
var certificate = GetCmsSignerCertificate (mailbox);
var pair = DotNetUtilities.GetKeyPair (certificate.PrivateKey);
var cert = DotNetUtilities.FromX509Certificate (certificate);
var signer = new CmsSigner (cert, pair.Private);
signer.DigestAlgorithm = digestAlgo;
return signer;
}
RealCmsSigner GetRealCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
{
var signer = new RealCmsSigner (GetCmsSignerCertificate (mailbox));
signer.DigestAlgorithm = new Oid (GetDigestOid (digestAlgo));
signer.SignedAttributes.Add (new Pkcs9SigningTime ());
signer.IncludeOption = X509IncludeOption.ExcludeRoot;
return signer;
}
/// <summary>
/// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
/// </summary>
/// <remarks>
/// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
/// </remarks>
/// <param name="certificate">The certificate.</param>
/// <param name="algorithms">The encryption algorithm capabilities of the client (in preferred order).</param>
/// <param name="timestamp">The timestamp.</param>
protected override void UpdateSecureMimeCapabilities (Org.BouncyCastle.X509.X509Certificate certificate, EncryptionAlgorithm[] algorithms, DateTime timestamp)
{
// TODO: implement this - should we add/update the X509Extension for S/MIME Capabilities?
}
static byte[] ReadAllBytes (Stream stream)
{
if (stream is MemoryBlockStream)
return ((MemoryBlockStream) stream).ToArray ();
if (stream is MemoryStream)
return ((MemoryStream) stream).ToArray ();
using (var memory = new MemoryBlockStream ()) {
stream.CopyTo (memory, 4096);
return memory.ToArray ();
}
}
/// <summary>
/// Sign and encapsulate the content using the specified signer.
/// </summary>
/// <remarks>
/// Sign and encapsulate the content using the specified signer.
/// </remarks>
/// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance
/// containing the detached signature data.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="digestAlgo"/> is out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public override ApplicationPkcs7Mime EncapsulatedSign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (content == null)
throw new ArgumentNullException ("content");
var contentInfo = new ContentInfo (ReadAllBytes (content));
var cmsSigner = GetRealCmsSigner (signer, digestAlgo);
var signed = new SignedCms (contentInfo, false);
signed.ComputeSignature (cmsSigner);
var signedData = signed.Encode ();
return new ApplicationPkcs7Mime (SecureMimeType.SignedData, new MemoryStream (signedData, false));
}
/// <summary>
/// Sign the content using the specified signer.
/// </summary>
/// <remarks>
/// Sign the content using the specified signer.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance
/// containing the detached signature data.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="digestAlgo"/> is out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (content == null)
throw new ArgumentNullException ("content");
var contentInfo = new ContentInfo (ReadAllBytes (content));
var cmsSigner = GetRealCmsSigner (signer, digestAlgo);
var signed = new SignedCms (contentInfo, true);
signed.ComputeSignature (cmsSigner);
var signedData = signed.Encode ();
return new ApplicationPkcs7Signature (new MemoryStream (signedData, false));
}
/// <summary>
/// Decrypt the encrypted data.
/// </summary>
/// <remarks>
/// Decrypt the encrypted data.
/// </remarks>
/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
/// <param name="encryptedData">The encrypted data.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encryptedData"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public override MimeEntity Decrypt (Stream encryptedData)
{
if (encryptedData == null)
throw new ArgumentNullException ("encryptedData");
var enveloped = new EnvelopedCms ();
enveloped.Decode (ReadAllBytes (encryptedData));
enveloped.Decrypt ();
var decryptedData = enveloped.Encode ();
var memory = new MemoryStream (decryptedData, false);
return MimeEntity.Load (memory, true);
}
/// <summary>
/// Import the specified certificate.
/// </summary>
/// <remarks>
/// Import the specified certificate.
/// </remarks>
/// <param name="certificate">The certificate.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificate"/> is <c>null</c>.
/// </exception>
public override void Import (Org.BouncyCastle.X509.X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
var store = new X509Store (StoreName.AddressBook, StoreLocation);
store.Open (OpenFlags.ReadWrite);
store.Add (new X509Certificate2 (certificate.GetEncoded ()));
store.Close ();
}
/// <summary>
/// Import the specified certificate revocation list.
/// </summary>
/// <remarks>
/// Import the specified certificate revocation list.
/// </remarks>
/// <param name="crl">The certificate revocation list.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="crl"/> is <c>null</c>.
/// </exception>
public override void Import (X509Crl crl)
{
if (crl == null)
throw new ArgumentNullException ("crl");
// TODO: figure out where to store the CRLs...
}
/// <summary>
/// Imports certificates and keys from a pkcs12-encoded stream.
/// </summary>
/// <remarks>
/// Imports certificates and keys from a pkcs12-encoded stream.
/// </remarks>
/// <param name="stream">The raw certificate and key data.</param>
/// <param name="password">The password to unlock the stream.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.NotSupportedException">
/// Importing keys is not supported by this cryptography context.
/// </exception>
public override void Import (Stream stream, string password)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (password == null)
throw new ArgumentNullException ("password");
var rawData = ReadAllBytes (stream);
var store = new X509Store (StoreName.My, StoreLocation);
var certs = new X509Certificate2Collection ();
store.Open (OpenFlags.ReadWrite);
certs.Import (rawData, password, X509KeyStorageFlags.UserKeySet);
store.AddRange (certs);
store.Close ();
}
#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 Microsoft.Azure.Management.Sql
{
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>
/// TransparentDataEncryptionsOperations operations.
/// </summary>
internal partial class TransparentDataEncryptionsOperations : IServiceOperations<SqlManagementClient>, ITransparentDataEncryptionsOperations
{
/// <summary>
/// Initializes a new instance of the TransparentDataEncryptionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal TransparentDataEncryptionsOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a database's transparent data encryption configuration.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database for which setting the transparent data encryption
/// applies.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating transparent data
/// encryption.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TransparentDataEncryption>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, TransparentDataEncryption parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
string apiVersion = "2014-04-01";
string transparentDataEncryptionName = "current";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("transparentDataEncryptionName", transparentDataEncryptionName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/transparentDataEncryption/{transparentDataEncryptionName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{transparentDataEncryptionName}", System.Uri.EscapeDataString(transparentDataEncryptionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
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<TransparentDataEncryption>();
_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<TransparentDataEncryption>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TransparentDataEncryption>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a database's transparent data encryption configuration.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database for which the transparent data encryption applies.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TransparentDataEncryption>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
string apiVersion = "2014-04-01";
string transparentDataEncryptionName = "current";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("transparentDataEncryptionName", transparentDataEncryptionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/transparentDataEncryption/{transparentDataEncryptionName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{transparentDataEncryptionName}", System.Uri.EscapeDataString(transparentDataEncryptionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = 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<TransparentDataEncryption>();
_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<TransparentDataEncryption>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using Cosmos.Common;
using Cosmos.Core;
using Cosmos.Core.IOGroup.Network;
using Cosmos.HAL.Network;
using Cosmos.IL2CPU.API.Attribs;
namespace Cosmos.HAL.Drivers.PCI.Network
{
public class AMDPCNetII : NetworkDevice
{
protected PCIDeviceNormal pciCard;
protected AMDPCNetIIIOGroup io;
protected MACAddress mac;
protected bool mInitDone;
protected ManagedMemoryBlock mInitBlock;
protected ManagedMemoryBlock mRxDescriptor;
protected ManagedMemoryBlock mTxDescriptor;
protected List<ManagedMemoryBlock> mRxBuffers;
protected List<ManagedMemoryBlock> mTxBuffers;
protected Queue<byte[]> mRecvBuffer;
protected Queue<byte[]> mTransmitBuffer;
private int mNextTXDesc;
public AMDPCNetII(PCIDeviceNormal device)
: base()
{
if (device == null)
{
throw new ArgumentException("PCI Device is null. Unable to get AMD PCNet card");
}
this.pciCard = device;
// this.pciCard.Claimed = true;
//this.pciCard.EnableDevice();
//this.io = new AMDPCNetIIIOGroup((ushort) this.pciCard.BaseAddresses[0].BaseAddress());
this.io.RegisterData.DWord = 0;
// Get the EEPROM MAC Address and set it as the devices MAC
byte[] eeprom_mac = new byte[6];
UInt32 result = io.MAC1.DWord;
eeprom_mac[0] = BinaryHelper.GetByteFrom32bit(result, 0);
eeprom_mac[1] = BinaryHelper.GetByteFrom32bit(result, 8);
eeprom_mac[2] = BinaryHelper.GetByteFrom32bit(result, 16);
eeprom_mac[3] = BinaryHelper.GetByteFrom32bit(result, 24);
result = io.MAC2.DWord;
eeprom_mac[4] = BinaryHelper.GetByteFrom32bit(result, 0);
eeprom_mac[5] = BinaryHelper.GetByteFrom32bit(result, 8);
mac = new MACAddress(eeprom_mac);
mInitBlock = new ManagedMemoryBlock(28, 4);
mRxDescriptor = new ManagedMemoryBlock(256, 16);
mTxDescriptor = new ManagedMemoryBlock(256, 16);
mInitBlock.Write32(0x00, (0x4 << 28) | (0x4 << 20));
mInitBlock.Write32(0x04,
(UInt32) (eeprom_mac[0] | (eeprom_mac[1] << 8) | (eeprom_mac[2] << 16) | (eeprom_mac[3] << 24)));
mInitBlock.Write32(0x08, (UInt32) (eeprom_mac[4] | (eeprom_mac[5] << 8)));
mInitBlock.Write32(0x0C, 0x0);
mInitBlock.Write32(0x10, 0x0);
mInitBlock.Write32(0x14, mRxDescriptor.Offset);
mInitBlock.Write32(0x18, mTxDescriptor.Offset);
InitializationBlockAddress = mInitBlock.Offset;
SoftwareStyleRegister = 0x03;
mRxBuffers = new List<ManagedMemoryBlock>();
mTxBuffers = new List<ManagedMemoryBlock>();
for (uint rxd = 0; rxd < 16; rxd++)
{
uint xOffset = rxd * 16;
ManagedMemoryBlock buffer = new ManagedMemoryBlock(2048);
mRxDescriptor.Write32(xOffset + 8, buffer.Offset);
UInt16 buffer_len = (UInt16) (~buffer.Size);
buffer_len++;
UInt32 flags = (UInt32) (buffer_len & 0x0FFF) | 0xF000 | 0x80000000;
mRxDescriptor.Write32(xOffset + 4, flags);
mRxBuffers.Add(buffer);
}
for (uint txd = 0; txd < 16; txd++)
{
uint xOffset = txd * 16;
ManagedMemoryBlock buffer = new ManagedMemoryBlock(2048);
mTxDescriptor.Write32(xOffset + 8, buffer.Offset);
mTxBuffers.Add(buffer);
}
mNextTXDesc = 0;
// Setup our Receive and Transmit Queues
mTransmitBuffer = new Queue<byte[]>();
mRecvBuffer = new Queue<byte[]>();
//INTs.SetIrqHandler(device.InterruptLine, HandleNetworkInterrupt);
}
protected void HandleNetworkInterrupt(ref INTs.IRQContext aContext)
{
UInt32 cur_status = StatusRegister;
//Console.WriteLine("AMD PCNet IRQ raised!");
if ((cur_status & 0x100) != 0)
{
mInitDone = true;
}
if ((cur_status & 0x200) != 0)
{
if (mTransmitBuffer.Count > 0)
{
byte[] data = mTransmitBuffer.Peek();
if (SendBytes(ref data) == true)
{
mTransmitBuffer.Dequeue();
}
}
}
if ((cur_status & 0x400) != 0)
{
ReadRawData();
}
StatusRegister = cur_status;
Cosmos.Core.Global.PIC.EoiSlave();
}
/// <summary>
/// Retrieve all AMD PCNetII network cards found on computer.
/// </summary>
public static void FindAll()
{
Console.WriteLine("Scanning for AMD PCNetII cards...");
// PCIDevice device = Cosmos.HAL.PCI.GetDevice(0x1022, 0x2000);
// if (device != null)
// {
// AMDPCNetII nic = new AMDPCNetII((PCIDeviceNormal) device);
//
// Console.WriteLine("Found AMD PCNetII NIC on PCI " + device.bus + ":" + device.slot + ":" +
// device.function);
// Console.WriteLine("NIC IRQ: " + device.InterruptLine);
// Console.WriteLine("NIC MAC Address: " + nic.MACAddress.ToString());
// }
}
#region Register Access Properties
protected UInt32 StatusRegister
{
get
{
io.RegisterAddress.DWord = 0x00;
return io.RegisterData.DWord;
}
set
{
io.RegisterAddress.DWord = 0x00;
io.RegisterData.DWord = value;
}
}
protected UInt32 InitializationBlockAddress
{
get
{
UInt32 result;
io.RegisterAddress.DWord = 0x01;
result = io.RegisterData.DWord;
io.RegisterAddress.DWord = 0x02;
result |= (io.RegisterData.DWord << 16);
return result;
}
set
{
io.RegisterAddress.DWord = 0x01;
io.RegisterData.DWord = (value & 0xFFFF);
io.RegisterAddress.DWord = 0x02;
io.RegisterData.DWord = (value >> 16);
}
}
protected UInt32 SoftwareStyleRegister
{
get
{
io.RegisterAddress.DWord = 0x14;
return io.BusData.DWord;
}
set
{
io.RegisterAddress.DWord = 0x14;
io.BusData.DWord = value;
}
}
#endregion
#region Network Device Implementation
public override MACAddress MACAddress
{
get { return mac; }
}
public override bool Ready
{
get { return mInitDone; }
}
public override bool Enable()
{
StatusRegister = 0x43;
return true;
}
[DebugStub(Off = true)]
public override bool QueueBytes(byte[] buffer, int offset, int length)
{
byte[] data = new byte[length];
for (int b = 0; b < length; b++)
{
data[b] = buffer[b + offset];
}
if (SendBytes(ref data) == false)
{
mTransmitBuffer.Enqueue(data);
}
return true;
}
public override bool ReceiveBytes(byte[] buffer, int offset, int max)
{
throw new NotImplementedException();
}
public override byte[] ReceivePacket()
{
if (mRecvBuffer.Count < 1)
{
return null;
}
byte[] data = mRecvBuffer.Dequeue();
return data;
}
public override int BytesAvailable()
{
if (mRecvBuffer.Count < 1)
{
return 0;
}
return mRecvBuffer.Peek().Length;
}
public override bool IsSendBufferFull()
{
return false;
}
public override bool IsReceiveBufferFull()
{
return false;
}
#endregion
#region Helper Functions
[DebugStub(Off = true)]
protected bool SendBytes(ref byte[] aData)
{
int txd = mNextTXDesc++;
if (mNextTXDesc >= 16)
{
mNextTXDesc = 0;
}
uint xOffset = (uint) (txd * 16);
UInt32 status = mTxDescriptor.Read32(xOffset + 4);
if ((status & 0x80000000) == 0)
{
for (uint b = 0; b < aData.Length; b++)
{
mTxBuffers[txd][b] = aData[b];
}
//UInt16 buffer_len = (UInt16)(aData.Length < 64 ? 64 : aData.Length);
UInt16 buffer_len = (UInt16) aData.Length;
buffer_len = (UInt16) (~buffer_len);
buffer_len++;
UInt32 flags = (UInt32) ((buffer_len) & 0x0FFF) | 0x0300F000 | 0x80000000;
mTxDescriptor.Write32(xOffset + 4, flags);
return true;
}
return false;
}
[DebugStub(Off = true)]
private void ReadRawData()
{
uint status;
UInt16 recv_size;
byte[] recv_data;
for (int rxd = 0; rxd < 16; rxd++)
{
uint xOffset = (uint) (rxd * 16);
status = mRxDescriptor.Read32(xOffset + 4);
if ((status & 0x80000000) == 0)
{
recv_size = (UInt16) (mRxDescriptor[xOffset + 0] & 0xFFF);
recv_data = new byte[recv_size];
for (uint b = 0; b < recv_size; b++)
{
recv_data[b] = mRxBuffers[rxd][b];
}
if (DataReceived != null)
{
DataReceived(recv_data);
}
else
{
mRecvBuffer.Enqueue(recv_data);
}
mRxDescriptor.Write32(xOffset + 4, status | 0x80000000);
}
}
}
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Memcached C# client, connection pool for Socket IO
* Copyright (c) 2005
*
* This module is Copyright (c) 2005 Tim Gebhardt
* Based on code from Greg Whalin and Richard Russo from the
* Java memcached client api:
* http://www.whalin.com/memcached/
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @author Tim Gebhardt <tim@gebhardtcomputing.com>
*
* @version 1.0
*/
namespace Memcached.ClientLibrary
{
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using log4net;
///<summary>
///Hashing algorithms we can use
///</summary>
public enum HashingAlgorithm
{
///<summary>native String.hashCode() - fast (cached) but not compatible with other clients</summary>
Native = 0,
///<summary>original compatibility hashing alg (works with other clients)</summary>
OldCompatibleHash = 1,
///<summary>new CRC32 based compatibility hashing algorithm (fast and works with other clients)</summary>
NewCompatibleHash = 2
}
/// <summary>
/// This class is a connection pool for maintaning a pool of persistent connections
/// to memcached servers.
///
/// The pool must be initialized prior to use. This should typically be early on
/// in the lifecycle of the application instance.
/// </summary>
/// <example>
/// //Using defaults
/// String[] serverlist = {"cache0.server.com:12345", "cache1.server.com:12345"};
///
/// SockIOPool pool = SockIOPool.GetInstance();
/// pool.SetServers(serverlist);
/// pool.Initialize();
///
///
/// //An example of initializing using defaults and providing weights for servers:
/// String[] serverlist = {"cache0.server.com:12345", "cache1.server.com:12345"};
/// int[] weights = new int[]{5, 2};
///
/// SockIOPool pool = SockIOPool.GetInstance();
/// pool.SetServers(serverlist);
/// pool.SetWeights(weights);
/// pool.Initialize();
///
///
/// //An example of initializing overriding defaults:
/// String[] serverlist = {"cache0.server.com:12345", "cache1.server.com:12345"};
/// int[] weights = new int[]{5, 2};
/// int initialConnections = 10;
/// int minSpareConnections = 5;
/// int maxSpareConnections = 50;
/// long maxIdleTime = 1000 * 60 * 30; // 30 minutes
/// long maxBusyTime = 1000 * 60 * 5; // 5 minutes
/// long maintThreadSleep = 1000 * 5; // 5 seconds
/// int socketTimeOut = 1000 * 3; // 3 seconds to block on reads
/// int socketConnectTO = 1000 * 3; // 3 seconds to block on initial connections. If 0, then will use blocking connect (default)
/// boolean failover = false; // turn off auto-failover in event of server down
/// boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in pool
///
/// SockIOPool pool = SockIOPool.getInstance();
/// pool.Servers = serverlist;
/// pool.Weights = weights;
/// pool.InitConnections = initialConnections;
/// pool.MinConnections = minSpareConnections;
/// pool.MaxConnections = maxSpareConnections;
/// pool.MaxIdle = maxIdleTime;
/// pool.MaxBusy = maxBusyTime;
/// pool.MaintenanceSleep = maintThreadSleep;
/// pool.SocketTimeout = socketTimeOut;
/// pool.SocketConnectTimeOut = socketConnectTO;
/// pool.Nagle = nagleAlg;
/// pool.HashingAlg = SockIOPool.HashingAlgorithms.NEW_COMPAT_HASH;
/// pool.Initialize();
///
///
/// //The easiest manner in which to initialize the pool is to set the servers and rely on defaults as in the first example.
/// //After pool is initialized, a client will request a SockIO object by calling getSock with the cache key
/// //The client must always close the SockIO object when finished, which will return the connection back to the pool.
/// //An example of retrieving a SockIO object:
/// SockIOPool.SockIO sock = SockIOPool.GetInstance().GetSock(key);
/// try
/// {
/// sock.write("version\r\n");
/// sock.flush();
/// Console.WriteLine("Version: " + sock.ReadLine());
/// }
/// catch(IOException ioe) { Console.WriteLine("io exception thrown") }
/// finally { sock.Close(); }
///
/// </example>
public class SockIOPool
{
// logger
private static ILog Log = LogManager.GetLogger(typeof(SockIOPool));
// store instances of pools
private static Hashtable Pools = new Hashtable();
// Pool data
private MaintenanceThread _maintenanceThread;
private bool _initialized;
private int _maxCreate = 1; // this will be initialized by pool when the pool is initialized
private Hashtable _createShift;
private int _poolMultiplier = 4;
private int _initConns = 3;
private int _minConns = 3;
private int _maxConns = 10;
private long _maxIdle = 1000 * 60 * 3; // max idle time for avail sockets (in milliseconds)
private long _maxBusyTime = 1000 * 60 * 5; // max idle time for avail sockets (in milliseconds)
private long _maintThreadSleep = 1000 * 5; // maintenance thread sleep time (in milliseconds)
private int _socketTimeout = 1000 * 10; // default timeout of socket reads
private int _socketConnectTimeout = 50; // default timeout of socket connections
private bool _failover = true; // default to failover in event of cache server dead
private bool _nagle = true; // enable/disable Nagle's algorithm
private HashingAlgorithm _hashingAlgorithm = HashingAlgorithm.Native; // default to using the native hash as it is the fastest
// list of all servers
private ArrayList _servers;
private ArrayList _weights;
private ArrayList _buckets;
// dead server map
private Hashtable _hostDead;
private Hashtable _hostDeadDuration;
// map to hold all available sockets
private Hashtable _availPool;
// map to hold busy sockets
private Hashtable _busyPool;
// empty constructor
protected SockIOPool() { }
/// <summary>
/// Factory to create/retrieve new pools given a unique poolName.
/// </summary>
/// <param name="poolName">unique name of the pool</param>
/// <returns>instance of SockIOPool</returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static SockIOPool GetInstance(String poolName)
{
if(Pools.ContainsKey(poolName))
return (SockIOPool)Pools[poolName];
SockIOPool pool = new SockIOPool();
Pools[poolName] = pool;
return pool;
}
/// <summary>
/// Single argument version of factory used for back compat.
/// Simply creates a pool named "default".
/// </summary>
/// <returns>instance of SockIOPool</returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static SockIOPool GetInstance()
{
return GetInstance(GetLocalizedString("default instance"));
}
/// <summary>
/// Gets the list of all cache servers
/// </summary>
/// <value>string array of servers [host:port]</value>
public ArrayList Servers
{
get { return _servers; }
}
/// <summary>
/// Sets the list of all cache servers
/// </summary>
/// <param name="servers">string array of servers [host:port]</param>
public void SetServers(string[] servers)
{
SetServers(new ArrayList(servers));
}
/// <summary>
/// Sets the list of all cache servers
/// </summary>
/// <param name="servers">string array of servers [host:port]</param>
public void SetServers(ArrayList servers)
{
_servers = servers;
}
/// <summary>
/// Gets or sets the list of weights to apply to the server list
/// </summary>
/// <value>
/// This is an int array with each element corresponding to an element
/// in the same position in the server string array <see>Servers</see>.
/// </value>
public ArrayList Weights
{
get { return _weights; }
}
/// <summary>
/// sets the list of weights to apply to the server list
/// </summary>
/// <param name="weights">
/// This is an int array with each element corresponding to an element
/// in the same position in the server string array <see>Servers</see>.
/// </param>
public void SetWeights(int[] weights)
{
SetWeights(new ArrayList(weights));
}
/// <summary>
/// sets the list of weights to apply to the server list
/// </summary>
/// <param name="weights">
/// This is an int array with each element corresponding to an element
/// in the same position in the server string array <see>Servers</see>.
/// </param>
public void SetWeights(ArrayList weights)
{
_weights = weights;
}
/// <summary>
/// Gets or sets the initial number of connections per server setting in the available pool.
/// </summary>
/// <value>int number of connections</value>
public int InitConnections
{
get { return _initConns; }
set { _initConns = value; }
}
/// <summary>
/// Gets or sets the minimum number of spare connections to maintain in our available pool
/// </summary>
public int MinConnections
{
get { return _minConns; }
set { _minConns = value; }
}
/// <summary>
/// Gets or sets the maximum number of spare connections allowed in our available pool.
/// </summary>
public int MaxConnections
{
get { return _maxConns; }
set { _maxConns = value; }
}
/// <summary>
/// Gets or sets the maximum idle time for threads in the avaiable pool.
/// </summary>
public long MaxIdle
{
get { return _maxIdle; }
set { _maxIdle = value; }
}
/// <summary>
/// Gets or sets the maximum busy time for threads in the busy pool
/// </summary>
/// <value>idle time in milliseconds</value>
public long MaxBusy
{
get { return _maxBusyTime; }
set { _maxBusyTime = value; }
}
/// <summary>
/// Gets or sets the sleep time between runs of the pool maintenance thread.
/// If set to 0, then the maintenance thread will not be started;
/// </summary>
/// <value>sleep time in milliseconds</value>
public long MaintenanceSleep
{
get { return _maintThreadSleep; }
set { _maintThreadSleep = value; }
}
/// <summary>
/// Gets or sets the socket timeout for reads
/// </summary>
/// <value>timeout time in milliseconds</value>
public int SocketTimeout
{
get { return _socketTimeout; }
set { _socketTimeout = value; }
}
/// <summary>
/// Gets or sets the socket timeout for connects.
/// </summary>
/// <value>timeout time in milliseconds</value>
public int SocketConnectTimeout
{
get { return _socketConnectTimeout; }
set { _socketConnectTimeout = value; }
}
/// <summary>
/// Gets or sets the failover flag for the pool.
///
/// If this flag is set to true and a socket fails to connect,
/// the pool will attempt to return a socket from another server
/// if one exists. If set to false, then getting a socket
/// will return null if it fails to connect to the requested server.
/// </summary>
public bool Failover
{
get { return _failover; }
set { _failover = value; }
}
/// <summary>
/// Gets or sets the Nagle algorithm flag for the pool.
///
/// If false, will turn off Nagle's algorithm on all sockets created.
/// </summary>
public bool Nagle
{
get { return _nagle; }
set { _nagle = value; }
}
/// <summary>
/// Gets or sets the hashing algorithm we will use.
/// </summary>
public HashingAlgorithm HashingAlgorithm
{
get { return _hashingAlgorithm; }
set { _hashingAlgorithm = value; }
}
/// <summary>
/// Internal private hashing method.
///
/// This is the original hashing algorithm from other clients.
/// Found to be slow and have poor distribution.
/// </summary>
/// <param name="key">string to hash</param>
/// <returns>hashcode for this string using memcached's hashing algorithm</returns>
private static int OriginalHashingAlgorithm(string key)
{
int hash = 0;
char[] cArr = key.ToCharArray();
for(int i = 0; i < cArr.Length; ++i)
{
hash = (hash * 33) + cArr[i];
}
return hash;
}
/// <summary>
/// Internal private hashing method.
///
/// This is the new hashing algorithm from other clients.
/// Found to be fast and have very good distribution.
///
/// UPDATE: this is dog slow under java. Maybe under .NET?
/// </summary>
/// <param name="key">string to hash</param>
/// <returns>hashcode for this string using memcached's hashing algorithm</returns>
private static int NewHashingAlgorithm(string key)
{
CRCTool checksum = new CRCTool();
checksum.Init(CRCTool.CRCCode.CRC32);
int crc = (int)checksum.crctablefast(UTF8Encoding.UTF8.GetBytes(key));
return (crc >> 16) & 0x7fff;
}
/// <summary>
/// Initializes the pool
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Initialize()
{
// check to see if already initialized
if(_initialized
&& _buckets != null
&& _availPool != null
&& _busyPool != null)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("initializing initialized pool"));
}
return;
}
// initialize empty maps
_buckets = new ArrayList();
_availPool = new Hashtable(_servers.Count * _initConns);
_busyPool = new Hashtable(_servers.Count * _initConns);
_hostDeadDuration = new Hashtable();
_hostDead = new Hashtable();
_createShift = new Hashtable();
_maxCreate = (_poolMultiplier > _minConns) ? _minConns : _minConns / _poolMultiplier; // only create up to maxCreate connections at once
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("initializing pool")
.Replace("$$InitConnections$$", InitConnections.ToString(new NumberFormatInfo()))
.Replace("$$MinConnections$$", MinConnections.ToString(new NumberFormatInfo()))
.Replace("$$MaxConnections$$", MaxConnections.ToString(new NumberFormatInfo())));
}
// if servers is not set, or it empty, then
// throw a runtime exception
if(_servers == null || _servers.Count <= 0)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("initialize with no servers"));
}
throw new ArgumentException(GetLocalizedString("initialize with no servers"));
}
for(int i = 0; i < _servers.Count; i++)
{
// add to bucket
// with weights if we have them
if(_weights != null && _weights.Count > i)
{
for(int k = 0; k < ((int)_weights[i]); k++)
{
_buckets.Add(_servers[i]);
if(Log.IsDebugEnabled)
{
Log.Debug("Added " + _servers[i] + " to server bucket");
}
}
}
else
{
_buckets.Add(_servers[i]);
if(Log.IsDebugEnabled)
{
Log.Debug("Added " + _servers[i] + " to server bucket");
}
}
// create initial connections
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("create initial connections").Replace("$$InitConns$$", InitConnections.ToString(new NumberFormatInfo())).Replace("$$Servers[i]$$", Servers[i].ToString()));
}
for(int j = 0; j < _initConns; j++)
{
SockIO socket = CreateSocket((string)_servers[i]);
if(socket == null)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to connect").Replace("$$Servers[i]$$", Servers[i].ToString()).Replace("$$j$$", j.ToString(new NumberFormatInfo())));
}
break;
}
AddSocketToPool(_availPool, (string)_servers[i], socket);
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("created and added socket").Replace("$$ToString$$", socket.ToString()).Replace("$$Servers[i]$$", Servers[i].ToString()));
}
}
}
// mark pool as initialized
_initialized = true;
// start maint thread TODO: re-enable
if(_maintThreadSleep > 0)
this.StartMaintenanceThread();
}
/// <summary>
/// Returns the state of the pool
/// </summary>
/// <returns>returns <c>true</c> if initialized</returns>
public bool Initialized
{
get { return _initialized; }
}
/// <summary>
/// Creates a new SockIO obj for the given server.
///
///If server fails to connect, then return null and do not try
///again until a duration has passed. This duration will grow
///by doubling after each failed attempt to connect.
/// </summary>
/// <param name="host">host:port to connect to</param>
/// <returns>SockIO obj or null if failed to create</returns>
protected SockIO CreateSocket(string host)
{
SockIO socket = null;
// if host is dead, then we don't need to try again
// until the dead status has expired
// we do not try to put back in if failover is off
if(_failover && _hostDead.ContainsKey(host) && _hostDeadDuration.ContainsKey(host))
{
DateTime store = (DateTime)_hostDead[host];
long expire = ((long)_hostDeadDuration[host]);
if((store.AddMilliseconds(expire)) > DateTime.Now)
return null;
}
try
{
socket = new SockIO(this, host, _socketTimeout, _socketConnectTimeout, _nagle);
if(!socket.IsConnected)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to get socket").Replace("$$Host$$", host));
}
try
{
socket.TrueClose();
}
catch(SocketException ex)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to close socket on host").Replace("$$Host$$", host), ex);
}
socket = null;
}
}
}
catch(SocketException ex)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to get socket").Replace("$$Host$$", host), ex);
}
socket = null;
}
catch(ArgumentException ex)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to get socket").Replace("$$Host$$", host), ex);
}
socket = null;
}
catch(IOException ex)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to get socket").Replace("$$Host$$", host), ex);
}
socket = null;
}
// if we failed to get socket, then mark
// host dead for a duration which falls off
if(socket == null)
{
DateTime now = DateTime.Now;
_hostDead[host] = now;
long expire = (_hostDeadDuration.ContainsKey(host)) ? (((long)_hostDeadDuration[host]) * 2) : 100;
_hostDeadDuration[host] = expire;
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("ignoring dead host").Replace("$$Host$$", host).Replace("$$Expire$$", expire.ToString(new NumberFormatInfo())));
}
// also clear all entries for this host from availPool
ClearHostFromPool(_availPool, host);
}
else
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("created socket").Replace("$$ToString$$", socket.ToString()).Replace("$$Host$$", host));
}
_hostDead.Remove(host);
_hostDeadDuration.Remove(host);
if(_buckets.BinarySearch(host) < 0)
_buckets.Add(host);
}
return socket;
}
/// <summary>
/// Returns appropriate SockIO object given
/// string cache key.
/// </summary>
/// <param name="key">hashcode for cache key</param>
/// <returns>SockIO obj connected to server</returns>
public SockIO GetSock(string key)
{
return GetSock(key, null);
}
/// <summary>
/// Returns appropriate SockIO object given
/// string cache key and optional hashcode.
///
/// Trys to get SockIO from pool. Fails over
/// to additional pools in event of server failure.
/// </summary>
/// <param name="key">hashcode for cache key</param>
/// <param name="hashCode">if not null, then the int hashcode to use</param>
/// <returns>SockIO obj connected to server</returns>
public SockIO GetSock(string key, object hashCode)
{
string hashCodeString = "<null>";
if(hashCode != null)
hashCodeString = hashCode.ToString();
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("cache socket pick").Replace("$$Key$$", key).Replace("$$HashCode$$", hashCodeString));
}
if (key == null || key.Length == 0)
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("null key"));
}
return null;
}
if(!_initialized)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("get socket from uninitialized pool"));
}
return null;
}
// if no servers return null
if(_buckets.Count == 0)
return null;
// if only one server, return it
if(_buckets.Count == 1)
return GetConnection((string)_buckets[0]);
int tries = 0;
// generate hashcode
int hv;
if(hashCode != null)
{
hv = (int)hashCode;
}
else
{
switch(_hashingAlgorithm)
{
case HashingAlgorithm.Native:
hv = key.GetHashCode();
break;
case HashingAlgorithm.OldCompatibleHash:
hv = OriginalHashingAlgorithm(key);
break;
case HashingAlgorithm.NewCompatibleHash:
hv = NewHashingAlgorithm(key);
break;
default:
// use the native hash as a default
hv = key.GetHashCode();
_hashingAlgorithm = HashingAlgorithm.Native;
break;
}
}
// keep trying different servers until we find one
while(tries++ <= _buckets.Count)
{
// get bucket using hashcode
// get one from factory
int bucket = hv % _buckets.Count;
if(bucket < 0)
bucket += _buckets.Count;
SockIO sock = GetConnection((string)_buckets[bucket]);
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("cache choose").Replace("$$Bucket$$", _buckets[bucket].ToString()).Replace("$$Key$$", key));
}
if(sock != null)
return sock;
// if we do not want to failover, then bail here
if(!_failover)
return null;
// if we failed to get a socket from this server
// then we try again by adding an incrementer to the
// current key and then rehashing
switch(_hashingAlgorithm)
{
case HashingAlgorithm.Native:
hv += ((string)("" + tries + key)).GetHashCode();
break;
case HashingAlgorithm.OldCompatibleHash:
hv += OriginalHashingAlgorithm("" + tries + key);
break;
case HashingAlgorithm.NewCompatibleHash:
hv += NewHashingAlgorithm("" + tries + key);
break;
default:
// use the native hash as a default
hv += ((string)("" + tries + key)).GetHashCode();
_hashingAlgorithm = HashingAlgorithm.Native;
break;
}
}
return null;
}
/// <summary>
/// Returns a SockIO object from the pool for the passed in host.
///
/// Meant to be called from a more intelligent method
/// which handles choosing appropriate server
/// and failover.
/// </summary>
/// <param name="host">host from which to retrieve object</param>
/// <returns>SockIO object or null if fail to retrieve one</returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public SockIO GetConnection(string host)
{
if(!_initialized)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("get socket from uninitialized pool"));
}
return null;
}
if(host == null)
return null;
// if we have items in the pool
// then we can return it
if(_availPool != null && !(_availPool.Count == 0))
{
// take first connected socket
Hashtable aSockets = (Hashtable)_availPool[host];
if(aSockets != null && !(aSockets.Count == 0))
{
foreach(SockIO socket in new IteratorIsolateCollection(aSockets.Keys))
{
if(socket.IsConnected)
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("move socket").Replace("$$Host$$", host).Replace("$$Socket$$", socket.ToString()));
}
// remove from avail pool
aSockets.Remove(socket);
// add to busy pool
AddSocketToPool(_busyPool, host, socket);
// return socket
return socket;
}
else
{
// not connected, so we need to remove it
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("socket not connected").Replace("$$Host$$", host).Replace("$$Socket$$", socket.ToString()));
}
// remove from avail pool
aSockets.Remove(socket);
}
}
}
}
// if here, then we found no sockets in the pool
// try to create on a sliding scale up to maxCreate
object cShift = _createShift[host];
int shift = (cShift != null) ? (int)cShift : 0;
int create = 1 << shift;
if(create >= _maxCreate)
{
create = _maxCreate;
}
else
{
shift++;
}
// store the shift value for this host
_createShift[host] = shift;
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("creating sockets").Replace("$$Create$$", create.ToString(new NumberFormatInfo())));
}
for(int i = create; i > 0; i--)
{
SockIO socket = CreateSocket(host);
if(socket == null)
break;
if(i == 1)
{
// last iteration, add to busy pool and return sockio
AddSocketToPool(_busyPool, host, socket);
return socket;
}
else
{
// add to avail pool
AddSocketToPool(_availPool, host, socket);
}
}
// should never get here
return null;
}
/// <summary>
/// Adds a socket to a given pool for the given host.
///
/// Internal utility method.
/// </summary>
/// <param name="pool">pool to add to</param>
/// <param name="host">host this socket is connected to</param>
/// <param name="socket">socket to add</param>
//[MethodImpl(MethodImplOptions.Synchronized)]
protected static void AddSocketToPool(Hashtable pool, string host, SockIO socket)
{
if (pool == null)
return;
Hashtable sockets;
if (host != null && host.Length != 0 && pool.ContainsKey(host))
{
sockets = (Hashtable)pool[host];
if (sockets != null)
{
sockets[socket] = DateTime.Now; //MaxM 1.16.05: Use current DateTime to indicate socker creation time rather than milliseconds since 1970
return;
}
}
sockets = new Hashtable();
sockets[socket] = DateTime.Now; //MaxM 1.16.05: Use current DateTime to indicate socker creation time rather than milliseconds since 1970
pool[host] = sockets;
}
/// <summary>
/// Removes a socket from specified pool for host.
///
/// Internal utility method.
/// </summary>
/// <param name="pool">pool to remove from</param>
/// <param name="host">host pool</param>
/// <param name="socket">socket to remove</param>
[MethodImpl(MethodImplOptions.Synchronized)]
protected static void RemoveSocketFromPool(Hashtable pool, string host, SockIO socket)
{
if (host != null && host.Length == 0 || pool == null)
return;
if(pool.ContainsKey(host))
{
Hashtable sockets = (Hashtable)pool[host];
if(sockets != null)
{
sockets.Remove(socket);
}
}
}
/// <summary>
/// Closes and removes all sockets from specified pool for host.
///
/// Internal utility method.
/// </summary>
/// <param name="pool">pool to clear</param>
/// <param name="host">host to clear</param>
[MethodImpl(MethodImplOptions.Synchronized)]
protected static void ClearHostFromPool(Hashtable pool, string host)
{
if (pool == null || host != null && host.Length == 0)
return;
if(pool.ContainsKey(host))
{
Hashtable sockets = (Hashtable)pool[host];
if(sockets != null && sockets.Count > 0)
{
foreach(SockIO socket in new IteratorIsolateCollection(sockets.Keys))
{
try
{
socket.TrueClose();
}
catch(IOException ioe)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to close socket"), ioe);
}
}
sockets.Remove(socket);
}
}
}
}
/// <summary>
/// Checks a SockIO object in with the pool.
///
/// This will remove SocketIO from busy pool, and optionally
/// add to avail pool.
/// </summary>
/// <param name="socket">socket to return</param>
/// <param name="addToAvail">add to avail pool if true</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public void CheckIn(SockIO socket, bool addToAvail)
{
if (socket == null)
return;
string host = socket.Host;
if(Log.IsDebugEnabled)
{
Log.Debug("Calling check-in on socket: " + socket.ToString() + " for host: " + host);
}
// remove from the busy pool
if(Log.IsDebugEnabled)
{
Log.Debug("Removing socket (" + socket.ToString() + ") from busy pool for host: " + host);
}
RemoveSocketFromPool(_busyPool, host, socket);
// add to avail pool
if(addToAvail && socket.IsConnected)
{
if(Log.IsDebugEnabled)
{
Log.Debug("Returning socket (" + socket.ToString() + " to avail pool for host: " + host);
}
AddSocketToPool(_availPool, host, socket);
}
}
/// <summary>
/// Returns a socket to the avail pool.
///
/// This is called from SockIO.close(). Calling this method
/// directly without closing the SockIO object first
/// will cause an IOException to be thrown.
/// </summary>
/// <param name="socket">socket to return</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public void CheckIn(SockIO socket)
{
CheckIn(socket, true);
}
/// <summary>
/// Closes all sockets in the passed in pool.
///
/// Internal utility method.
/// </summary>
/// <param name="pool">pool to close</param>
protected static void ClosePool(Hashtable pool)
{
if (pool == null)
return;
foreach(string host in pool.Keys)
{
Hashtable sockets = (Hashtable)pool[host];
foreach(SockIO socket in new IteratorIsolateCollection(sockets.Keys))
{
try
{
socket.TrueClose();
}
catch(IOException ioe)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to true close").Replace("$$ToString$$", socket.ToString()).Replace("$$Host$$", host), ioe);
}
}
sockets.Remove(socket);
}
}
}
/// <summary>
/// Shuts down the pool.
///
/// Cleanly closes all sockets.
/// Stops the maint thread.
/// Nulls out all internal maps
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Shutdown()
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("start socket pool shutdown"));
}
if(_maintenanceThread != null && _maintenanceThread.IsRunning)
StopMaintenanceThread();
if(Log.IsDebugEnabled)
{
Log.Debug("Closing all internal pools.");
}
ClosePool(_availPool);
ClosePool(_busyPool);
_availPool = null;
_busyPool = null;
_buckets = null;
_hostDeadDuration = null;
_hostDead = null;
_initialized = false;
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("end socket pool shutdown"));
}
}
/// <summary>
/// Starts the maintenance thread.
///
/// This thread will manage the size of the active pool
/// as well as move any closed, but not checked in sockets
/// back to the available pool.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
protected void StartMaintenanceThread()
{
if(_maintenanceThread != null)
{
if(_maintenanceThread.IsRunning)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("main thread running"));
}
}
else
{
_maintenanceThread.Start();
}
}
else
{
_maintenanceThread = new MaintenanceThread(this);
_maintenanceThread.Interval = _maintThreadSleep;
_maintenanceThread.Start();
}
}
/// <summary>
/// Stops the maintenance thread.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
protected void StopMaintenanceThread()
{
if(_maintenanceThread != null && _maintenanceThread.IsRunning)
_maintenanceThread.StopThread();
}
/// <summary>
/// Runs self maintenance on all internal pools.
///
/// This is typically called by the maintenance thread to manage pool size.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
protected void SelfMaintain()
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("start self maintenance"));
}
// go through avail sockets and create/destroy sockets
// as needed to maintain pool settings
foreach(string host in new IteratorIsolateCollection(_availPool.Keys))
{
Hashtable sockets = (Hashtable)_availPool[host];
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("size of available pool").Replace("$$Host$$", host).Replace("$$Sockets$$", sockets.Count.ToString(new NumberFormatInfo())));
}
// if pool is too small (n < minSpare)
if(sockets.Count < _minConns)
{
// need to create new sockets
int need = _minConns - sockets.Count;
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("need to create new sockets").Replace("$$Need$$", need.ToString(new NumberFormatInfo())).Replace("$$Host$$", host));
}
for(int j = 0; j < need; j++)
{
SockIO socket = CreateSocket(host);
if(socket == null)
break;
AddSocketToPool(_availPool, host, socket);
}
}
else if(sockets.Count > _maxConns)
{
// need to close down some sockets
int diff = sockets.Count - _maxConns;
int needToClose = (diff <= _poolMultiplier)
? diff
: (diff) / _poolMultiplier;
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("need to remove spare sockets").Replace("$$NeedToClose$$", needToClose.ToString(new NumberFormatInfo()).Replace("$$Host$$", host)));
}
foreach(SockIO socket in new IteratorIsolateCollection(sockets.Keys))
{
if(needToClose <= 0)
break;
// remove stale entries
DateTime expire = (DateTime)sockets[socket];
// if past idle time
// then close socket
// and remove from pool
if((expire.AddMilliseconds(_maxIdle)) < DateTime.Now)
{
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("removing stale entry"));
}
try
{
socket.TrueClose();
}
catch(IOException ioe)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to close socket"), ioe);
}
}
sockets.Remove(socket);
needToClose--;
}
}
}
// reset the shift value for creating new SockIO objects
_createShift[host] = 0;
}
// go through busy sockets and destroy sockets
// as needed to maintain pool settings
foreach(string host in _busyPool.Keys)
{
Hashtable sockets = (Hashtable)_busyPool[host];
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("size of busy pool").Replace("$$Host$$", host).Replace("$$Sockets$$", sockets.Count.ToString(new NumberFormatInfo())));
}
// loop through all connections and check to see if we have any hung connections
foreach(SockIO socket in new IteratorIsolateCollection(sockets.Keys))
{
// remove stale entries
DateTime hungTime = (DateTime)sockets[socket];
// if past max busy time
// then close socket
// and remove from pool
if((hungTime.AddMilliseconds(_maxBusyTime)) < DateTime.Now)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("removing hung connection").Replace("$$Time$$", (new TimeSpan(DateTime.Now.Ticks - hungTime.Ticks).TotalMilliseconds).ToString(new NumberFormatInfo())));
}
try
{
socket.TrueClose();
}
catch(IOException ioe)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("failed to close socket"), ioe);
}
}
sockets.Remove(socket);
}
}
}
if(Log.IsDebugEnabled)
{
Log.Debug(GetLocalizedString("end self maintenance"));
}
}
/// <summary>
/// Class which extends thread and handles maintenance of the pool.
/// </summary>
private class MaintenanceThread
{
private MaintenanceThread() { }
private Thread _thread;
private SockIOPool _pool;
private long _interval = 1000 * 3; // every 3 seconds
private bool _stopThread;
public MaintenanceThread(SockIOPool pool)
{
_thread = new Thread(new ThreadStart(Maintain));
_pool = pool;
}
public long Interval
{
get { return _interval; }
set { _interval = value; }
}
public bool IsRunning
{
get { return _thread.IsAlive; }
}
/// <summary>
/// Sets stop variable and interups and wait
/// </summary>
public void StopThread()
{
_stopThread = true;
_thread.Interrupt();
}
/// <summary>
/// The logic of the thread.
/// </summary>
private void Maintain()
{
while(!_stopThread)
{
try
{
Thread.Sleep((int)_interval);
// if pool is initialized, then
// run the maintenance method on itself
if(_pool.Initialized)
_pool.SelfMaintain();
}
catch(ThreadInterruptedException) { } //MaxM: When SockIOPool.getInstance().shutDown() is called, this exception will be raised and can be safely ignored.
catch(Exception ex)
{
if(Log.IsErrorEnabled)
{
Log.Error(GetLocalizedString("maintenance thread choked"), ex);
}
}
}
}
/// <summary>
/// Start the thread
/// </summary>
public void Start()
{
_stopThread = false;
_thread.Start();
}
}
private static ResourceManager _resourceManager = new ResourceManager("Memcached.ClientLibrary.StringMessages", typeof(SockIOPool).Assembly);
private static string GetLocalizedString(string key)
{
return _resourceManager.GetString(key);
}
}
}
| |
// 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: Class to represent all synchronization objects in the runtime (that allow multiple wait)
**
**
=============================================================================*/
namespace System.Threading
{
using System.Threading;
using System.Runtime.Remoting;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.Versioning;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using Win32Native = Microsoft.Win32.Win32Native;
public abstract class WaitHandle : MarshalByRefObject, IDisposable
{
public const int WaitTimeout = 0x102;
private const int MAX_WAITHANDLES = 64;
#pragma warning disable 414 // Field is not used from managed.
private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.)
#pragma warning restore 414
internal volatile SafeWaitHandle safeWaitHandle;
internal bool hasThreadAffinity;
private static IntPtr GetInvalidHandle()
{
return Win32Native.INVALID_HANDLE_VALUE;
}
protected static readonly IntPtr InvalidHandle = GetInvalidHandle();
private const int WAIT_OBJECT_0 = 0;
private const int WAIT_ABANDONED = 0x80;
private const int WAIT_FAILED = 0x7FFFFFFF;
private const int ERROR_TOO_MANY_POSTS = 0x12A;
internal enum OpenExistingResult
{
Success,
NameNotFound,
PathNotFound,
NameInvalid
}
protected WaitHandle()
{
Init();
}
private void Init()
{
safeWaitHandle = null;
waitHandle = InvalidHandle;
hasThreadAffinity = false;
}
[Obsolete("Use the SafeWaitHandle property instead.")]
public virtual IntPtr Handle
{
get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle(); }
set
{
if (value == InvalidHandle)
{
// This line leaks a handle. However, it's currently
// not perfectly clear what the right behavior is here
// anyways. This preserves Everett behavior. We should
// ideally do these things:
// *) Expose a settable SafeHandle property on WaitHandle.
// *) Expose a settable OwnsHandle property on SafeHandle.
if (safeWaitHandle != null)
{
safeWaitHandle.SetHandleAsInvalid();
safeWaitHandle = null;
}
}
else
{
safeWaitHandle = new SafeWaitHandle(value, true);
}
waitHandle = value;
}
}
public SafeWaitHandle SafeWaitHandle
{
get
{
if (safeWaitHandle == null)
{
safeWaitHandle = new SafeWaitHandle(InvalidHandle, false);
}
return safeWaitHandle;
}
set
{
// Set safeWaitHandle and waitHandle in a CER so we won't take
// a thread abort between the statements and leave the wait
// handle in an invalid state. Note this routine is not thread
// safe however.
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
if (value == null)
{
safeWaitHandle = null;
waitHandle = InvalidHandle;
}
else
{
safeWaitHandle = value;
waitHandle = safeWaitHandle.DangerousGetHandle();
}
}
}
}
// Assembly-private version that doesn't do a security check. Reduces the
// number of link-time security checks when reading & writing to a file,
// and helps avoid a link time check while initializing security (If you
// call a Serialization method that requires security before security
// has started up, the link time check will start up security, run
// serialization code for some security attribute stuff, call into
// FileStream, which will then call Sethandle, which requires a link time
// security check.). While security has fixed that problem, we still
// don't need to do a linktime check here.
internal void SetHandleInternal(SafeWaitHandle handle)
{
safeWaitHandle = handle;
waitHandle = handle.DangerousGetHandle();
}
public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
return WaitOne((long)millisecondsTimeout, exitContext);
}
public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
{
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return WaitOne(tm, exitContext);
}
public virtual bool WaitOne()
{
//Infinite Timeout
return WaitOne(-1, false);
}
public virtual bool WaitOne(int millisecondsTimeout)
{
return WaitOne(millisecondsTimeout, false);
}
public virtual bool WaitOne(TimeSpan timeout)
{
return WaitOne(timeout, false);
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
private bool WaitOne(long timeout, bool exitContext)
{
return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext);
}
internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
{
if (waitableSafeHandle == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext);
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
if (ret == WAIT_ABANDONED)
{
ThrowAbandonedMutexException();
}
return (ret != WaitTimeout);
}
internal bool WaitOneWithoutFAS()
{
// version of waitone without fast application switch (FAS) support
// This is required to support the Wait which FAS needs (otherwise recursive dependency comes in)
if (safeWaitHandle == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
long timeout = -1;
int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false);
if (ret == WAIT_ABANDONED)
{
ThrowAbandonedMutexException();
}
return (ret != WaitTimeout);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext);
/*========================================================================
** Waits for signal from all the objects.
** timeout indicates how long to wait before the method returns.
** This method will return either when all the object have been pulsed
** or timeout milliseonds have elapsed.
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll);
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
if (waitHandles == null)
{
throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles);
}
if (waitHandles.Length == 0)
{
//
// Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct.
// Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2,
// which went back to ArgumentException.
//
// Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException
// in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking
// user code.
//
throw new ArgumentException(SR.Argument_EmptyWaithandleArray);
}
if (waitHandles.Length > MAX_WAITHANDLES)
{
throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
for (int i = 0; i < waitHandles.Length; i++)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement);
internalWaitHandles[i] = waitHandle;
}
#if _DEBUG
// make sure we do not use waitHandles any more.
waitHandles = null;
#endif
int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ );
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret))
{
//In the case of WaitAll the OS will only provide the
// information that mutex was abandoned.
// It won't tell us which one. So we can't set the Index or provide access to the Mutex
ThrowAbandonedMutexException();
}
GC.KeepAlive(internalWaitHandles);
return (ret != WaitTimeout);
}
public static bool WaitAll(
WaitHandle[] waitHandles,
TimeSpan timeout,
bool exitContext)
{
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return WaitAll(waitHandles, (int)tm, exitContext);
}
/*========================================================================
** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true
========================================================================*/
public static bool WaitAll(WaitHandle[] waitHandles)
{
return WaitAll(waitHandles, Timeout.Infinite, true);
}
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
{
return WaitAll(waitHandles, millisecondsTimeout, true);
}
public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
{
return WaitAll(waitHandles, timeout, true);
}
/*========================================================================
** Waits for notification from any of the objects.
** timeout indicates how long to wait before the method returns.
** This method will return either when either one of the object have been
** signalled or timeout milliseonds have elapsed.
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
if (waitHandles == null)
{
throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles);
}
if (waitHandles.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyWaithandleArray);
}
if (MAX_WAITHANDLES < waitHandles.Length)
{
throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
for (int i = 0; i < waitHandles.Length; i++)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement);
internalWaitHandles[i] = waitHandle;
}
#if _DEBUG
// make sure we do not use waitHandles any more.
waitHandles = null;
#endif
int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ );
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret))
{
int mutexIndex = ret - WAIT_ABANDONED;
if (0 <= mutexIndex && mutexIndex < internalWaitHandles.Length)
{
ThrowAbandonedMutexException(mutexIndex, internalWaitHandles[mutexIndex]);
}
else
{
ThrowAbandonedMutexException();
}
}
GC.KeepAlive(internalWaitHandles);
return ret;
}
public static int WaitAny(
WaitHandle[] waitHandles,
TimeSpan timeout,
bool exitContext)
{
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return WaitAny(waitHandles, (int)tm, exitContext);
}
public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
{
return WaitAny(waitHandles, timeout, true);
}
/*========================================================================
** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true
========================================================================*/
public static int WaitAny(WaitHandle[] waitHandles)
{
return WaitAny(waitHandles, Timeout.Infinite, true);
}
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
{
return WaitAny(waitHandles, millisecondsTimeout, true);
}
/*=================================================
==
== SignalAndWait
==
==================================================*/
#if PLATFORM_WINDOWS
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal, SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
bool hasThreadAffinity, bool exitContext);
#endif // PLATFORM_WINDOWS
public static bool SignalAndWait(
WaitHandle toSignal,
WaitHandle toWaitOn)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // https://github.com/dotnet/coreclr/issues/10441
#else
return SignalAndWait(toSignal, toWaitOn, -1, false);
#endif
}
public static bool SignalAndWait(
WaitHandle toSignal,
WaitHandle toWaitOn,
TimeSpan timeout,
bool exitContext)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // https://github.com/dotnet/coreclr/issues/10441
#else
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return SignalAndWait(toSignal, toWaitOn, (int)tm, exitContext);
#endif
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
public static bool SignalAndWait(
WaitHandle toSignal,
WaitHandle toWaitOn,
int millisecondsTimeout,
bool exitContext)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // https://github.com/dotnet/coreclr/issues/10441
#else
if (null == toSignal)
{
throw new ArgumentNullException(nameof(toSignal));
}
if (null == toWaitOn)
{
throw new ArgumentNullException(nameof(toWaitOn));
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
//NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL)
int ret = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout,
toWaitOn.hasThreadAffinity, exitContext);
if (WAIT_ABANDONED == ret)
{
ThrowAbandonedMutexException();
}
if (ERROR_TOO_MANY_POSTS == ret)
{
throw new InvalidOperationException(SR.Threading_WaitHandleTooManyPosts);
}
//Object was signaled
if (WAIT_OBJECT_0 == ret)
{
return true;
}
//Timeout
return false;
#endif
}
private static void ThrowAbandonedMutexException()
{
throw new AbandonedMutexException();
}
private static void ThrowAbandonedMutexException(int location, WaitHandle handle)
{
throw new AbandonedMutexException(location, handle);
}
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool explicitDisposing)
{
if (safeWaitHandle != null)
{
safeWaitHandle.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
// 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.EventHub
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ConsumerGroupsOperations.
/// </summary>
public static partial class ConsumerGroupsOperationsExtensions
{
/// <summary>
/// Creates or updates an Event Hubs consumer group as a nested resource within
/// a Namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639498.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a consumer group resource.
/// </param>
public static ConsumerGroupResource CreateOrUpdate(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, ConsumerGroupCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Event Hubs consumer group as a nested resource within
/// a Namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639498.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a consumer group resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConsumerGroupResource> CreateOrUpdateAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, ConsumerGroupCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a consumer group from the specified Event Hub and resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639491.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
public static void Delete(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName)
{
operations.DeleteAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a consumer group from the specified Event Hub and resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639491.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a description for the specified consumer group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639488.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
public static ConsumerGroupResource Get(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName)
{
return operations.GetAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a description for the specified consumer group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639488.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConsumerGroupResource> GetAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the consumer groups in a Namespace. An empty feed is returned if
/// no consumer group exists in the Namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639503.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
public static IPage<ConsumerGroupResource> ListAll(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName)
{
return operations.ListAllAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the consumer groups in a Namespace. An empty feed is returned if
/// no consumer group exists in the Namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639503.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ConsumerGroupResource>> ListAllAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the consumer groups in a Namespace. An empty feed is returned if
/// no consumer group exists in the Namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639503.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ConsumerGroupResource> ListAllNext(this IConsumerGroupsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the consumer groups in a Namespace. An empty feed is returned if
/// no consumer group exists in the Namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639503.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ConsumerGroupResource>> ListAllNextAsync(this IConsumerGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
// EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
// FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
namespace Microsoft.Spectrum.MeasurementStation.Service
{
using Common.Enums;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
using Microsoft.Spectrum.Common;
using Microsoft.Spectrum.Common.Azure;
using Microsoft.Spectrum.MeasurementStation.Contract;
using Microsoft.Spectrum.Storage.Enums;
using Microsoft.Spectrum.Storage.Queue.Azure;
using Microsoft.Spectrum.Storage.Table.Azure;
using Microsoft.Spectrum.Storage.Table.Azure.DataAccessLayer;
using Microsoft.Spectrum.Storage.Table.Azure.Helpers;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
public class MeasurementStationService : IMeasurementStationService
{
private RetryMessageQueue workerQueue = null;
private RetryMessageQueue healthReportQueue = null;
private RetryAzureTableOperations<MeasurementStationsPublic> measurementStationPublicTableContext;
private ILogger logger;
// NB: There is no default constructor necessary since an instance of the object will be provided by the container (via the MeasurementStationServiceInstanceProvider).
public MeasurementStationService(CloudStorageAccount storageAccount, string queueName, AzureServiceBusQueue azureServiceBusQueue)
{
if (storageAccount == null)
{
throw new ArgumentNullException("storageAccount");
}
if (azureServiceBusQueue == null)
{
throw new ArgumentNullException("AzureServiceBusQueue", "AzureServiceBusQueue instance can't be null");
}
this.logger = new AzureLogger();
var queueRetryStrategy = new FixedInterval(3, TimeSpan.FromSeconds(1));
var queueRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(queueRetryStrategy);
IMessageQueue azureInputQueue = new AzureMessageQueue(queueName, storageAccount, false);
this.workerQueue = new RetryMessageQueue(azureInputQueue, queueRetryPolicy);
IMessageQueue azureHealthReportQueue = azureServiceBusQueue;
this.healthReportQueue = new RetryMessageQueue(azureHealthReportQueue, queueRetryPolicy);
var tableRetryStrategy = new FixedInterval(3, TimeSpan.FromSeconds(1));
var tableRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(tableRetryStrategy);
AzureTableDbContext azureTableDbContext = new AzureTableDbContext(storageAccount, tableRetryPolicy);
this.measurementStationPublicTableContext = azureTableDbContext.PublicMeasurementStationsOperations;
this.measurementStationPublicTableContext.GetTableReference(AzureTableHelper.MeasurementStationsPublicTable);
SpectrumDataStorageAccountsTableOperations.Instance.Initialize(azureTableDbContext);
}
public int GetStationAvailability(string measurementStationAccessId)
{
if (string.IsNullOrWhiteSpace(measurementStationAccessId))
{
throw new ArgumentException("MeasurementStationAccessId can't be null or empty", "measurementStationAccessId");
}
MeasurementStationsPublic publicStation = this.measurementStationPublicTableContext.GetByKeys<MeasurementStationsPublic>(Constants.DummyPartitionKey, measurementStationAccessId).FirstOrDefault();
if (publicStation == null)
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format("Invalid station access id :{0}, couldn't able to obtain information for this station", measurementStationAccessId));
throw new ArgumentException("Invalid MeasurementStationAccessId");
}
return publicStation.StationAvailability;
}
public void GetUpdatedSettings(string measurementStationAccessId, out string storageAccountName, out string storageAccessKey, out byte[] measurementStationConfiguration)
{
MeasurementStationsPublic publicStation = this.measurementStationPublicTableContext.GetByKeys<MeasurementStationsPublic>(Constants.DummyPartitionKey, measurementStationAccessId).FirstOrDefault();
if (publicStation != null)
{
CloudStorageAccount account = SpectrumDataStorageAccountsTableOperations.Instance.GetCloudStorageAccountByName(publicStation.SpectrumDataStorageAccountName);
if (account != null)
{
try
{
// create the blob container for this measurement station if it doesn't exist
CloudBlobClient blob = account.CreateCloudBlobClient();
CloudBlobContainer container = blob.GetContainerReference(measurementStationAccessId);
container.CreateIfNotExists(BlobContainerPublicAccessType.Container);
// create a write only shared access policy that lasts for one year
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Write,
SharedAccessExpiryTime = DateTime.UtcNow.AddYears(1),
};
BlobContainerPermissions blobPermissions = new BlobContainerPermissions();
blobPermissions.PublicAccess = BlobContainerPublicAccessType.Container;
blobPermissions.SharedAccessPolicies.Add("measurement station write policy", policy);
container.SetPermissions(blobPermissions);
// return both the account name and the SAS key so that the measurement station can then write to the blob storage
storageAccountName = container.Uri.AbsoluteUri;
storageAccessKey = container.GetSharedAccessSignature(null, "measurement station write policy");
measurementStationConfiguration = publicStation.ClientEndToEndConfiguration;
// Set the station to be online
if (publicStation.StationAvailability != (int)Microsoft.Spectrum.Storage.Enums.StationAvailability.Decommissioned)
{
publicStation.StationAvailability = (int)Microsoft.Spectrum.Storage.Enums.StationAvailability.Online;
}
this.measurementStationPublicTableContext.InsertOrReplaceEntity(publicStation, true);
}
catch (Exception ex)
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format(CultureInfo.InvariantCulture, "There was an error in GetUpdatedSettings for measurement station {0} in storage account {1}, Exception: {2}", measurementStationAccessId, account.Credentials.AccountName, ex.ToString()));
throw;
}
}
else
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format(CultureInfo.InvariantCulture, "The storage account for this measurement station {0} can not be found.", measurementStationAccessId));
throw new InvalidOperationException("The storage account for this measurement station can not be found.");
}
}
else
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format(CultureInfo.InvariantCulture, "The measurement station {0} can not be found.", measurementStationAccessId));
throw new ArgumentException("The measurement station id can not be found.", "measurementStationAccessId");
}
}
public void ScanFileUploaded(string measurementStationAccessId, string blobUri, bool success)
{
try
{
MeasurementStationsPublic publicStation = this.measurementStationPublicTableContext.GetByKeys<MeasurementStationsPublic>(Constants.DummyPartitionKey, measurementStationAccessId).FirstOrDefault();
if (publicStation == null)
{
System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;
MessageProperties oMessageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty clientMachine = (RemoteEndpointMessageProperty)oMessageProperties[RemoteEndpointMessageProperty.Name];
string error = string.Format("Invalid station id:{0} reported, blob uri:{1}, blob upload status :{2}, Message sent by Client:{3},Port:{4}", measurementStationAccessId, blobUri, success, clientMachine.Address, clientMachine.Port);
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, error);
throw new InvalidOperationException(string.Format("Invalid MeasurementStationAccessId :{0}", measurementStationAccessId));
}
// Do a little validation on the incoming parameters before even queueing them up, so that we catch these errors as early as possible
Uri blob = new Uri(blobUri);
Guid measurementStation = Guid.Parse(measurementStationAccessId);
// Queue up this file for processing
WorkerQueueMessage queueMessage = new WorkerQueueMessage(MessageType.FileProcessing, measurementStationAccessId, blobUri, success);
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.TypeNameHandling = TypeNameHandling.All;
this.workerQueue.PutMessage(JsonConvert.SerializeObject(queueMessage, jss));
}
catch (Exception ex)
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format(CultureInfo.InvariantCulture, "There was an error in ScanFileUploaded, Measurement station: {0}, Blob Uri: {1}, Success: {2}, Exception: {3}", measurementStationAccessId, blobUri, success, ex.ToString()));
throw;
}
}
public void ReportHealthStatus(string measurementStationAccessId, int healthStatus, int messagePriority, string title, string description, DateTime occurredAt)
{
try
{
HealthReportQueueMessage queueMessage = new HealthReportQueueMessage((StationHealthStatus)healthStatus, measurementStationAccessId, title, description, occurredAt);
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.TypeNameHandling = TypeNameHandling.All;
this.healthReportQueue.PutMessage(JsonConvert.SerializeObject(queueMessage, jss), messagePriority);
}
catch (Exception ex)
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format(CultureInfo.InvariantCulture, "There was an error processing HealtReport message, Measurement station {0}, Title:{1}, Descripton :{2}, Exception:{3}", measurementStationAccessId, title, description, ex.ToString()));
throw;
}
}
public int GetHealthStatusCheckInterval(string meaurementStationAccessId)
{
try
{
MeasurementStationsPublic publicStation = this.measurementStationPublicTableContext.GetByKeys<MeasurementStationsPublic>(Constants.DummyPartitionKey, meaurementStationAccessId).FirstOrDefault();
return publicStation != null ? publicStation.ClientHealthStatusCheckIntervalInMin : 0;
}
catch (Exception ex)
{
this.logger.Log(TraceEventType.Error, LoggingMessageId.MeasurementStationService, string.Format(CultureInfo.InvariantCulture, "There was an while obtaining Health Check Interval, Measurement station {0},Exception:{2}", meaurementStationAccessId, ex.ToString()));
throw;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using NUnit.Framework;
namespace c24.Deputy.Checks
{
public class ReferenceExistsCheck_Tests
{
public class Given_an_existing_reference
{
private readonly BinaryReference reference;
private readonly ReferenceExistsCheck check;
public Given_an_existing_reference()
{
this.reference = new BinaryReference
{
Name = "test",
Path = "test.dll",
FullPath = "test.dll",
Referrer = "project"
};
var fileSystemMock = new MockFileSystem(new Dictionary<string, MockFileData>
{
{"test.dll", new MockFileData(String.Empty)}
});
this.check = new ReferenceExistsCheck(fileSystemMock);
}
[Test]
public void It_should_be_satisfied()
{
Assert.IsTrue(this.check.IsSatisfiedBy(this.reference));
}
[Test]
public void It_should_return_is_ok_on_report()
{
var report = this.check.Report(this.reference);
Assert.IsTrue(report.IsOk);
}
[Test]
public void It_should_return_given_reference_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreSame(this.reference, report.Reference);
}
[Test]
public void It_should_return_ok_message_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreEqual(ReportSeverity.Info, report.Message.Severity);
}
[Test]
public void It_should_return_ok_description_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreEqual("Ok.", report.Message.Description);
}
}
public class Given_a_non_existent_reference
{
private readonly ReferenceExistsCheck check;
private readonly BinaryReference reference;
public Given_a_non_existent_reference()
{
this.reference = new BinaryReference
{
Name = "test",
Path = "test.dll",
FullPath = "test.dll",
Referrer = "project"
};
var fileSystemMock = new MockFileSystem(new Dictionary<string, MockFileData>
{
{"another.dll", new MockFileData(String.Empty)}
});
this.check = new ReferenceExistsCheck(fileSystemMock);
}
[Test]
public void It_should_not_be_satisfied()
{
Assert.IsFalse(this.check.IsSatisfiedBy(this.reference));
}
[Test]
public void It_should_return_global_reference_as_report_source()
{
var report = this.check.Report(this.reference);
Assert.AreEqual("ExistsReferenceCheck", report.Source);
}
[Test]
public void It_should_return_not_ok_on_report()
{
var report = this.check.Report(this.reference);
Assert.IsFalse(report.IsOk);
}
[Test]
public void It_should_return_given_reference_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreSame(this.reference, report.Reference);
}
[Test]
public void It_should_return_error_message_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreEqual(ReportSeverity.Error, report.Message.Severity);
}
[Test]
public void It_should_return_error_description_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreEqual("The project 'project' references 'test'. It doesn't exist here: 'test.dll'.", report.Message.Description);
}
}
public class Given_a_non_existent_project_in_a_solution_file
{
private readonly ReferenceExistsCheck check;
private readonly ProjectReference reference;
public Given_a_non_existent_project_in_a_solution_file()
{
this.reference = new ProjectReference
{
Name = "test",
Path = "test.proj",
FullPath = "test.proj",
Referrer = "sol",
SourceType = ReferenceSourceType.Solution
};
var fileSystemMock = new MockFileSystem(new Dictionary<string, MockFileData>
{
{"another.proj", new MockFileData(String.Empty)}
});
this.check = new ReferenceExistsCheck(fileSystemMock);
}
[Test]
public void It_should_return_solution_based_error_description_on_report()
{
var report = this.check.Report(this.reference);
Assert.AreEqual("The solution 'sol' references 'test'. It doesn't exist here: 'test.proj'.", report.Message.Description);
}
}
public class Given_an_existing_reference_relative_to_project_path
{
[Test]
public void It_should_be_satisfied()
{
var reference = new BinaryReference
{
Name = "test",
Path = Path.Combine("..", "test.dll"),
FullPath = Path.GetFullPath(Path.Combine("root", "test.dll"))
};
var fileSystemMock = new MockFileSystem(new Dictionary<string, MockFileData>
{
{Path.GetFullPath(Path.Combine("root", "test.dll")), new MockFileData(String.Empty)}
});
var check = new ReferenceExistsCheck(fileSystemMock);
Assert.IsTrue(check.IsSatisfiedBy(reference));
}
}
public class Given_a_reference_to_gac_without_path
{
[Test]
public void It_should_not_be_satisfied()
{
var reference = new BinaryReference
{
Name = "system",
Path = null,
FullPath = null
};
var fileSystemMock = new MockFileSystem(new Dictionary<string, MockFileData>());
var check = new ReferenceExistsCheck(fileSystemMock);
Assert.IsFalse(check.IsSatisfiedBy(reference));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Orders;
using Nop.Services.Catalog.Cache;
using Nop.Services.Customers;
using Nop.Services.Discounts;
namespace Nop.Services.Catalog
{
/// <summary>
/// Price calculation service
/// </summary>
public partial class PriceCalculationService : IPriceCalculationService
{
#region Fields
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly IDiscountService _discountService;
private readonly ICategoryService _categoryService;
private readonly IManufacturerService _manufacturerService;
private readonly IProductAttributeParser _productAttributeParser;
private readonly IProductService _productService;
private readonly ICacheManager _cacheManager;
private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly CatalogSettings _catalogSettings;
#endregion
#region Ctor
public PriceCalculationService(IWorkContext workContext,
IStoreContext storeContext,
IDiscountService discountService,
ICategoryService categoryService,
IManufacturerService manufacturerService,
IProductAttributeParser productAttributeParser,
IProductService productService,
ICacheManager cacheManager,
ShoppingCartSettings shoppingCartSettings,
CatalogSettings catalogSettings)
{
this._workContext = workContext;
this._storeContext = storeContext;
this._discountService = discountService;
this._categoryService = categoryService;
this._manufacturerService = manufacturerService;
this._productAttributeParser = productAttributeParser;
this._productService = productService;
this._cacheManager = cacheManager;
this._shoppingCartSettings = shoppingCartSettings;
this._catalogSettings = catalogSettings;
}
#endregion
#region Nested classes
[Serializable]
protected class ProductPriceForCaching
{
public decimal Price { get; set; }
public decimal AppliedDiscountAmount { get; set; }
public int AppliedDiscountId { get; set; }
}
#endregion
#region Utilities
/// <summary>
/// Gets allowed discounts applied to product
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">Customer</param>
/// <returns>Discounts</returns>
protected virtual IList<Discount> GetAllowedDiscountsAppliedToProduct(Product product, Customer customer)
{
var allowedDiscounts = new List<Discount>();
if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
if (product.HasDiscountsApplied)
{
//we use this property ("HasDiscountsApplied") for performance optimziation to avoid unnecessary database calls
foreach (var discount in product.AppliedDiscounts)
{
if (_discountService.ValidateDiscount(discount, customer).IsValid &&
discount.DiscountType == DiscountType.AssignedToSkus &&
!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
}
}
return allowedDiscounts;
}
/// <summary>
/// Gets allowed discounts applied to categories
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">Customer</param>
/// <returns>Discounts</returns>
protected virtual IList<Discount> GetAllowedDiscountsAppliedToCategories(Product product, Customer customer)
{
var allowedDiscounts = new List<Discount>();
if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
foreach (var discount in _discountService.GetAllDiscounts(DiscountType.AssignedToCategories))
{
//load identifier of categories with this discount applied to
var cacheKey = string.Format(PriceCacheEventConsumer.DISCOUNT_CATEGORY_IDS_MODEL_KEY,
discount.Id,
string.Join(",", customer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var appliedToCategoryIds = _cacheManager.Get(cacheKey, () =>
{
var categoryIds = new List<int>();
foreach (var category in discount.AppliedToCategories)
{
if (!categoryIds.Contains(category.Id))
categoryIds.Add(category.Id);
if (discount.AppliedToSubCategories)
{
//include subcategories
foreach (var childCategoryId in _categoryService
.GetAllCategoriesByParentCategoryId(category.Id, false, true)
.Select(x => x.Id))
{
if (!categoryIds.Contains(childCategoryId))
categoryIds.Add(childCategoryId);
}
}
}
return categoryIds;
});
//compare with categories of this product
if (appliedToCategoryIds.Any())
{
//load identifier of categories with this discount applied to
var cacheKey2 = string.Format(PriceCacheEventConsumer.DISCOUNT_PRODUCT_CATEGORY_IDS_MODEL_KEY,
product.Id,
string.Join(",", customer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categoryIds = _cacheManager.Get(cacheKey2, () =>
_categoryService
.GetProductCategoriesByProductId(product.Id)
.Select(x => x.CategoryId)
.ToList());
foreach (var id in categoryIds)
{
if (appliedToCategoryIds.Contains(id))
{
if (_discountService.ValidateDiscount(discount, customer).IsValid &&
discount.DiscountType == DiscountType.AssignedToCategories &&
!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
}
}
}
}
return allowedDiscounts;
}
/// <summary>
/// Gets allowed discounts applied to manufacturers
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">Customer</param>
/// <returns>Discounts</returns>
protected virtual IList<Discount> GetAllowedDiscountsAppliedToManufacturers(Product product, Customer customer)
{
var allowedDiscounts = new List<Discount>();
if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
foreach (var discount in _discountService.GetAllDiscounts(DiscountType.AssignedToManufacturers))
{
//load identifier of categories with this discount applied to
var cacheKey = string.Format(PriceCacheEventConsumer.DISCOUNT_MANUFACTURER_IDS_MODEL_KEY,
discount.Id,
string.Join(",", customer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var appliedToManufacturerIds = _cacheManager.Get(cacheKey,
() => discount.AppliedToManufacturers.Select(x => x.Id).ToList());
//compare with manufacturers of this product
if (appliedToManufacturerIds.Any())
{
//load identifier of categories with this discount applied to
var cacheKey2 = string.Format(PriceCacheEventConsumer.DISCOUNT_PRODUCT_MANUFACTURER_IDS_MODEL_KEY,
product.Id,
string.Join(",", customer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var manufacturerIds = _cacheManager.Get(cacheKey2, () =>
_manufacturerService
.GetProductManufacturersByProductId(product.Id)
.Select(x => x.ManufacturerId)
.ToList());
foreach (var id in manufacturerIds)
{
if (appliedToManufacturerIds.Contains(id))
{
if (_discountService.ValidateDiscount(discount, customer).IsValid &&
discount.DiscountType == DiscountType.AssignedToManufacturers &&
!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
}
}
}
}
return allowedDiscounts;
}
/// <summary>
/// Gets allowed discounts
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">Customer</param>
/// <returns>Discounts</returns>
protected virtual IList<Discount> GetAllowedDiscounts(Product product, Customer customer)
{
var allowedDiscounts = new List<Discount>();
if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
//discounts applied to products
foreach (var discount in GetAllowedDiscountsAppliedToProduct(product, customer))
if (!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
//discounts applied to categories
foreach (var discount in GetAllowedDiscountsAppliedToCategories(product, customer))
if (!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
//discounts applied to manufacturers
foreach (var discount in GetAllowedDiscountsAppliedToManufacturers(product, customer))
if (!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
return allowedDiscounts;
}
/// <summary>
/// Gets a tier price
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">Customer</param>
/// <param name="quantity">Quantity</param>
/// <returns>Price</returns>
protected virtual decimal? GetMinimumTierPrice(Product product, Customer customer, int quantity)
{
if (!product.HasTierPrices)
return decimal.Zero;
var tierPrices = product.TierPrices
.OrderBy(tp => tp.Quantity)
.ToList()
.FilterByStore(_storeContext.CurrentStore.Id)
.FilterForCustomer(customer)
.RemoveDuplicatedQuantities();
int previousQty = 1;
decimal? previousPrice = null;
foreach (var tierPrice in tierPrices)
{
//check quantity
if (quantity < tierPrice.Quantity)
continue;
if (tierPrice.Quantity < previousQty)
continue;
//save new price
previousPrice = tierPrice.Price;
previousQty = tierPrice.Quantity;
}
return previousPrice;
}
/// <summary>
/// Gets discount amount
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">The customer</param>
/// <param name="productPriceWithoutDiscount">Already calculated product price without discount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Discount amount</returns>
protected virtual decimal GetDiscountAmount(Product product,
Customer customer,
decimal productPriceWithoutDiscount,
out Discount appliedDiscount)
{
if (product == null)
throw new ArgumentNullException("product");
appliedDiscount = null;
decimal appliedDiscountAmount = decimal.Zero;
//we don't apply discounts to products with price entered by a customer
if (product.CustomerEntersPrice)
return appliedDiscountAmount;
//discounts are disabled
if (_catalogSettings.IgnoreDiscounts)
return appliedDiscountAmount;
var allowedDiscounts = GetAllowedDiscounts(product, customer);
//no discounts
if (allowedDiscounts.Count == 0)
return appliedDiscountAmount;
appliedDiscount = allowedDiscounts.GetPreferredDiscount(productPriceWithoutDiscount);
if (appliedDiscount != null)
appliedDiscountAmount = appliedDiscount.GetDiscountAmount(productPriceWithoutDiscount);
return appliedDiscountAmount;
}
#endregion
#region Methods
/// <summary>
/// Gets the final price
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">The customer</param>
/// <param name="additionalCharge">Additional charge</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
/// <param name="quantity">Shopping cart item quantity</param>
/// <returns>Final price</returns>
public virtual decimal GetFinalPrice(Product product,
Customer customer,
decimal additionalCharge = decimal.Zero,
bool includeDiscounts = true,
int quantity = 1)
{
decimal discountAmount;
Discount appliedDiscount;
return GetFinalPrice(product, customer, additionalCharge, includeDiscounts,
quantity, out discountAmount, out appliedDiscount);
}
/// <summary>
/// Gets the final price
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">The customer</param>
/// <param name="additionalCharge">Additional charge</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
/// <param name="quantity">Shopping cart item quantity</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Final price</returns>
public virtual decimal GetFinalPrice(Product product,
Customer customer,
decimal additionalCharge,
bool includeDiscounts,
int quantity,
out decimal discountAmount,
out Discount appliedDiscount)
{
return GetFinalPrice(product, customer,
additionalCharge, includeDiscounts, quantity,
null, null,
out discountAmount, out appliedDiscount);
}
/// <summary>
/// Gets the final price
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">The customer</param>
/// <param name="additionalCharge">Additional charge</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
/// <param name="quantity">Shopping cart item quantity</param>
/// <param name="rentalStartDate">Rental period start date (for rental products)</param>
/// <param name="rentalEndDate">Rental period end date (for rental products)</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Final price</returns>
public virtual decimal GetFinalPrice(Product product,
Customer customer,
decimal additionalCharge,
bool includeDiscounts,
int quantity,
DateTime? rentalStartDate,
DateTime? rentalEndDate,
out decimal discountAmount,
out Discount appliedDiscount)
{
if (product == null)
throw new ArgumentNullException("product");
discountAmount = decimal.Zero;
appliedDiscount = null;
var cacheKey = string.Format(PriceCacheEventConsumer.PRODUCT_PRICE_MODEL_KEY,
product.Id,
additionalCharge.ToString(CultureInfo.InvariantCulture),
includeDiscounts,
quantity,
string.Join(",", customer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var cacheTime = _catalogSettings.CacheProductPrices ? 60 : 0;
//we do not cache price for rental products
//otherwise, it can cause memory leaks (to store all possible date period combinations)
if (product.IsRental)
cacheTime = 0;
var cachedPrice = _cacheManager.Get(cacheKey, cacheTime, () =>
{
var result = new ProductPriceForCaching();
//initial price
decimal price = product.Price;
//special price
var specialPrice = product.GetSpecialPrice();
if (specialPrice.HasValue)
price = specialPrice.Value;
//tier prices
if (product.HasTierPrices)
{
decimal? tierPrice = GetMinimumTierPrice(product, customer, quantity);
if (tierPrice.HasValue)
price = Math.Min(price, tierPrice.Value);
}
//additional charge
price = price + additionalCharge;
//rental products
if (product.IsRental)
if (rentalStartDate.HasValue && rentalEndDate.HasValue)
price = price * product.GetRentalPeriods(rentalStartDate.Value, rentalEndDate.Value);
if (includeDiscounts)
{
//discount
Discount tmpAppliedDiscount;
decimal tmpDiscountAmount = GetDiscountAmount(product, customer, price, out tmpAppliedDiscount);
price = price - tmpDiscountAmount;
if (tmpAppliedDiscount != null)
{
result.AppliedDiscountId = tmpAppliedDiscount.Id;
result.AppliedDiscountAmount = tmpDiscountAmount;
}
}
if (price < decimal.Zero)
price = decimal.Zero;
result.Price = price;
return result;
});
if (includeDiscounts)
{
//Discount instance cannnot be cached between requests (when "catalogSettings.CacheProductPrices" is "true)
//This is limitation of Entity Framework
//That's why we load it here after working with cache
appliedDiscount = _discountService.GetDiscountById(cachedPrice.AppliedDiscountId);
if (appliedDiscount != null)
{
discountAmount = cachedPrice.AppliedDiscountAmount;
}
}
return cachedPrice.Price;
}
/// <summary>
/// Gets the shopping cart unit price (one item)
/// </summary>
/// <param name="shoppingCartItem">The shopping cart item</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
/// <returns>Shopping cart unit price (one item)</returns>
public virtual decimal GetUnitPrice(ShoppingCartItem shoppingCartItem,
bool includeDiscounts = true)
{
decimal discountAmount;
Discount appliedDiscount;
return GetUnitPrice(shoppingCartItem, includeDiscounts,
out discountAmount, out appliedDiscount);
}
/// <summary>
/// Gets the shopping cart unit price (one item)
/// </summary>
/// <param name="shoppingCartItem">The shopping cart item</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Shopping cart unit price (one item)</returns>
public virtual decimal GetUnitPrice(ShoppingCartItem shoppingCartItem,
bool includeDiscounts,
out decimal discountAmount,
out Discount appliedDiscount)
{
if (shoppingCartItem == null)
throw new ArgumentNullException("shoppingCartItem");
return GetUnitPrice(shoppingCartItem.Product,
shoppingCartItem.Customer,
shoppingCartItem.ShoppingCartType,
shoppingCartItem.Quantity,
shoppingCartItem.AttributesXml,
shoppingCartItem.CustomerEnteredPrice,
shoppingCartItem.RentalStartDateUtc,
shoppingCartItem.RentalEndDateUtc,
includeDiscounts,
out discountAmount,
out appliedDiscount);
}
/// <summary>
/// Gets the shopping cart unit price (one item)
/// </summary>
/// <param name="product">Product</param>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="quantity">Quantity</param>
/// <param name="attributesXml">Product atrributes (XML format)</param>
/// <param name="customerEnteredPrice">Customer entered price (if specified)</param>
/// <param name="rentalStartDate">Rental start date (null for not rental products)</param>
/// <param name="rentalEndDate">Rental end date (null for not rental products)</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Shopping cart unit price (one item)</returns>
public virtual decimal GetUnitPrice(Product product,
Customer customer,
ShoppingCartType shoppingCartType,
int quantity,
string attributesXml,
decimal customerEnteredPrice,
DateTime? rentalStartDate, DateTime? rentalEndDate,
bool includeDiscounts,
out decimal discountAmount,
out Discount appliedDiscount)
{
if (product == null)
throw new ArgumentNullException("product");
if (customer == null)
throw new ArgumentNullException("customer");
discountAmount = decimal.Zero;
appliedDiscount = null;
decimal finalPrice;
var combination = _productAttributeParser.FindProductAttributeCombination(product, attributesXml);
if (combination != null && combination.OverriddenPrice.HasValue)
{
finalPrice = combination.OverriddenPrice.Value;
}
else
{
//summarize price of all attributes
decimal attributesTotalPrice = decimal.Zero;
var attributeValues = _productAttributeParser.ParseProductAttributeValues(attributesXml);
if (attributeValues != null)
{
foreach (var attributeValue in attributeValues)
{
attributesTotalPrice += GetProductAttributeValuePriceAdjustment(attributeValue);
}
}
//get price of a product (with previously calculated price of all attributes)
if (product.CustomerEntersPrice)
{
finalPrice = customerEnteredPrice;
}
else
{
int qty;
if (_shoppingCartSettings.GroupTierPricesForDistinctShoppingCartItems)
{
//the same products with distinct product attributes could be stored as distinct "ShoppingCartItem" records
//so let's find how many of the current products are in the cart
qty = customer.ShoppingCartItems
.Where(x => x.ProductId == product.Id)
.Where(x => x.ShoppingCartType == shoppingCartType)
.Sum(x => x.Quantity);
if (qty == 0)
{
qty = quantity;
}
}
else
{
qty = quantity;
}
finalPrice = GetFinalPrice(product,
customer,
attributesTotalPrice,
includeDiscounts,
qty,
product.IsRental ? rentalStartDate : null,
product.IsRental ? rentalEndDate : null,
out discountAmount, out appliedDiscount);
}
}
//rounding
if (_shoppingCartSettings.RoundPricesDuringCalculation)
finalPrice = RoundingHelper.RoundPrice(finalPrice);
return finalPrice;
}
/// <summary>
/// Gets the shopping cart item sub total
/// </summary>
/// <param name="shoppingCartItem">The shopping cart item</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
/// <returns>Shopping cart item sub total</returns>
public virtual decimal GetSubTotal(ShoppingCartItem shoppingCartItem,
bool includeDiscounts = true)
{
decimal discountAmount;
Discount appliedDiscount;
return GetSubTotal(shoppingCartItem, includeDiscounts, out discountAmount, out appliedDiscount);
}
/// <summary>
/// Gets the shopping cart item sub total
/// </summary>
/// <param name="shoppingCartItem">The shopping cart item</param>
/// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Shopping cart item sub total</returns>
public virtual decimal GetSubTotal(ShoppingCartItem shoppingCartItem,
bool includeDiscounts,
out decimal discountAmount,
out Discount appliedDiscount)
{
if (shoppingCartItem == null)
throw new ArgumentNullException("shoppingCartItem");
decimal subTotal;
//unit price
var unitPrice = GetUnitPrice(shoppingCartItem, includeDiscounts,
out discountAmount, out appliedDiscount);
//discount
if (appliedDiscount != null)
{
if (appliedDiscount.MaximumDiscountedQuantity.HasValue &&
shoppingCartItem.Quantity > appliedDiscount.MaximumDiscountedQuantity.Value)
{
//we cannot apply discount for all shopping cart items
var discountedQuantity = appliedDiscount.MaximumDiscountedQuantity.Value;
var discountedSubTotal = unitPrice * discountedQuantity;
discountAmount = discountAmount * discountedQuantity;
var notDiscountedQuantity = shoppingCartItem.Quantity - discountedQuantity;
var notDiscountedUnitPrice = GetUnitPrice(shoppingCartItem, false);
var notDiscountedSubTotal = notDiscountedUnitPrice*notDiscountedQuantity;
subTotal = discountedSubTotal + notDiscountedSubTotal;
}
else
{
//discount is applied to all items (quantity)
//calculate discount amount for all items
discountAmount = discountAmount * shoppingCartItem.Quantity;
subTotal = unitPrice * shoppingCartItem.Quantity;
}
}
else
{
subTotal = unitPrice * shoppingCartItem.Quantity;
}
return subTotal;
}
/// <summary>
/// Gets the product cost (one item)
/// </summary>
/// <param name="product">Product</param>
/// <param name="attributesXml">Shopping cart item attributes in XML</param>
/// <returns>Product cost (one item)</returns>
public virtual decimal GetProductCost(Product product, string attributesXml)
{
if (product == null)
throw new ArgumentNullException("product");
decimal cost = product.ProductCost;
var attributeValues = _productAttributeParser.ParseProductAttributeValues(attributesXml);
foreach (var attributeValue in attributeValues)
{
switch (attributeValue.AttributeValueType)
{
case AttributeValueType.Simple:
{
//simple attribute
cost += attributeValue.Cost;
}
break;
case AttributeValueType.AssociatedToProduct:
{
//bundled product
var associatedProduct = _productService.GetProductById(attributeValue.AssociatedProductId);
if (associatedProduct != null)
cost += associatedProduct.ProductCost * attributeValue.Quantity;
}
break;
default:
break;
}
}
return cost;
}
/// <summary>
/// Get a price adjustment of a product attribute value
/// </summary>
/// <param name="value">Product attribute value</param>
/// <returns>Price adjustment</returns>
public virtual decimal GetProductAttributeValuePriceAdjustment(ProductAttributeValue value)
{
if (value == null)
throw new ArgumentNullException("value");
var adjustment = decimal.Zero;
switch (value.AttributeValueType)
{
case AttributeValueType.Simple:
{
//simple attribute
adjustment = value.PriceAdjustment;
}
break;
case AttributeValueType.AssociatedToProduct:
{
//bundled product
var associatedProduct = _productService.GetProductById(value.AssociatedProductId);
if (associatedProduct != null)
{
adjustment = GetFinalPrice(associatedProduct, _workContext.CurrentCustomer, includeDiscounts: true) * value.Quantity;
}
}
break;
default:
break;
}
return adjustment;
}
#endregion
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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.Reflection;
using MindTouch.Xml;
namespace MindTouch.Dream {
internal static class CoreUtil {
//--- Constants ---
internal const byte PADDING_BYTE = 32;
//--- Methods ---
internal static XDoc ExecuteCommand(Plug env, DreamHeaders headers, XDoc cmd) {
try {
switch(cmd.Name.ToLowerInvariant()) {
case "script":
return ExecuteScript(env, headers, cmd);
case "fork":
return ExecuteFork(env, headers, cmd);
case "action":
return ExecuteAction(env, headers, cmd);
case "pipe":
return ExecutePipe(env, headers, cmd);
default:
throw new DreamException(string.Format("unregonized script command: " + cmd.Name));
}
} catch(Exception e) {
return new XException(e);
}
}
internal static XDoc ExecuteScript(Plug env, DreamHeaders headers, XDoc script) {
// execute script commands
XDoc reply = new XDoc("results");
string ID = script["@ID"].Contents;
if(!string.IsNullOrEmpty(ID)) {
reply.Attr("ID", ID);
}
foreach(XDoc cmd in script.Elements) {
reply.Add(ExecuteCommand(env, headers, cmd));
}
return reply;
}
internal static XDoc ExecuteFork(Plug env, DreamHeaders headers, XDoc fork) {
// execute script commands
XDoc reply = new XDoc("results");
string ID = fork["@ID"].Contents;
if(!string.IsNullOrEmpty(ID)) {
reply.Attr("ID", ID);
}
// TODO (steveb): we should use a 'fixed capacity' cue which marks itself as done when 'count' is reached
XDoc forks = fork.Elements;
foreach(XDoc cmd in forks) {
// TODO (steveb): we should be doing this in parallel, not sequentially!
try {
reply.Add(ExecuteCommand(env, headers, cmd));
} catch(Exception e) {
reply.Add(new XException(e));
}
}
return reply;
}
#if WARN_ON_SYNC
[Obsolete("This method is thread-blocking. Please avoid using it if possible.")]
#endif
/// <summary>
/// WARNING: This method is thread-blocking. Please avoid using it if possible.
/// </summary>
internal static XDoc ExecuteAction(Plug env, DreamHeaders headers, XDoc action) {
string verb = action["@verb"].Contents;
string path = action["@path"].Contents;
if((path.Length > 0) && (path[0] == '/')) {
path = path.Substring(1);
}
XUri uri;
if(!XUri.TryParse(path, out uri)) {
uri = env.Uri.AtAbsolutePath(path);
}
// create message
DreamMessage message = DreamMessage.Ok(GetActionBody(action));
message.Headers.AddRange(headers);
// apply headers
foreach(XDoc header in action["header"]) {
message.Headers[header["@name"].Contents] = header.Contents;
}
// BUG #814: we need to support events
// execute action
DreamMessage reply = Plug.New(uri).Invoke(verb, message);
// prepare response
XDoc result = new XMessage(reply);
string ID = action["@ID"].Contents;
if(!string.IsNullOrEmpty(ID)) {
result.Root.Attr("ID", ID);
}
return result;
}
#if WARN_ON_SYNC
[Obsolete("This method is thread-blocking. Please avoid using it if possible.")]
#endif
/// <summary>
/// WARNING: This method is thread-blocking. Please avoid using it if possible.
/// </summary>
internal static XDoc ExecutePipe(Plug env, DreamHeaders headers, XDoc pipe) {
DreamMessage message = null;
foreach(XDoc action in pipe["action"]) {
string verb = action["@verb"].Contents;
string path = action["@path"].Contents;
XUri uri;
if(!XUri.TryParse(path, out uri)) {
uri = env.Uri.AtPath(path);
}
// create first message
if(message == null) {
message = DreamMessage.Ok(GetActionBody(action));
}
message.Headers.AddRange(headers);
// apply headers
foreach(XDoc header in action["header"]) {
message.Headers[header["@name"].Contents] = header.Contents;
}
// execute action
message = Plug.New(uri).Invoke(verb, message);
if(!message.IsSuccessful) {
break;
}
}
// prepare response
if(message == null) {
return XDoc.Empty;
}
XDoc result = new XMessage(message);
string ID = pipe["@ID"].Contents;
if(!string.IsNullOrEmpty(ID)) {
result.Root.Attr("ID", ID);
}
return result;
}
internal static XDoc GetActionBody(XDoc action) {
XDoc result = action["body"];
if(!result.IsEmpty) {
// check if the body tag contains a nested element
if(!result.Elements.IsEmpty) {
result = result[0];
}
} else {
// select the last child element of the <action> element
result = action["*[last()]"];
}
return result;
}
internal static Type FindBuiltInTypeBySID(XUri sid) {
Assembly assembly = Assembly.GetCallingAssembly();
foreach(Type type in assembly.GetTypes()) {
DreamServiceAttribute attr = (DreamServiceAttribute)Attribute.GetCustomAttribute(type, typeof(DreamServiceAttribute), false);
XUri[] sids = (attr != null) ? attr.GetSIDAsUris() : new XUri[0];
if(sids.Length > 0) {
foreach(XUri tmp in sids) {
if(tmp == sid) {
return type;
}
}
}
}
return null;
}
}
}
| |
// TODO this file has moved
//
//
// Copyright (c) 2010-2014 Frank A. Krueger
//
// 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 Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using System.Drawing; // TODO do we need this?
using System.Collections.Generic;
using MonoTouch.CoreGraphics;
using MonoTouch.UIKit;
using MonoTouch.CoreText;
using MonoTouch.Foundation;
namespace XFGraphics.CoreGraphics
{
public class CoreGraphicsGraphics : IGraphics
{
CGContext _c;
//bool _highQuality = false;
static CoreGraphicsGraphics ()
{
//foreach (var f in UIFont.FamilyNames) {
// Console.WriteLine (f);
// var fs = UIFont.FontNamesForFamilyName (f);
// foreach (var ff in fs) {
// Console.WriteLine (" " + ff);
// }
//}
_textMatrix = CGAffineTransform.MakeScale (1, -1); // TODO what is this for?
}
private float _overall_height;
private Stack<float> _prev_overall_height;
public CoreGraphicsGraphics (CGContext c, bool highQuality, float overall_height)
{
if (c == null) throw new ArgumentNullException ("c");
_overall_height = (float) overall_height;
_c = c;
//_highQuality = highQuality;
if (highQuality) {
c.SetLineCap (CGLineCap.Round);
}
else {
c.SetLineCap (CGLineCap.Butt);
}
SetColor (Xamarin.Forms.Color.Black);
}
public void SetColor (Xamarin.Forms.Color c)
{
var clr = c.ToCGColor ();
#if MONOMAC
_c.SetFillColorWithColor (cgcol);
_c.SetStrokeColorWithColor (cgcol);
#else
_c.SetFillColor (clr);
_c.SetStrokeColor (clr);
#endif
}
public void Clear (Xamarin.Forms.Color color)
{
_c.ClearRect (_c.GetClipBoundingBox ());
}
public void FillPolygon (Polygon poly)
{
var count = poly.Points.Count;
_c.MoveTo ((float) poly.Points[0].X, (float) poly.Points[0].Y);
for (var i = 1; i < count; i++) {
var p = poly.Points[i];
_c.AddLineToPoint ((float) p.X, (float) p.Y);
}
_c.FillPath ();
}
public void DrawPolygon (Polygon poly, float w)
{
_c.SetLineWidth (w);
_c.SetLineJoin (CGLineJoin.Round);
_c.MoveTo ((float) poly.Points[0].X, (float) poly.Points[0].Y);
for (var i = 1; i < poly.Points.Count; i++) {
var p = poly.Points[i];
_c.AddLineToPoint ((float) p.X, (float) p.Y);
}
_c.ClosePath ();
_c.StrokePath ();
}
public void FillRoundedRect (float x, float y, float width, float height, float radius)
{
_c.AddRoundedRect (new RectangleF (x, y, width, height), radius);
_c.FillPath ();
}
public void DrawRoundedRect (float x, float y, float width, float height, float radius, float w)
{
_c.SetLineWidth (w);
_c.AddRoundedRect (new RectangleF (x, y, width, height), radius);
_c.StrokePath ();
}
public void FillRect (float x, float y, float width, float height)
{
_c.FillRect (new RectangleF (x, y, width, height));
}
public void FillOval (float x, float y, float width, float height)
{
_c.FillEllipseInRect (new RectangleF (x, y, width, height));
}
public void DrawOval (float x, float y, float width, float height, float w)
{
_c.SetLineWidth (w);
_c.StrokeEllipseInRect (new RectangleF (x, y, width, height));
}
public void DrawRect (float x, float y, float width, float height, float w)
{
_c.SetLineWidth (w);
_c.StrokeRect (new RectangleF (x, y, width, height));
}
public void DrawArc (float cx, float cy, float radius, float startAngle, float endAngle, float w)
{
_c.SetLineWidth (w);
_c.AddArc (cx, cy, radius, -startAngle, -endAngle, true);
_c.StrokePath ();
}
public void FillArc (float cx, float cy, float radius, float startAngle, float endAngle)
{
_c.AddArc (cx, cy, radius, -startAngle, -endAngle, true);
_c.FillPath ();
}
const int _linePointsCount = 1024;
PointF[] _linePoints = new PointF[_linePointsCount];
bool _linesBegun = false;
int _numLinePoints = 0;
float _lineWidth = 1;
bool _lineRounded = false;
public void BeginLines (bool rounded)
{
_linesBegun = true;
_lineRounded = rounded;
_numLinePoints = 0;
}
public void DrawLine (float sx, float sy, float ex, float ey, float w)
{
#if not
#if DEBUG
if (float.IsNaN (sx) || float.IsNaN (sy) || float.IsNaN (ex) || float.IsNaN (ey) || float.IsNaN (w)) {
System.Diagnostics.Debug.WriteLine ("NaN in CoreGraphicsGraphics.DrawLine");
}
#endif
#endif
if (_linesBegun) {
_lineWidth = w;
if (_numLinePoints < _linePointsCount) {
if (_numLinePoints == 0) {
_linePoints[_numLinePoints].X = sx;
_linePoints[_numLinePoints].Y = sy;
_numLinePoints++;
}
_linePoints[_numLinePoints].X = ex;
_linePoints[_numLinePoints].Y = ey;
_numLinePoints++;
}
} else {
_c.MoveTo (sx, sy);
_c.AddLineToPoint (ex, ey);
_c.SetLineWidth (w);
_c.StrokePath ();
}
}
public void EndLines ()
{
if (!_linesBegun)
return;
_c.SaveState ();
_c.SetLineJoin (_lineRounded ? CGLineJoin.Round : CGLineJoin.Miter);
_c.SetLineWidth (_lineWidth);
for (var i = 0; i < _numLinePoints; i++) {
var p = _linePoints[i];
if (i == 0) {
_c.MoveTo (p.X, p.Y);
} else {
_c.AddLineToPoint (p.X, p.Y);
}
}
_c.StrokePath ();
_c.RestoreState ();
_linesBegun = false;
}
static CGAffineTransform _textMatrix;
Xamarin.Forms.Font _font_xf = Font.Default;
UIFont _font_ui = null;
CTFont _font_ct = null;
CTStringAttributes _ct_attr = null;
public void SetFont (Xamarin.Forms.Font f)
{
_font_xf = f;
// We have a Xamarin.Forms.Font object. We need a CTFont. X.F.Font has
// ToUIFont() but not a Core Text version of same. So we make a UIFont first.
_font_ui = _font_xf.ToUIFont ();
_font_ct = new CTFont (_font_ui.Name, _font_ui.PointSize);
// With Core Text, it is important that we use a CTStringAttributes() with the
// NSAttributedString constructor.
// TODO maybe we should have the text color be separate, have it be an arg on SetFont?
_ct_attr = new CTStringAttributes {
Font = _font_ct,
ForegroundColorFromContext = true,
//ForegroundColor = _clr_cg,
// ParagraphStyle = new CTParagraphStyle(new CTParagraphStyleSettings() { Alignment = CTTextAlignment.Center })
};
}
#if not
void SelectFont ()
{
_c.SetFont (CGFont.CreateWithFontName (_lastFont.FontFamily));
_c.SetFontSize (_lastFont.FontSize);
_c.SetFont (_lastFont.ToUIFont());
_c.TextMatrix = _textMatrix;
}
#endif
#if not
static Dictionary<string, byte[]> _stringFixups = new Dictionary<string, byte[]>();
byte[] FixupString (string s)
{
byte[] fix;
if (_stringFixups.TryGetValue (s, out fix)) {
return fix;
}
else {
var n = s.Length;
var bad = false;
for (var i = 0; i < n && !bad; i++) {
bad = ((int)s[i] > 127);
}
if (bad) {
fix = MacRomanEncoding.GetBytes (s.Replace ("\u03A9", "Ohm"));
_stringFixups [s] = fix;
return fix;
}
else {
return null;
}
}
}
#endif
public void SetClippingRect (float x, float y, float width, float height)
{
_c.ClipToRect (new RectangleF (x, y, width, height));
}
// TODO using Core Text here is going to be a huge problem because we have to
// change the coordinate system for every call to DrawString rather than changing
// it once for all the calls. Not even sure we have enough info (the height of
// the coord system or UIView) to do the transform?
// TODO if we know the text is one-line, we can skip the big transform and just use
// the textmatrix thing.
public void DrawString(string s,
float box_x,
float box_y,
float box_width,
float box_height,
Xamarin.Forms.LineBreakMode lineBreak,
Xamarin.Forms.TextAlignment horizontal_align,
Xamarin.Forms.TextAlignment vertical_align
)
{
_c.SaveState();
// TODO _c.SetTextDrawingMode (CGTextDrawingMode.Fill);
// Core Text uses a different coordinate system.
_c.TranslateCTM (0, _overall_height);
_c.ScaleCTM (1, -1);
var attributedString = new NSAttributedString (s, _ct_attr);
float text_width;
float text_height;
if (
(horizontal_align != TextAlignment.Start)
|| (vertical_align != TextAlignment.Start)) {
// not all of the alignments need the bounding rect. don't
// calculate it if not needed.
var sizeAttr = attributedString.GetBoundingRect (
new SizeF (
(float)box_width,
int.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading,
null
);
text_width = sizeAttr.Width;
//text_height = sizeAttr.Height;
//text_height = sizeAttr.Height + uif.Descender; // descender is negative
text_height = _font_ui.CapHeight;
} else {
text_width = 0;
text_height = 0;
}
//Console.WriteLine ("width: {0} height: {1}", text_width, text_height);
float x;
switch (horizontal_align) {
case Xamarin.Forms.TextAlignment.End:
x = (box_x + box_width) - text_width;
break;
case Xamarin.Forms.TextAlignment.Center:
x = box_x + (box_width - text_width) / 2;
break;
case Xamarin.Forms.TextAlignment.Start:
default:
x = box_x;
break;
}
float y;
switch (vertical_align) {
case Xamarin.Forms.TextAlignment.End:
y = box_y + text_height;
break;
case Xamarin.Forms.TextAlignment.Center:
y = (box_y + box_height) - (box_height - text_height) / 2;
break;
case Xamarin.Forms.TextAlignment.Start:
default:
y = (box_y + box_height);
break;
}
_c.TextPosition = new PointF ((float) x, (float) (_overall_height - y));
// I think that by using CTLine() below, we are preventing multi-line text. :-(
using (var textLine = new CTLine (attributedString)) {
textLine.Draw (_c);
}
//gctx.StrokeRect (new RectangleF(x, height - y, text_width, text_height));
_c.RestoreState ();
}
#if not
public void DrawString (string s, float x, float y)
{
var attributedString = new NSAttributedString (s, _ct_attr);
_c.TextPosition = new PointF ((float) x, (float) /*height -*/ y);
// I think that by using CTLine() below, we are preventing multi-line text. :-(
using (var textLine = new CTLine (attributedString)) {
textLine.Draw (_c);
}
}
public void DrawString (string s, float x, float y, float width, float height, LineBreakMode lineBreak, TextAlignment align)
{
if (_lastFont == null) return;
var fm = GetFontMetrics ();
var fix = FixupString (s);
var xx = x;
var yy = y;
if (align == TextAlignment.Center) {
xx = (x + width / 2) - (fm.StringWidth (s) / 2);
}
else if (align == TextAlignment.Right) {
xx = (x + width) - fm.StringWidth (s);
}
if (fix == null) {
_c.ShowTextAtPoint (xx, yy + fm.Height, s);
}
else {
_c.ShowTextAtPoint (xx, yy + fm.Height, fix);
}
}
#endif
#if not
public IFontMetrics GetFontMetrics ()
{
var f = _lastFont;
if (f == null) throw new InvalidOperationException ("Cannot call GetFontMetrics before calling SetFont.");
var fm = f.Tag as CoreGraphicsFontMetrics;
if (fm == null) {
fm = new CoreGraphicsFontMetrics ();
f.Tag = fm;
}
if (fm.Widths == null) {
fm.MeasureText (_c, _lastFont);
}
return fm;
}
#endif
public void DrawImage (IImage img, float x, float y)
{
if (img is UIKitImage) {
var uiImg = ((UIKitImage)img).Image;
uiImg.Draw (new PointF ((float) x, (float) y));
}
}
public void DrawImage (IImage img, float x, float y, float width, float height)
{
if (img is UIKitImage) {
var uiImg = ((UIKitImage)img).Image;
uiImg.Draw (new RectangleF ((float)x, (float)y, (float)width, (float)height));
}
}
public void SaveState ()
{
_c.SaveState ();
}
public void Translate (float dx, float dy)
{
_c.TranslateCTM ((float) dx, (float) dy);
}
public void Scale (float sx, float sy)
{
_c.ScaleCTM ((float) sx, (float) sy);
}
public void RestoreState ()
{
_c.RestoreState ();
// TODO do anything to the font?
}
public IImage ImageFromFile (string filename)
{
// TODO don't hard-code the path stuff below
return new UIKitImage (UIImage.FromFile ("Images/" + filename));
}
public void BeginOffscreen(float width, float height, IImage img)
{
// iOS apparently cannot re-use an image for offscreen draws
if (img != null) {
img.Destroy ();
}
UIGraphics.BeginImageContextWithOptions (new SizeF ((float)width, (float)height), false, 0);
if (_prev_overall_height == null) {
_prev_overall_height = new Stack<float> ();
}
_prev_overall_height.Push (_overall_height);
_overall_height = (float)height;
_c = UIGraphics.GetCurrentContext ();
}
public IImage EndOffscreen()
{
UIImage img = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();
_overall_height = _prev_overall_height.Pop ();
_c = UIGraphics.GetCurrentContext();
return new UIKitImage(img);
}
public void BeginEntity (object entity)
{
}
}
#if not
public static class ColorEx
{
class ColorTag {
#if MONOMAC
public NSColor NSColor;
#else
public UIColor UIColor;
#endif
public CGColor CGColor;
}
#if MONOMAC
public static NSColor GetNSColor (this Color c)
{
var t = c.Tag as ColorTag;
if (t == null) {
t = new ColorTag ();
c.Tag = t;
}
if (t.NSColor == null) {
t.NSColor = NSColor.FromDeviceRgba (c.Red / 255.0f, c.Green / 255.0f, c.Blue / 255.0f, c.Alpha / 255.0f);
}
return t.NSColor;
}
#else
public static UIColor GetUIColor (this Color c)
{
var t = c.Tag as ColorTag;
if (t == null) {
t = new ColorTag ();
c.Tag = t;
}
if (t.UIColor == null) {
t.UIColor = UIColor.FromRGBA (c.Red / 255.0f, c.Green / 255.0f, c.Blue / 255.0f, c.Alpha / 255.0f);
}
return t.UIColor;
}
#endif
public static CGColor GetCGColor (this Color c)
{
var t = c.Tag as ColorTag;
if (t == null) {
t = new ColorTag ();
c.Tag = t;
}
if (t.CGColor == null) {
t.CGColor = new CGColor (c.Red / 255.0f, c.Green / 255.0f, c.Blue / 255.0f, c.Alpha / 255.0f);
}
return t.CGColor;
}
}
public static class FontEx
{
/*public static UIFont CreateUIFont (this Font f)
{
if (f.FontFamily == "") {
return UIFont.FromName (f.FontFamily, f.Size);
}
else {
if ((f.Options & FontOptions.Bold) != 0) {
return UIFont.BoldSystemFontOfSize (f.Size);
}
else {
return UIFont.SystemFontOfSize (f.Size);
}
}
}*/
/*public static CTFont GetCTFont (this Font f)
{
var t = f.Tag as CTFont;
if (t == null) {
if (f.Options == FontOptions.Bold) {
t = new CTFont ("Helvetica-Bold", f.Size);
} else {
t = new CTFont ("Helvetica", f.Size);
}
f.Tag = t;
}
return t;
}*/
}
#endif
public class UIKitImage : IImage
{
#if not
public CGImage Image { get; private set; }
public UIKitImage (CGImage image)
{
Image = image;
}
#endif
public UIImage Image { get; private set; }
public UIKitImage(UIImage img)
{
Image = img;
}
public void Destroy()
{
Image.Dispose ();
Image = null;
}
}
#if not
public class CoreGraphicsFontMetrics : IFontMetrics
{
int _height;
public float[] Widths;
const float DefaultWidth = 8.0f;
public void MeasureText (CGContext c, Font f)
{
// Console.WriteLine ("MEASURE {0}", f);
c.SetTextDrawingMode (CGTextDrawingMode.Invisible);
c.TextPosition = new PointF(0, 0);
c.ShowText ("MM");
var mmWidth = c.TextPosition.X;
_height = f.FontSize - 5;
Widths = new float[0x80];
for (var i = ' '; i < 127; i++) {
var s = "M" + ((char)i).ToString() + "M";
c.TextPosition = new PointF(0, 0);
c.ShowText (s);
var sz = c.TextPosition.X - mmWidth;
if (sz < 0.1f) {
Widths = null;
return;
}
Widths[i] = sz;
}
c.SetTextDrawingMode (CGTextDrawingMode.Fill);
}
public CoreGraphicsFontMetrics ()
{
}
public int StringWidth (string str, int startIndex, int length)
{
if (str == null) return 0;
var end = startIndex + str.Length;
if (end <= 0) return 0;
if (Widths == null) {
return 0;
}
var w = 0.0f;
for (var i = startIndex; i < end; i++) {
var ch = (int)str[i];
if (ch < Widths.Length) {
w += Widths[ch];
}
else {
w += DefaultWidth;
}
}
return (int)(w + 0.5f);
}
public int Height
{
get {
return _height;
}
}
public int Ascent
{
get {
return Height;
}
}
public int Descent
{
get {
return 0;
}
}
}
#endif
public static class CGContextEx
{
#if not
#if !MONOMAC
[System.Runtime.InteropServices.DllImport (MonoTouch.Constants.CoreGraphicsLibrary)]
extern static void CGContextShowTextAtPoint(IntPtr c, float x, float y, byte[] bytes, int size_t_length);
public static void ShowTextAtPoint (this CGContext c, float x, float y, byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException ("bytes");
CGContextShowTextAtPoint (c.Handle, x, y, bytes, bytes.Length);
}
#endif
#endif
public static void AddRoundedRect (this CGContext c, RectangleF b, float r)
{
c.MoveTo (b.Left, b.Top + r);
c.AddLineToPoint (b.Left, b.Bottom - r);
c.AddArc (b.Left + r, b.Bottom - r, r, (float)(Math.PI), (float)(Math.PI / 2), true);
c.AddLineToPoint (b.Right - r, b.Bottom);
c.AddArc (b.Right - r, b.Bottom - r, r, (float)(-3 * Math.PI / 2), (float)(0), true);
c.AddLineToPoint (b.Right, b.Top + r);
c.AddArc (b.Right - r, b.Top + r, r, (float)(0), (float)(-Math.PI / 2), true);
c.AddLineToPoint (b.Left + r, b.Top);
c.AddArc (b.Left + r, b.Top + r, r, (float)(-Math.PI / 2), (float)(Math.PI), true);
}
public static void AddBottomRoundedRect (this CGContext c, RectangleF b, float r)
{
c.MoveTo (b.Left, b.Top + r);
c.AddLineToPoint (b.Left, b.Bottom - r);
c.AddArc (b.Left + r, b.Bottom - r, r, (float)(Math.PI), (float)(Math.PI / 2), true);
c.AddLineToPoint (b.Right - r, b.Bottom);
c.AddArc (b.Right - r, b.Bottom - r, r, (float)(-3 * Math.PI / 2), (float)(0), true);
c.AddLineToPoint (b.Right, b.Top);
c.AddLineToPoint (b.Left, b.Top);
}
}
#if not
public class MacRomanEncoding {
static Dictionary<int, byte> _uniToMac= new Dictionary<int, byte>() {
{160, 202}, {161, 193}, {162, 162}, {163, 163}, {165, 180}, {167, 164}, {168, 172}, {169,
169}, {170, 187}, {171, 199}, {172, 194}, {174, 168}, {175, 248}, {176, 161}, {177, 177},
{180, 171}, {181, 181}, {182, 166}, {183, 225}, {184, 252}, {186, 188}, {187, 200}, {191,
192}, {192, 203}, {193, 231}, {194, 229}, {195, 204}, {196, 128}, {197, 129}, {198, 174},
{199, 130}, {200, 233}, {201, 131}, {202, 230}, {203, 232}, {204, 237}, {205, 234}, {206,
235}, {207, 236}, {209, 132}, {210, 241}, {211, 238}, {212, 239}, {213, 205}, {214, 133},
{216, 175}, {217, 244}, {218, 242}, {219, 243}, {220, 134}, {223, 167}, {224, 136}, {225,
135}, {226, 137}, {227, 139}, {228, 138}, {229, 140}, {230, 190}, {231, 141}, {232, 143},
{233, 142}, {234, 144}, {235, 145}, {236, 147}, {237, 146}, {238, 148}, {239, 149}, {241,
150}, {242, 152}, {243, 151}, {244, 153}, {245, 155}, {246, 154}, {247, 214}, {248, 191},
{249, 157}, {250, 156}, {251, 158}, {252, 159}, {255, 216}, {305, 245}, {338, 206}, {339,
207}, {376, 217}, {402, 196}, {710, 246}, {711, 255}, {728, 249}, {729, 250}, {730, 251},
{731, 254}, {732, 247}, {733, 253}, {937, 189}, {960, 185}, {8211, 208}, {8212, 209},
{8216, 212}, {8217, 213}, {8218, 226}, {8220, 210}, {8221, 211}, {8222, 227}, {8224, 160},
{8225, 224}, {8226, 165}, {8230, 201}, {8240, 228}, {8249, 220}, {8250, 221}, {8260, 218},
{8364, 219}, {8482, 170}, {8706, 182}, {8710, 198}, {8719, 184}, {8721, 183}, {8730, 195},
{8734, 176}, {8747, 186}, {8776, 197}, {8800, 173}, {8804, 178}, {8805, 179}, {9674, 215},
{63743, 240}, {64257, 222}, {64258, 223},
};
public static byte[] GetBytes (string str)
{
if (str == null) throw new ArgumentNullException ("str");
var n = str.Length;
var r = new byte [n];
for (var i = 0; i < n; i++) {
var ch = (int)str [i];
var mac = (byte)'?';
if (ch <= 127) {
mac = (byte)ch;
}
else if (_uniToMac.TryGetValue (ch, out mac)) {
}
else {
mac = (byte)'?';
}
r [i] = mac;
}
return r;
}
}
#endif
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Globalization;
namespace PdfSharp.Drawing
{
/// <summary>
/// Represents a value and its unit of measure. The structure converts implicitly from and to
/// double with a value measured in point.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay}")]
public struct XUnit : IFormattable
{
internal const double PointFactor = 1;
internal const double InchFactor = 72;
internal const double MillimeterFactor = 72 / 25.4;
internal const double CentimeterFactor = 72 / 2.54;
internal const double PresentationFactor = 72 / 96.0;
internal const double PointFactorWpf = 96 / 72.0;
internal const double InchFactorWpf = 96;
internal const double MillimeterFactorWpf = 96 / 25.4;
internal const double CentimeterFactorWpf = 96 / 2.54;
internal const double PresentationFactorWpf = 1;
/// <summary>
/// Initializes a new instance of the XUnit class with type set to point.
/// </summary>
public XUnit(double point)
{
_value = point;
_type = XGraphicsUnit.Point;
}
/// <summary>
/// Initializes a new instance of the XUnit class.
/// </summary>
public XUnit(double value, XGraphicsUnit type)
{
if (!Enum.IsDefined(typeof(XGraphicsUnit), type))
#if !SILVERLIGHT && !NETFX_CORE && !UWP
throw new System.ComponentModel.InvalidEnumArgumentException("type");
#else
throw new ArgumentException("type");
#endif
_value = value;
_type = type;
}
/// <summary>
/// Gets the raw value of the object without any conversion.
/// To determine the XGraphicsUnit use property <code>Type</code>.
/// To get the value in point use the implicit conversion to double.
/// </summary>
public double Value
{
get { return _value; }
}
/// <summary>
/// Gets the unit of measure.
/// </summary>
public XGraphicsUnit Type
{
get { return _type; }
}
/// <summary>
/// Gets or sets the value in point.
/// </summary>
public double Point
{
get
{
switch (_type)
{
case XGraphicsUnit.Point:
return _value;
case XGraphicsUnit.Inch:
return _value * 72;
case XGraphicsUnit.Millimeter:
return _value * 72 / 25.4;
case XGraphicsUnit.Centimeter:
return _value * 72 / 2.54;
case XGraphicsUnit.Presentation:
return _value * 72 / 96;
default:
throw new InvalidCastException();
}
}
set
{
_value = value;
_type = XGraphicsUnit.Point;
}
}
/// <summary>
/// Gets or sets the value in inch.
/// </summary>
public double Inch
{
get
{
switch (_type)
{
case XGraphicsUnit.Point:
return _value / 72;
case XGraphicsUnit.Inch:
return _value;
case XGraphicsUnit.Millimeter:
return _value / 25.4;
case XGraphicsUnit.Centimeter:
return _value / 2.54;
case XGraphicsUnit.Presentation:
return _value / 96;
default:
throw new InvalidCastException();
}
}
set
{
_value = value;
_type = XGraphicsUnit.Inch;
}
}
/// <summary>
/// Gets or sets the value in millimeter.
/// </summary>
public double Millimeter
{
get
{
switch (_type)
{
case XGraphicsUnit.Point:
return _value * 25.4 / 72;
case XGraphicsUnit.Inch:
return _value * 25.4;
case XGraphicsUnit.Millimeter:
return _value;
case XGraphicsUnit.Centimeter:
return _value * 10;
case XGraphicsUnit.Presentation:
return _value * 25.4 / 96;
default:
throw new InvalidCastException();
}
}
set
{
_value = value;
_type = XGraphicsUnit.Millimeter;
}
}
/// <summary>
/// Gets or sets the value in centimeter.
/// </summary>
public double Centimeter
{
get
{
switch (_type)
{
case XGraphicsUnit.Point:
return _value * 2.54 / 72;
case XGraphicsUnit.Inch:
return _value * 2.54;
case XGraphicsUnit.Millimeter:
return _value / 10;
case XGraphicsUnit.Centimeter:
return _value;
case XGraphicsUnit.Presentation:
return _value * 2.54 / 96;
default:
throw new InvalidCastException();
}
}
set
{
_value = value;
_type = XGraphicsUnit.Centimeter;
}
}
/// <summary>
/// Gets or sets the value in presentation units (1/96 inch).
/// </summary>
public double Presentation
{
get
{
switch (_type)
{
case XGraphicsUnit.Point:
return _value * 96 / 72;
case XGraphicsUnit.Inch:
return _value * 96;
case XGraphicsUnit.Millimeter:
return _value * 96 / 25.4;
case XGraphicsUnit.Centimeter:
return _value * 96 / 2.54;
case XGraphicsUnit.Presentation:
return _value;
default:
throw new InvalidCastException();
}
}
set
{
_value = value;
_type = XGraphicsUnit.Point;
}
}
/// <summary>
/// Returns the object as string using the format information.
/// The unit of measure is appended to the end of the string.
/// </summary>
public string ToString(IFormatProvider formatProvider)
{
string valuestring = _value.ToString(formatProvider) + GetSuffix();
return valuestring;
}
/// <summary>
/// Returns the object as string using the specified format and format information.
/// The unit of measure is appended to the end of the string.
/// </summary>
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
string valuestring = _value.ToString(format, formatProvider) + GetSuffix();
return valuestring;
}
/// <summary>
/// Returns the object as string. The unit of measure is appended to the end of the string.
/// </summary>
public override string ToString()
{
string valuestring = _value.ToString(CultureInfo.InvariantCulture) + GetSuffix();
return valuestring;
}
/// <summary>
/// Returns the unit of measure of the object as a string like 'pt', 'cm', or 'in'.
/// </summary>
string GetSuffix()
{
switch (_type)
{
case XGraphicsUnit.Point:
return "pt";
case XGraphicsUnit.Inch:
return "in";
case XGraphicsUnit.Millimeter:
return "mm";
case XGraphicsUnit.Centimeter:
return "cm";
case XGraphicsUnit.Presentation:
return "pu";
//case XGraphicsUnit.Pica:
// return "pc";
//case XGraphicsUnit.Line:
// return "li";
default:
throw new InvalidCastException();
}
}
/// <summary>
/// Returns an XUnit object. Sets type to point.
/// </summary>
public static XUnit FromPoint(double value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Point;
return unit;
}
/// <summary>
/// Returns an XUnit object. Sets type to inch.
/// </summary>
public static XUnit FromInch(double value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Inch;
return unit;
}
/// <summary>
/// Returns an XUnit object. Sets type to millimeters.
/// </summary>
public static XUnit FromMillimeter(double value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Millimeter;
return unit;
}
/// <summary>
/// Returns an XUnit object. Sets type to centimeters.
/// </summary>
public static XUnit FromCentimeter(double value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Centimeter;
return unit;
}
/// <summary>
/// Returns an XUnit object. Sets type to Presentation.
/// </summary>
public static XUnit FromPresentation(double value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Presentation;
return unit;
}
/// <summary>
/// Converts a string to an XUnit object.
/// If the string contains a suffix like 'cm' or 'in' the object will be converted
/// to the appropriate type, otherwise point is assumed.
/// </summary>
public static implicit operator XUnit(string value)
{
XUnit unit;
value = value.Trim();
// HACK for Germans...
value = value.Replace(',', '.');
int count = value.Length;
int valLen = 0;
for (; valLen < count; )
{
char ch = value[valLen];
if (ch == '.' || ch == '-' || ch == '+' || char.IsNumber(ch))
valLen++;
else
break;
}
try
{
unit._value = Double.Parse(value.Substring(0, valLen).Trim(), CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
unit._value = 1;
string message = String.Format("String '{0}' is not a valid value for structure 'XUnit'.", value);
throw new ArgumentException(message, ex);
}
string typeStr = value.Substring(valLen).Trim().ToLower();
unit._type = XGraphicsUnit.Point;
switch (typeStr)
{
case "cm":
unit._type = XGraphicsUnit.Centimeter;
break;
case "in":
unit._type = XGraphicsUnit.Inch;
break;
case "mm":
unit._type = XGraphicsUnit.Millimeter;
break;
case "":
case "pt":
unit._type = XGraphicsUnit.Point;
break;
case "pu": // presentation units
unit._type = XGraphicsUnit.Presentation;
break;
default:
throw new ArgumentException("Unknown unit type: '" + typeStr + "'");
}
return unit;
}
/// <summary>
/// Converts an int to an XUnit object with type set to point.
/// </summary>
public static implicit operator XUnit(int value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Point;
return unit;
}
/// <summary>
/// Converts a double to an XUnit object with type set to point.
/// </summary>
public static implicit operator XUnit(double value)
{
XUnit unit;
unit._value = value;
unit._type = XGraphicsUnit.Point;
return unit;
}
/// <summary>
/// Returns a double value as point.
/// </summary>
public static implicit operator double(XUnit value)
{
return value.Point;
}
/// <summary>
/// Memberwise comparison. To compare by value,
/// use code like Math.Abs(a.Pt - b.Pt) < 1e-5.
/// </summary>
public static bool operator ==(XUnit value1, XUnit value2)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
return value1._type == value2._type && value1._value == value2._value;
// ReSharper restore CompareOfFloatsByEqualityOperator
}
/// <summary>
/// Memberwise comparison. To compare by value,
/// use code like Math.Abs(a.Pt - b.Pt) < 1e-5.
/// </summary>
public static bool operator !=(XUnit value1, XUnit value2)
{
return !(value1 == value2);
}
/// <summary>
/// Calls base class Equals.
/// </summary>
public override bool Equals(Object obj)
{
if (obj is XUnit)
return this == (XUnit)obj;
return false;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
// ReSharper disable NonReadonlyFieldInGetHashCode
return _value.GetHashCode() ^ _type.GetHashCode();
// ReSharper restore NonReadonlyFieldInGetHashCode
}
/// <summary>
/// This member is intended to be used by XmlDomainObjectReader only.
/// </summary>
public static XUnit Parse(string value)
{
XUnit unit = value;
return unit;
}
/// <summary>
/// Converts an existing object from one unit into another unit type.
/// </summary>
public void ConvertType(XGraphicsUnit type)
{
if (_type == type)
return;
switch (type)
{
case XGraphicsUnit.Point:
_value = Point;
_type = XGraphicsUnit.Point;
break;
case XGraphicsUnit.Inch:
_value = Inch;
_type = XGraphicsUnit.Inch;
break;
case XGraphicsUnit.Centimeter:
_value = Centimeter;
_type = XGraphicsUnit.Centimeter;
break;
case XGraphicsUnit.Millimeter:
_value = Millimeter;
_type = XGraphicsUnit.Millimeter;
break;
case XGraphicsUnit.Presentation:
_value = Presentation;
_type = XGraphicsUnit.Presentation;
break;
default:
throw new ArgumentException("Unknown unit type: '" + type + "'");
}
}
/// <summary>
/// Represents a unit with all values zero.
/// </summary>
public static readonly XUnit Zero = new XUnit();
double _value;
XGraphicsUnit _type;
/// <summary>
/// Gets the DebuggerDisplayAttribute text.
/// </summary>
/// <value>The debugger display.</value>
// ReSharper disable UnusedMember.Local
string DebuggerDisplay
// ReSharper restore UnusedMember.Local
{
get
{
const string format = Config.SignificantFigures10;
return String.Format(CultureInfo.InvariantCulture, "unit=({0:" + format + "} {1})", _value, GetSuffix());
}
}
}
}
| |
//////////////////////////////////////////////////////////////////////////////////////
// Author : Shukri Adams //
// Contact : shukri.adams@gmail.com //
// //
// vcFramework : A reuseable library of utility classes //
// Copyright (C) //
//////////////////////////////////////////////////////////////////////////////////////
namespace vcFramework.Parsers
{
/// <summary> Static collection of string manipulation methods
/// primarily used for formatting.</summary>
public class StringFormatLib
{
/// <summary> Mimics behaviour of ASP url encode method.
/// </summary>
public static string UrlEncode(
string strSource
)
{
string strOutput = "";
strOutput = strSource;
//REPLACES SPACES
strOutput = strOutput.Replace(" ", "+");
return strOutput;
}
/// <summary> Indents all lines in a string block with the
/// specified indenter. Can be used to format "reply"
/// messages in emails, as well as forcing a fixed linewidth
/// onto a string block. </summary>
/// <param name="strText"></param>
/// <param name="strIndentCharacter"></param>
/// <param name="intLineLength"></param>
/// <returns></returns>
public static string IndentText(
string strText,
string strIndentCharacter,
int intLineLength
)
{
//INDENTS A BODY OF TEXT AS IN REPLY EMAILS : TEXT IS INDENTED WITH A CHARACTER, AND REARRANGED ACCORDINGLY.
int intLastSpacePosition;
int intLastLineBreakPosition;
string strMessageOrig;
string strLineStretch = "";
string strMessage = "";
strMessageOrig = strText;
while (strMessageOrig.Length > 0)
{
//CHECKS OF THE REMAINING strMessageOrig IS TOO SHORT TO PROCEED. IF SO, ADDS IT TO OUTPUT AND EXITS LOOP
if (strMessageOrig.Length < intLineLength)
{
//CHECKS IF THERE IS A LINEBREAK IN THE REMAIN LENGTH OF strMessageOrig
if (ParserLib.IndexOfFixed(strMessageOrig, "\r\n") != -1)
{
//INDENTS ALL REMAIN LINEBREAKS UNTIL NO strMessageOrig REMAINING
while (ParserLib.StringCount(strMessageOrig, "\r\n") > 0)
{
strMessage = strMessage + strIndentCharacter + strMessageOrig.Substring(0, ParserLib.IndexOfFixed(strMessageOrig, "\r\n")) + "\r\n";
strMessageOrig = strMessageOrig.Substring(ParserLib.IndexOfFixed(strMessageOrig, "\r\n") + 2, strMessageOrig.Length - ParserLib.IndexOfFixed(strMessageOrig, "\r\n") - 2);
}
}
else
{
//IF NO LINE BREAK, SIMPLY DUMPS REMAINING STRING INTO THE OUTPUT
strMessage = strMessage + strIndentCharacter + strMessageOrig;
strMessageOrig = "";
}
}
//IF strMessageOrig LENGTH IS GREATER THATN intLineLength
else
{
//IF LINELENGTH STRETCH HAS A LINEBREAK IN IT
if (ParserLib.IndexOfFixed(strMessageOrig.Substring(0, intLineLength), "\r\n") != -1)
//if (strMessageOrig.Substring(0, intLineLength).IndexOf("\r\n", 0) != -1)
{
//MAKES TEMP COPY OF LINELENTH PIECE, AND REMOVES LINELENGTH PIECE FROM strMessageOrig
intLastLineBreakPosition = strMessageOrig.Substring(0, intLineLength).LastIndexOf("\r\n");
strLineStretch = strMessageOrig.Substring(0, intLastLineBreakPosition + 2);
strMessageOrig = strMessageOrig.Substring(intLastLineBreakPosition + 2, strMessageOrig.Length - intLastLineBreakPosition - 2);
//INDENTS ALL REMAIN LINEBREAKS UNTIL NO strMessageOrig REMAINING
while (ParserLib.StringCount(strLineStretch, "\r\n") > 0)
{
strMessage = strMessage + strIndentCharacter + strLineStretch.Substring(0, ParserLib.IndexOfFixed(strLineStretch, "\r\n")) + "\r\n";
strLineStretch = strLineStretch.Substring(ParserLib.IndexOfFixed(strLineStretch, "\r\n") + 2, strLineStretch.Length - ParserLib.IndexOfFixed(strLineStretch, "\r\n") - 2);
}
}
//IF LINELENGHT STRETCH HAS A SPACE IN IT
else if (ParserLib.IndexOfFixed(strMessageOrig.Substring(0, intLineLength), " ") != -1)
//else if (strMessageOrig.Substring(0, intLineLength).IndexOf(" ", 0) != -1)
{
//IF THERE IS A SPACE SOMEWHERE IN THE LINE TO BE CUT, FINDS IT
intLastSpacePosition = strMessageOrig.Substring(0, intLineLength).LastIndexOf(" ");
strMessage += strIndentCharacter + strMessageOrig.Substring(0, intLastSpacePosition) + "\r\n";
strMessageOrig = strMessageOrig.Substring(intLastSpacePosition + 1, strMessageOrig.Length - intLastSpacePosition - 1); //THE +1 -1 HAS BEEN ADDED TO FACTOR FOR THE " ", WHICH ENDS UP SLIPPING THROUGH ERRONEOUSLY
}
//IF THERE IS NO SPACE OR NO LINEBREAK TO CUT ON, BREAKS THE STRING AT THE STRETCH LENGTH POINT
else
{
//IF NO SPACE, CUT AT MAX LENGTH, AND ADD -
strMessage += strIndentCharacter + strMessageOrig.Substring(0, intLineLength - 1) + "-" + "\r\n";
strMessageOrig = strMessageOrig.Substring(intLineLength - 1, strMessageOrig.Length - intLineLength + 1);
}
}
}
return strMessage;
}
/// <summary>
/// Adds the given padding text to the given main text, until main text reaches the given
/// length. this can be used, for example, to add trailing white space to text to make it
/// fit a given length
/// </summary>
/// <param name="strText"></param>
/// <param name="intTextMaxLength"></param>
/// <returns></returns>
public static string PadText(
string strText,
string strPadder,
int intTextMaxLength
)
{
int intOriginalStrTextLength = strText.Length;
// returns unchanged strText if length is wrong
if (strText.Length >= intTextMaxLength)
return strText;
// adds spaces
for (int i = 0; i < intTextMaxLength - intOriginalStrTextLength; i++)
strText += strPadder;
return strText;
}
/// <summary>
/// Produces a line mae from the strLineBlock text for a given length </summary>
/// <param name="strLineBlock"></param>
/// <param name="intLineLength"></param>
/// <returns></returns>
public static string CharLine(
string strLineBlock,
int intLineLength
)
{
string strOutput = "";
// handles incorrect input
if (strLineBlock.Length == 0 || intLineLength < 1)
return "";
for (int i = 0; i < intLineLength / strLineBlock.Length; i++)
strOutput += strLineBlock;
return strOutput;
}
/// <summary> Removes linebreaks from a string, but will
/// not remove paragraph breaks (double linebreaks)</summary>
/// <param name="strSourceText"></param>
/// <returns></returns>
public static string RemoveLineBreaks(
string strSourceText
)
{
string strVCTemporaryLinebreak = ">vcTemp--LineBreakT--hingie0192---983<";
// 1 - CONVERT PARAGRAPH BREAKS INTO SPECIAL PARAGRAPH BREAK
strSourceText = strSourceText.Replace("\r\n\r\n", strVCTemporaryLinebreak);
//2 - REMOVE ALL REMANING LINEBREAKS
strSourceText = strSourceText.Replace("\r\n", "");
//3 - CONVERT ALL SPECIAL PARAGRAPH BREAK INTO NORMAL PARAGRAPH BREAKS
strSourceText = strSourceText.Replace(strVCTemporaryLinebreak, "\r\n\r\n");
return strSourceText;
}
/// <summary> Converts all non-HTML formatted URLs in a string
/// into HTML-formatted URLS, and returns entire string. </summary>
/// <param name="strInput"></param>
/// <returns></returns>
public static string UrlConvert(
string strInput
)
{
string strOutput = "";
string strURLText = "";
string strCurrentURLStartTag = "";
int intURLStartPosition;
int intURLEndPosition;
//1. STANDARDIZES TEXT
strInput = ParserLib.ReplaceNoCase(strInput, "http://", "http://");
strInput = ParserLib.ReplaceNoCase(strInput, "www.", "www.");
while (strInput.Length > 0)
{
//DETERMINES START TAG OF FIRST URL - NOTE : THIS FEATURE ALLOWS FOR BOTH FULL AND PARTIAL URL START STRINGS ("http://" & "www.") TO BE SUPPORTED
//FIRST, ALLOCATE DEFAULT VALUE
strCurrentURLStartTag = "http://"; //SETS DEFAULT. IF NO DEFAULT SET, AND NO START TAG OCCURS IN STRING, A BLANK LINE WILL BEHAVE LIKE A START TAG
if (strInput.IndexOf("http://") != -1)
{
strCurrentURLStartTag = "http://";
}
else if (strInput.IndexOf("www.") != -1)
{
strCurrentURLStartTag = "www.";
}
if ((strInput.IndexOf("http://") < strInput.IndexOf("www.")) && (strInput.IndexOf("http://") != -1))
{ strCurrentURLStartTag = "http://"; }
if ((strInput.IndexOf("www://") < strInput.IndexOf("http://")) && (strInput.IndexOf("www://") != -1))
{ strCurrentURLStartTag = "www://"; }
intURLStartPosition = strInput.IndexOf(strCurrentURLStartTag); //FINDS WHERE URL STARTS;
intURLEndPosition = strInput.IndexOf(" ", intURLStartPosition + 1); //FINDS WHERE URL ENDS - A SPACE;
if (intURLEndPosition == -1)
{ intURLEndPosition = strInput.Length; } //IF CANNOT FIND AN END OF URL, MAKES TEH END OF THE WHOLE STRING THE END OF THE URL;
if (intURLStartPosition != -1)
{
//ADDS PRE-URL STIRNG TO OUTPUT;
strOutput = strOutput + strInput.Substring(0, intURLStartPosition);
strURLText = strInput.Substring(intURLStartPosition, intURLEndPosition - intURLStartPosition);
if (strCurrentURLStartTag == "www.")
{
//THIS IS REQUIRED TO TURN A PARTIAL URL START INTO A FULL ONE, BUT ONLY IN THE BEHIND-SIDE HTML CODE;
strURLText = "<a href='http:// '" + strURLText + "'>" + strURLText + "</a>";
}
else
{
//THIS IS THE NORMAL MODE;
strURLText = "<a href='" + strURLText + "'>" + strURLText + "</a>";
}
strOutput = strOutput + strURLText;
strInput = strInput.Substring(intURLEndPosition, strInput.Length - intURLEndPosition);
}
else
{
//IF REACH HERE, NO URL STARTER FOUND IN strInput. DUMPS strInput INTO OUTPUT, SETS strInput TO "" AND THUS EXITS LOOP;
strOutput = strOutput + strInput;
strInput = "";
}
}
return strOutput;
}
/// <summary> Truncates a string if it is longer than a
/// specified string, and adds "tail" text to it </summary>
/// <param name="strTheString"></param>
/// <param name="intMaxLength"></param>
/// <param name="strEndString"></param>
/// <returns></returns>
public static string LimitStringLength(
string strTheString,
int intMaxLength,
string strEndString
)
{
if (strTheString.Length > intMaxLength)
return (strTheString.Substring(intMaxLength - strEndString.Length) + strEndString);
return "";
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 the Event Store LLP 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
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using EventStore.Common.Utils;
using EventStore.Projections.Core.Messages;
using EventStore.Projections.Core.Services;
using EventStore.Projections.Core.Services.Processing;
namespace EventStore.Projections.Core.Tests.Services.core_projection
{
public class FakeProjectionStateHandler : IProjectionStateHandler
{
public int _initializeCalled = 0;
public int _initializeSharedCalled = 0;
public int _loadCalled = 0;
public int _eventsProcessed = 0;
public string _loadedState = null;
public string _lastProcessedStreamId;
public string _lastProcessedEventType;
public Guid _lastProcessedEventId;
public int _lastProcessedSequencenumber;
public string _lastProcessedMetadata;
public string _lastProcessedData;
public string _lastPartition;
public const string _emit1Data = @"{""emit"":1}";
public const string _emit2Data = @"{""emit"":2}";
public const string _emit3Data = @"{""emit"":3}";
public const string _emit1StreamId = "/emit1";
public const string _emit2StreamId = "/emit2";
public const string _emit1EventType = "emit1_event_type";
public const string _emit2EventType = "emit2_event_type";
private readonly bool _failOnInitialize;
private readonly bool _failOnLoad;
private readonly bool _failOnProcessEvent;
private readonly bool _failOnGetPartition;
private readonly Action<SourceDefinitionBuilder> _configureBuilder;
private readonly IQuerySources _definition;
public FakeProjectionStateHandler(string source, Action<string> logger)
{
_definition = source.ParseJson<QuerySourcesDefinition>();
}
public FakeProjectionStateHandler(
bool failOnInitialize = false, bool failOnLoad = false, bool failOnProcessEvent = false,
bool failOnGetPartition = true,
Action<SourceDefinitionBuilder> configureBuilder = null)
{
_failOnInitialize = failOnInitialize;
_failOnLoad = failOnLoad;
_failOnProcessEvent = failOnProcessEvent;
_failOnGetPartition = failOnGetPartition;
_configureBuilder = configureBuilder;
}
public void ConfigureSourceProcessingStrategy(SourceDefinitionBuilder builder)
{
if (_configureBuilder != null)
_configureBuilder(builder);
else
{
builder.FromAll();
builder.AllEvents();
builder.SetDefinesStateTransform();
}
}
public void Load(string state)
{
if (_failOnLoad)
throw new Exception("LOAD_FAILED");
_loadCalled++;
_loadedState = state;
}
public void LoadShared(string state)
{
throw new NotImplementedException();
}
public void Initialize()
{
if (_failOnInitialize)
throw new Exception("INITIALIZE_FAILED");
_initializeCalled++;
_loadedState = "";
}
public void InitializeShared()
{
if (_failOnInitialize)
throw new Exception("INITIALIZE_SHARED_FAILED");
_initializeSharedCalled++;
_loadedState = "";
}
public string GetStatePartition(CheckpointTag eventPosition, string category, ResolvedEvent data)
{
if (_failOnGetPartition)
throw new Exception("GetStatePartition FAILED");
return "region-a";
}
public string TransformCatalogEvent(CheckpointTag eventPosition, ResolvedEvent data)
{
throw new NotImplementedException();
}
public bool ProcessEvent(
string partition, CheckpointTag eventPosition, string category1, ResolvedEvent data,
out string newState, out string newSharedState, out EmittedEventEnvelope[] emittedEvents)
{
newSharedState = null;
if (_failOnProcessEvent)
throw new Exception("PROCESS_EVENT_FAILED");
_lastProcessedStreamId = data.EventStreamId;
_lastProcessedEventType = data.EventType;
_lastProcessedEventId = data.EventId;
_lastProcessedSequencenumber = data.EventSequenceNumber;
_lastProcessedMetadata = data.Metadata;
_lastProcessedData = data.Data;
_lastPartition = partition;
_eventsProcessed++;
switch (data.EventType)
{
case "skip_this_type":
newState = null;
emittedEvents = null;
return false;
case "handle_this_type":
_loadedState = newState = data.Data;
emittedEvents = null;
return true;
case "append":
_loadedState = newState = _loadedState + data.Data;
emittedEvents = null;
return true;
case "no_state_emit1_type":
_loadedState = newState = "";
emittedEvents = new[]
{
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit1StreamId, Guid.NewGuid(), _emit1EventType, true, _emit1Data, null, eventPosition, null)),
};
return true;
case "emit1_type":
_loadedState = newState = data.Data;
emittedEvents = new[]
{
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit1StreamId, Guid.NewGuid(), _emit1EventType, true, _emit1Data, null, eventPosition, null)),
};
return true;
case "emit22_type":
_loadedState = newState = data.Data;
emittedEvents = new[]
{
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit2StreamId, Guid.NewGuid(), _emit2EventType, true, _emit1Data, null, eventPosition, null)),
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit2StreamId, Guid.NewGuid(), _emit2EventType, true, _emit2Data, null, eventPosition, null)),
};
return true;
case "emit212_type":
_loadedState = newState = data.Data;
emittedEvents = new[]
{
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit2StreamId, Guid.NewGuid(), _emit2EventType, true, _emit1Data, null, eventPosition, null)),
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit1StreamId, Guid.NewGuid(), _emit1EventType, true, _emit2Data, null, eventPosition, null)),
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit2StreamId, Guid.NewGuid(), _emit2EventType, true, _emit3Data, null, eventPosition, null)),
};
return true;
case "emit12_type":
_loadedState = newState = data.Data;
emittedEvents = new[]
{
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit1StreamId, Guid.NewGuid(), _emit1EventType, true, _emit1Data, null, eventPosition, null)),
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit2StreamId, Guid.NewGuid(), _emit2EventType, true, _emit2Data, null, eventPosition, null)),
};
return true;
case "just_emit":
newState = _loadedState;
emittedEvents = new[]
{
new EmittedEventEnvelope(
new EmittedDataEvent(
_emit1StreamId, Guid.NewGuid(), _emit1EventType, true, _emit1Data, null, eventPosition, null)),
};
return true;
default:
throw new NotSupportedException();
}
}
public string TransformStateToResult()
{
return _loadedState;
}
public void Dispose()
{
}
public IQuerySources GetSourceDefinition()
{
return _definition ?? SourceDefinitionBuilder.From(ConfigureSourceProcessingStrategy);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.