context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// --------------------------------------------------------------------------- // <copyright file="Persona.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the Persona class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; /// <summary> /// Represents a Persona. Properties available on Personas are defined in the PersonaSchema class. /// </summary> [Attachable] [ServiceObjectDefinition(XmlElementNames.Persona)] public class Persona : Item { /// <summary> /// Initializes an unsaved local instance of <see cref="Persona"/>. To bind to an existing Persona, use Persona.Bind() instead. /// </summary> /// <param name="service">The ExchangeService object to which the Persona will be bound.</param> public Persona(ExchangeService service) : base(service) { this.PersonaType = string.Empty; this.CreationTime = null; this.DisplayNameFirstLastHeader = string.Empty; this.DisplayNameLastFirstHeader = string.Empty; this.DisplayName = string.Empty; this.DisplayNameFirstLast = string.Empty; this.DisplayNameLastFirst = string.Empty; this.FileAs = string.Empty; this.Generation = string.Empty; this.DisplayNamePrefix = string.Empty; this.GivenName = string.Empty; this.Surname = string.Empty; this.Title = string.Empty; this.CompanyName = string.Empty; this.ImAddress = string.Empty; this.HomeCity = string.Empty; this.WorkCity = string.Empty; this.Alias = string.Empty; this.RelevanceScore = 0; // Remaining properties are initialized when the property definition is created in // PersonaSchema.cs. } /// <summary> /// Binds to an existing Persona and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the Persona.</param> /// <param name="id">The Id of the Persona to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A Persona instance representing the Persona corresponding to the specified Id.</returns> public static new Persona Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<Persona>(id, propertySet); } /// <summary> /// Binds to an existing Persona and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the Persona.</param> /// <param name="id">The Id of the Persona to bind to.</param> /// <returns>A Persona instance representing the Persona corresponding to the specified Id.</returns> public static new Persona Bind(ExchangeService service, ItemId id) { return Persona.Bind( service, id, PropertySet.FirstClassProperties); } /// <summary> /// Internal method to return the schema associated with this type of object. /// </summary> /// <returns>The schema associated with this type of object.</returns> internal override ServiceObjectSchema GetSchema() { return PersonaSchema.Instance; } /// <summary> /// Gets the minimum required server version. /// </summary> /// <returns>Earliest Exchange version in which this service object type is supported.</returns> internal override ExchangeVersion GetMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2013_SP1; } /// <summary> /// The property definition for the Id of this object. /// </summary> /// <returns>A PropertyDefinition instance.</returns> internal override PropertyDefinition GetIdPropertyDefinition() { return PersonaSchema.PersonaId; } /// <summary> /// Validates this instance. /// </summary> internal override void Validate() { base.Validate(); } #region Properties /// <summary> /// Gets the persona id /// </summary> public ItemId PersonaId { get { return (ItemId)this.PropertyBag[this.GetIdPropertyDefinition()]; } set { this.PropertyBag[this.GetIdPropertyDefinition()] = value; } } /// <summary> /// Gets the persona type /// </summary> public string PersonaType { get { return (string)this.PropertyBag[PersonaSchema.PersonaType]; } set { this.PropertyBag[PersonaSchema.PersonaType] = value; } } /// <summary> /// Gets the creation time of the underlying contact /// </summary> public DateTime? CreationTime { get { return (DateTime?)this.PropertyBag[PersonaSchema.CreationTime]; } set { this.PropertyBag[PersonaSchema.CreationTime] = value; } } /// <summary> /// Gets the header of the FirstLast display name /// </summary> public string DisplayNameFirstLastHeader { get { return (string)this.PropertyBag[PersonaSchema.DisplayNameFirstLastHeader]; } set { this.PropertyBag[PersonaSchema.DisplayNameFirstLastHeader] = value; } } /// <summary> /// Gets the header of the LastFirst display name /// </summary> public string DisplayNameLastFirstHeader { get { return (string)this.PropertyBag[PersonaSchema.DisplayNameLastFirstHeader]; } set { this.PropertyBag[PersonaSchema.DisplayNameLastFirstHeader] = value; } } /// <summary> /// Gets the display name /// </summary> public string DisplayName { get { return (string)this.PropertyBag[PersonaSchema.DisplayName]; } set { this.PropertyBag[PersonaSchema.DisplayName] = value; } } /// <summary> /// Gets the display name in first last order /// </summary> public string DisplayNameFirstLast { get { return (string)this.PropertyBag[PersonaSchema.DisplayNameFirstLast]; } set { this.PropertyBag[PersonaSchema.DisplayNameFirstLast] = value; } } /// <summary> /// Gets the display name in last first order /// </summary> public string DisplayNameLastFirst { get { return (string)this.PropertyBag[PersonaSchema.DisplayNameLastFirst]; } set { this.PropertyBag[PersonaSchema.DisplayNameLastFirst] = value; } } /// <summary> /// Gets the name under which this Persona is filed as. FileAs can be manually set or /// can be automatically calculated based on the value of the FileAsMapping property. /// </summary> public string FileAs { get { return (string)this.PropertyBag[PersonaSchema.FileAs]; } set { this.PropertyBag[PersonaSchema.FileAs] = value; } } /// <summary> /// Gets the generation of the Persona /// </summary> public string Generation { get { return (string)this.PropertyBag[PersonaSchema.Generation]; } set { this.PropertyBag[PersonaSchema.Generation] = value; } } /// <summary> /// Gets the DisplayNamePrefix of the Persona /// </summary> public string DisplayNamePrefix { get { return (string)this.PropertyBag[PersonaSchema.DisplayNamePrefix]; } set { this.PropertyBag[PersonaSchema.DisplayNamePrefix] = value; } } /// <summary> /// Gets the given name of the Persona /// </summary> public string GivenName { get { return (string)this.PropertyBag[PersonaSchema.GivenName]; } set { this.PropertyBag[PersonaSchema.GivenName] = value; } } /// <summary> /// Gets the surname of the Persona /// </summary> public string Surname { get { return (string)this.PropertyBag[PersonaSchema.Surname]; } set { this.PropertyBag[PersonaSchema.Surname] = value; } } /// <summary> /// Gets the Persona's title /// </summary> public string Title { get { return (string)this.PropertyBag[PersonaSchema.Title]; } set { this.PropertyBag[PersonaSchema.Title] = value; } } /// <summary> /// Gets the company name of the Persona /// </summary> public string CompanyName { get { return (string)this.PropertyBag[PersonaSchema.CompanyName]; } set { this.PropertyBag[PersonaSchema.CompanyName] = value; } } /// <summary> /// Gets the email of the persona /// </summary> public PersonaEmailAddress EmailAddress { get { return (PersonaEmailAddress)this.PropertyBag[PersonaSchema.EmailAddress]; } set { this.PropertyBag[PersonaSchema.EmailAddress] = value; } } /// <summary> /// Gets the list of e-mail addresses of the contact /// </summary> public PersonaEmailAddressCollection EmailAddresses { get { return (PersonaEmailAddressCollection)this.PropertyBag[PersonaSchema.EmailAddresses]; } set { this.PropertyBag[PersonaSchema.EmailAddresses] = value; } } /// <summary> /// Gets the IM address of the persona /// </summary> public string ImAddress { get { return (string)this.PropertyBag[PersonaSchema.ImAddress]; } set { this.PropertyBag[PersonaSchema.ImAddress] = value; } } /// <summary> /// Gets the city of the Persona's home /// </summary> public string HomeCity { get { return (string)this.PropertyBag[PersonaSchema.HomeCity]; } set { this.PropertyBag[PersonaSchema.HomeCity] = value; } } /// <summary> /// Gets the city of the Persona's work place /// </summary> public string WorkCity { get { return (string)this.PropertyBag[PersonaSchema.WorkCity]; } set { this.PropertyBag[PersonaSchema.WorkCity] = value; } } /// <summary> /// Gets the alias of the Persona /// </summary> public string Alias { get { return (string)this.PropertyBag[PersonaSchema.Alias]; } set { this.PropertyBag[PersonaSchema.Alias] = value; } } /// <summary> /// Gets the relevance score /// </summary> public int RelevanceScore { get { return (int)this.PropertyBag[PersonaSchema.RelevanceScore]; } set { this.PropertyBag[PersonaSchema.RelevanceScore] = value; } } /// <summary> /// Gets the list of attributions /// </summary> public AttributionCollection Attributions { get { return (AttributionCollection)this.PropertyBag[PersonaSchema.Attributions]; } set { this.PropertyBag[PersonaSchema.Attributions] = value; } } /// <summary> /// Gets the list of office locations /// </summary> public AttributedStringCollection OfficeLocations { get { return (AttributedStringCollection)this.PropertyBag[PersonaSchema.OfficeLocations]; } set { this.PropertyBag[PersonaSchema.OfficeLocations] = value; } } /// <summary> /// Gets the list of IM addresses of the persona /// </summary> public AttributedStringCollection ImAddresses { get { return (AttributedStringCollection)this.PropertyBag[PersonaSchema.ImAddresses]; } set { this.PropertyBag[PersonaSchema.ImAddresses] = value; } } /// <summary> /// Gets the list of departments of the persona /// </summary> public AttributedStringCollection Departments { get { return (AttributedStringCollection)this.PropertyBag[PersonaSchema.Departments]; } set { this.PropertyBag[PersonaSchema.Departments] = value; } } /// <summary> /// Gets the list of photo URLs /// </summary> public AttributedStringCollection ThirdPartyPhotoUrls { get { return (AttributedStringCollection)this.PropertyBag[PersonaSchema.ThirdPartyPhotoUrls]; } set { this.PropertyBag[PersonaSchema.ThirdPartyPhotoUrls] = value; } } #endregion } }
using System; using Csla; using Csla.Data; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using DalEf; using System.Collections.Generic; namespace BusinessObjects.Documents { [Serializable] public partial class cDocuments_Offer_Maturity: CoreBusinessChildClass<cDocuments_Offer_Maturity> { public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.Int32 > documents_OfferIdProperty = RegisterProperty<System.Int32>(p => p.Documents_OfferId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 Documents_OfferId { get { return GetProperty(documents_OfferIdProperty); } set { SetProperty(documents_OfferIdProperty, value); } } private static readonly PropertyInfo<System.Int32> ordinalProperty = RegisterProperty<System.Int32>(p => p.Ordinal, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 Ordinal { get { return GetProperty(ordinalProperty); } set { SetProperty(ordinalProperty, value); } } private static readonly PropertyInfo< System.DateTime > paymentDateProperty = RegisterProperty<System.DateTime>(p => p.PaymentDate, string.Empty,System.DateTime.Now); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.DateTime PaymentDate { get { return GetProperty(paymentDateProperty); } set { SetProperty(paymentDateProperty, value); } } private static readonly PropertyInfo< System.Decimal > paymentAmountProperty = RegisterProperty<System.Decimal>(p => p.PaymentAmount, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Decimal PaymentAmount { get { return GetProperty(paymentAmountProperty); } set { SetProperty(paymentAmountProperty, value); } } private static readonly PropertyInfo<System.Boolean?> invoicedProperty = RegisterProperty<System.Boolean?>(p => p.Invoiced, string.Empty, (System.Boolean?)null); public System.Boolean? Invoiced { get { return GetProperty(invoicedProperty); } set { SetProperty(invoicedProperty, value); } } private static readonly PropertyInfo< System.Int32? > documents_InvoiceIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_InvoiceId, string.Empty,(System.Int32?)null); public System.Int32? Documents_InvoiceId { get { return GetProperty(documents_InvoiceIdProperty); } set { SetProperty(documents_InvoiceIdProperty, value); } } private static readonly PropertyInfo< System.DateTime > lastActivityDateProperty = RegisterProperty<System.DateTime>(p => p.LastActivityDate, string.Empty,System.DateTime.Now); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.DateTime LastActivityDate { get { return GetProperty(lastActivityDateProperty); } set { SetProperty(lastActivityDateProperty, value); } } private static readonly PropertyInfo< System.Int32 > mDSubjects_EmployeeWhoChengedIdProperty = RegisterProperty<System.Int32>(p => p.MDSubjects_EmployeeWhoChengedId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 MDSubjects_EmployeeWhoChengedId { get { return GetProperty(mDSubjects_EmployeeWhoChengedIdProperty); } set { SetProperty(mDSubjects_EmployeeWhoChengedIdProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; internal static cDocuments_Offer_Maturity NewDocuments_Offer_Maturity() { return DataPortal.CreateChild<cDocuments_Offer_Maturity>(); } public static cDocuments_Offer_Maturity GetDocuments_Offer_Maturity(Documents_Offer_MaturityCol data) { return DataPortal.FetchChild<cDocuments_Offer_Maturity>(data); } #region Data Access [RunLocal] protected override void Child_Create() { BusinessRules.CheckRules(); } private void Child_Fetch(Documents_Offer_MaturityCol data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(documents_OfferIdProperty, data.Documents_OfferId); LoadProperty<int>(ordinalProperty, data.Ordinal); LoadProperty<DateTime>(paymentDateProperty, data.PaymentDate); LoadProperty<decimal>(paymentAmountProperty, data.PaymentAmount); LoadProperty<bool?>(invoicedProperty, data.Invoiced); LoadProperty<int?>(documents_InvoiceIdProperty, data.Documents_InvoiceId); LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate); LoadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty, data.MDSubjects_EmployeeWhoChengedId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } private void Child_Insert(Documents_Offer parent) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Offer_MaturityCol(); data.Documents_Offer = parent; data.Ordinal = ReadProperty<int>(ordinalProperty); data.PaymentDate = ReadProperty<DateTime>(paymentDateProperty); data.PaymentAmount = ReadProperty<decimal>(paymentAmountProperty); data.Invoiced = ReadProperty<bool?>(invoicedProperty); data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty); ctx.ObjectContext.AddToDocuments_Offer_MaturityCol(data); data.PropertyChanged += (o, e) => { if (e.PropertyName == "Id") { LoadProperty<int>(IdProperty, data.Id); LoadProperty<int>(documents_OfferIdProperty, data.Documents_OfferId); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LastChanged = data.LastChanged; } }; } } private void Child_Update() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Offer_MaturityCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Ordinal = ReadProperty<int>(ordinalProperty); data.PaymentDate = ReadProperty<DateTime>(paymentDateProperty); data.PaymentAmount = ReadProperty<decimal>(paymentAmountProperty); data.Invoiced = ReadProperty<bool?>(invoicedProperty); data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty); data.PropertyChanged += (o, e) => { if (e.PropertyName == "LastChanged") LastChanged = data.LastChanged; }; } } private void Child_DeleteSelf() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Offer_MaturityCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); ctx.ObjectContext.DeleteObject(data); } } #endregion public void MarkChild() { this.MarkAsChild(); } } [Serializable] public partial class cDocuments_Offer_MaturityCol : BusinessListBase<cDocuments_Offer_MaturityCol, cDocuments_Offer_Maturity> { internal static cDocuments_Offer_MaturityCol NewDocuments_Offer_MaturityCol() { return DataPortal.CreateChild<cDocuments_Offer_MaturityCol>(); } public static cDocuments_Offer_MaturityCol GetDocuments_Offer_MaturityCol(IEnumerable<Documents_Offer_MaturityCol> dataSet) { var childList = new cDocuments_Offer_MaturityCol(); childList.Fetch(dataSet); return childList; } #region Data Access private void Fetch(IEnumerable<Documents_Offer_MaturityCol> dataSet) { RaiseListChangedEvents = false; foreach (var data in dataSet) this.Add(cDocuments_Offer_Maturity.GetDocuments_Offer_Maturity(data)); RaiseListChangedEvents = true; } #endregion //Data Access } }
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.IO; namespace C4F.DevKit.PreviewHandler.PreviewHandlerHost { /// <summary> /// Very simple wrapper class implementation for the IStream interface. /// <remarks>Does not support advanced operations like the Revert() operation, options specified in Commit(), basic stat values, etc.</remarks> /// </summary> internal sealed class StreamWrapper : IStream { #region Constants private const long POSITION_NOT_SET = -1; private const int STG_E_INVALIDFUNCTION = 32774; private const int CHUNK = 4096; private const string METHOD_NOT_SUPPORTED = "Method not supported."; private const string UNKNOWN_ERROR = "Unknown error."; #endregion #region Private Data private long _indexPosition = POSITION_NOT_SET; private readonly Stream _stream = null; #endregion #region Constructor /// <summary> /// Initializes a new instance of the StreamWrapper with the specified input stream. /// </summary> /// <param name="stream">The stream being wrapped.</param> internal StreamWrapper(Stream stream) { _indexPosition = POSITION_NOT_SET; _stream = stream; } #endregion #region IStream Members public void Clone(out IStream ppstm) { // Operation not supported ppstm = null; throw new ExternalException(METHOD_NOT_SUPPORTED, STG_E_INVALIDFUNCTION); } public void Commit(int grfCommitFlags) { _stream.Flush(); } public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten) { byte[] buffer = new byte[CHUNK]; long written = 0; int read = 0; if (cb != 0) { SetSizeToPosition(); do { int count = CHUNK; if (written + CHUNK > cb) { count = (int)(cb - written); } if ((read = _stream.Read(buffer, 0, count)) == 0) { break; } pstm.Write(buffer, read, IntPtr.Zero); written += read; } while (written < cb); } if (pcbRead != IntPtr.Zero) { Marshal.WriteInt64(pcbRead, written); } if (pcbWritten != IntPtr.Zero) { Marshal.WriteInt64(pcbWritten, written); } } public void LockRegion(long libOffset, long cb, int dwLockType) { // Operation not supported throw new ExternalException(METHOD_NOT_SUPPORTED, STG_E_INVALIDFUNCTION); } public void Read(byte[] pv, int cb, IntPtr pcbRead) { int read = 0; if (cb != 0) { SetSizeToPosition(); read = _stream.Read(pv, 0, cb); } if (pcbRead != IntPtr.Zero) { Marshal.WriteInt32(pcbRead, read); } } public void Revert() { throw new ExternalException(METHOD_NOT_SUPPORTED, STG_E_INVALIDFUNCTION); } public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition) { long newPosition = 0; SeekOrigin seekOrigin = SeekOrigin.Begin; try { // attempt to cast parameter seekOrigin = (SeekOrigin)dwOrigin; } catch { throw new ExternalException(UNKNOWN_ERROR, STG_E_INVALIDFUNCTION); } if (_stream.CanWrite) { switch (seekOrigin) { case SeekOrigin.Begin: newPosition = dlibMove; break; case SeekOrigin.Current: newPosition = _indexPosition; if (newPosition == POSITION_NOT_SET) { newPosition = _stream.Position; } newPosition += dlibMove; break; case SeekOrigin.End: newPosition = _stream.Length + dlibMove; break; default: // should never happen throw new ExternalException(UNKNOWN_ERROR, STG_E_INVALIDFUNCTION); } if (newPosition > _stream.Length) { _indexPosition = newPosition; } else { _stream.Position = newPosition; _indexPosition = POSITION_NOT_SET; } } else { try { newPosition = _stream.Seek(dlibMove, seekOrigin); } catch (ArgumentException) { throw new ExternalException(UNKNOWN_ERROR, STG_E_INVALIDFUNCTION); } _indexPosition = POSITION_NOT_SET; } if (plibNewPosition != IntPtr.Zero) { Marshal.WriteInt64(plibNewPosition, newPosition); } } public void SetSize(long libNewSize) { _stream.SetLength(libNewSize); } public void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, int grfStatFlag) { pstatstg = new System.Runtime.InteropServices.ComTypes.STATSTG(); pstatstg.cbSize = _stream.Length; } public void UnlockRegion(long libOffset, long cb, int dwLockType) { // Operation not supported throw new ExternalException(METHOD_NOT_SUPPORTED, STG_E_INVALIDFUNCTION); } public void Write(byte[] pv, int cb, IntPtr pcbWritten) { if (cb != 0) { SetSizeToPosition(); _stream.Write(pv, 0, cb); } if (pcbWritten != IntPtr.Zero) { Marshal.WriteInt32(pcbWritten, cb); } } #endregion #region Private Methods private void SetSizeToPosition() { if (_indexPosition != POSITION_NOT_SET) { // position requested greater than current length? if (_indexPosition > _stream.Length) { // expand stream _stream.SetLength(_indexPosition); } // set new position _stream.Position = _indexPosition; _indexPosition = POSITION_NOT_SET; } } #endregion } }
using System.Diagnostics; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2009 March 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the implementation of the sqlite3_unlock_notify() ** API method and its associated functionality. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c ** ************************************************************************* */ //#include "sqliteInt.h" //#include "btreeInt.h" /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ #if SQLITE_ENABLE_UNLOCK_NOTIFY /* ** Public interfaces: ** ** sqlite3ConnectionBlocked() ** sqlite3ConnectionUnlocked() ** sqlite3ConnectionClosed() ** sqlite3_unlock_notify() */ //#define assertMutexHeld() \ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) /* ** Head of a linked list of all sqlite3 objects created by this process ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection ** is not NULL. This variable may only accessed while the STATIC_MASTER ** mutex is held. */ static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; #if !NDEBUG /* ** This function is a complex assert() that verifies the following ** properties of the blocked connections list: ** ** 1) Each entry in the list has a non-NULL value for either ** pUnlockConnection or pBlockingConnection, or both. ** ** 2) All entries in the list that share a common value for ** xUnlockNotify are grouped together. ** ** 3) If the argument db is not NULL, then none of the entries in the ** blocked connections list have pUnlockConnection or pBlockingConnection ** set to db. This is used when closing connection db. */ static void checkListProperties(sqlite3 *db){ sqlite3 *p; for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ int seen = 0; sqlite3 *p2; /* Verify property (1) */ assert( p->pUnlockConnection || p->pBlockingConnection ); /* Verify property (2) */ for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); assert( db==0 || p->pUnlockConnection!=db ); assert( db==0 || p->pBlockingConnection!=db ); } } } #else //# define checkListProperties(x) #endif /* ** Remove connection db from the blocked connections list. If connection ** db is not currently a part of the list, this function is a no-op. */ static void removeFromBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ if( *pp==db ){ *pp = (*pp)->pNextBlocked; break; } } } /* ** Add connection db to the blocked connections list. It is assumed ** that it is not already a part of the list. */ static void addToBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for( pp=&sqlite3BlockedList; *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; pp=&(*pp)->pNextBlocked ); db->pNextBlocked = *pp; *pp = db; } /* ** Obtain the STATIC_MASTER mutex. */ static void enterMutex(){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); checkListProperties(0); } /* ** Release the STATIC_MASTER mutex. */ static void leaveMutex(){ assertMutexHeld(); checkListProperties(0); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); } /* ** Register an unlock-notify callback. ** ** This is called after connection "db" has attempted some operation ** but has received an SQLITE_LOCKED error because another connection ** (call it pOther) in the same process was busy using the same shared ** cache. pOther is found by looking at db->pBlockingConnection. ** ** If there is no blocking connection, the callback is invoked immediately, ** before this routine returns. ** ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate ** a deadlock. ** ** Otherwise, make arrangements to invoke xNotify when pOther drops ** its locks. ** ** Each call to this routine overrides any prior callbacks registered ** on the same "db". If xNotify==0 then any prior callbacks are immediately ** cancelled. */ int sqlite3_unlock_notify( sqlite3 *db, void (*xNotify)(void **, int), void *pArg ){ int rc = SQLITE_OK; sqlite3_mutex_enter(db->mutex); enterMutex(); if( xNotify==0 ){ removeFromBlockedList(db); db->pUnlockConnection = 0; db->xUnlockNotify = 0; db->pUnlockArg = 0; }else if( 0==db->pBlockingConnection ){ /* The blocking transaction has been concluded. Or there never was a ** blocking transaction. In either case, invoke the notify callback ** immediately. */ xNotify(&pArg, 1); }else{ sqlite3 *p; for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} if( p ){ rc = SQLITE_LOCKED; /* Deadlock detected. */ }else{ db->pUnlockConnection = db->pBlockingConnection; db->xUnlockNotify = xNotify; db->pUnlockArg = pArg; removeFromBlockedList(db); addToBlockedList(db); } } leaveMutex(); assert( !db->mallocFailed ); sqlite3Error(db, rc, (rc?"database is deadlocked":0)); sqlite3_mutex_leave(db->mutex); return rc; } /* ** This function is called while stepping or preparing a statement ** associated with connection db. The operation will return SQLITE_LOCKED ** to the user because it requires a lock that will not be available ** until connection pBlocker concludes its current transaction. */ void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ enterMutex(); if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ addToBlockedList(db); } db->pBlockingConnection = pBlocker; leaveMutex(); } /* ** This function is called when ** the transaction opened by database db has just finished. Locks held ** by database connection db have been released. ** ** This function loops through each entry in the blocked connections ** list and does the following: ** ** 1) If the sqlite3.pBlockingConnection member of a list entry is ** set to db, then set pBlockingConnection=0. ** ** 2) If the sqlite3.pUnlockConnection member of a list entry is ** set to db, then invoke the configured unlock-notify callback and ** set pUnlockConnection=0. ** ** 3) If the two steps above mean that pBlockingConnection==0 and ** pUnlockConnection==0, remove the entry from the blocked connections ** list. */ void sqlite3ConnectionUnlocked(sqlite3 *db){ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ int nArg = 0; /* Number of entries in aArg[] */ sqlite3 **pp; /* Iterator variable */ void **aArg; /* Arguments to the unlock callback */ void **aDyn = 0; /* Dynamically allocated space for aArg[] */ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ aArg = aStatic; enterMutex(); /* Enter STATIC_MASTER mutex */ /* This loop runs once for each entry in the blocked-connections list. */ for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ sqlite3 *p = *pp; /* Step 1. */ if( p->pBlockingConnection==db ){ p->pBlockingConnection = 0; } /* Step 2. */ if( p->pUnlockConnection==db ){ assert( p->xUnlockNotify ); if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ xUnlockNotify(aArg, nArg); nArg = 0; } sqlite3BeginBenignMalloc(); assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); if( (!aDyn && nArg==(int)ArraySize(aStatic)) || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*))) ){ /* The aArg[] array needs to grow. */ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); if( pNew ){ memcpy(pNew, aArg, nArg*sizeof(void *)); //sqlite3_free(aDyn); aDyn = aArg = pNew; }else{ /* This occurs when the array of context pointers that need to ** be passed to the unlock-notify callback is larger than the ** aStatic[] array allocated on the stack and the attempt to ** allocate a larger array from the heap has failed. ** ** This is a difficult situation to handle. Returning an error ** code to the caller is insufficient, as even if an error code ** is returned the transaction on connection db will still be ** closed and the unlock-notify callbacks on blocked connections ** will go unissued. This might cause the application to wait ** indefinitely for an unlock-notify callback that will never ** arrive. ** ** Instead, invoke the unlock-notify callback with the context ** array already accumulated. We can then clear the array and ** begin accumulating any further context pointers without ** requiring any dynamic allocation. This is sub-optimal because ** it means that instead of one callback with a large array of ** context pointers the application will receive two or more ** callbacks with smaller arrays of context pointers, which will ** reduce the applications ability to prioritize multiple ** connections. But it is the best that can be done under the ** circumstances. */ xUnlockNotify(aArg, nArg); nArg = 0; } } sqlite3EndBenignMalloc(); aArg[nArg++] = p->pUnlockArg; xUnlockNotify = p->xUnlockNotify; p->pUnlockConnection = 0; p->xUnlockNotify = 0; p->pUnlockArg = 0; } /* Step 3. */ if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ /* Remove connection p from the blocked connections list. */ *pp = p->pNextBlocked; p->pNextBlocked = 0; }else{ pp = &p->pNextBlocked; } } if( nArg!=0 ){ xUnlockNotify(aArg, nArg); } //sqlite3_free(aDyn); leaveMutex(); /* Leave STATIC_MASTER mutex */ } /* ** This is called when the database connection passed as an argument is ** being closed. The connection is removed from the blocked list. */ void sqlite3ConnectionClosed(sqlite3 *db){ sqlite3ConnectionUnlocked(db); enterMutex(); removeFromBlockedList(db); checkListProperties(db); leaveMutex(); } #endif } }
using System; using System.Data; using org.swyn.foundation.utils; using tdb.DS; namespace tdb { /// <summary> /// Customer. /// - delete first name as soon traveler is done /// </summary> public class Traveler : tdbroot { // person properties (name is code, NO bez) private const int perstyp = 1; // persontype is traveler private int langid; private int staid; // customer properties private string tel; private string handy; private string fax; private string tlx; private string email; private string web; private string account; private int manager; private string attr1; private string attr2; private int custtypid; private int curid; #region init public Traveler() { // // TODO: Add constructor logic here // typ = TableTypes.kunden; bez = ""; bez_id = -1; } #endregion public virtual int ObjLangid { get {return langid;} set {langid = value;} } public virtual int ObjCusttypid { get {return custtypid;} set {custtypid = value;} } public virtual string ObjTel { get {return tel;} set {tel = value;} } public virtual string ObjHandy { get {return handy;} set {handy = value;} } public virtual string ObjFax { get {return fax;} set {fax = value;} } public virtual string ObjTlx { get {return tlx;} set {tlx = value;} } public virtual string ObjMail { get {return email;} set {email = value;} } public virtual string ObjAcc { get {return account;} set {account = value;} } public virtual string ObjA1 { get {return attr1;} set {attr1 = value;} } public virtual string ObjA2 { get {return attr2;} set {attr2 = value;} } public virtual string ObjWww { get {return web;} set {web = value;} } public virtual int ObjCurid { get {return curid;} set {curid = value;} } public virtual int ObjStaid { get {return staid;} set {staid = value;} } #region Object Methods/Functions (get one, selection, insert, update, delete) public override void Get(int Aid, ref int Arows) { string sql; int rows; CustV workDS; // get the first suiteable title and return it workDS = new CustV(); sql = String.Format("Select * from tdbadmin.tdbv_cust where pers_id = {0}", Aid); FillDs(workDS, sql, new string[] { "tdbv_cust" }); Arows = workDS.tdbv_cust.Rows.Count; CustV.tdbv_custRow Rwork = workDS.tdbv_cust[0]; // set variables now id = Rwork.PERS_ID; code = Rwork.NAME; curid = Rwork.CURID; langid = Rwork.S_ID; staid = Rwork.STA_ID; tel = Rwork.TEL; handy = Rwork.HANDY; fax = Rwork.FAX; tlx = Rwork.TLX; email = Rwork.EMAIL; web = Rwork.WEB; account = Rwork.ACCOUNT; manager = Rwork.MANAGER; attr1 = Rwork.ATTR1; attr2 = Rwork.ATTR2; custtypid = Rwork.CUSTTYPEID; text_id = Rwork.TEXTID; if (text_id > 0) rows = GetText(); else text = ""; } public override string GetBez(int Aid) { string sql; CustVsel workDS; // get the first suiteable title and return it workDS = new CustVsel(); sql = String.Format("Select * from tdbadmin.tdbv_custsel where pers_id = {0}", Aid); FillDs(workDS, sql, new string[] { "tdbv_custsel" }); CustVsel.tdbv_custselRow Rwork = workDS.tdbv_custsel[0]; id = Rwork.PERS_ID; return(Rwork.NAME); } public override string[,] Sel(ref int Arows) { string sql; int i=0; CustVsel workDS; // get the first suiteable title and return it workDS = new CustVsel(); sql = String.Format("Select * from tdbadmin.tdbv_custsel order by name"); FillDs(workDS, sql, new string[] { "tdbv_custsel" }); Arows = workDS.tdbv_custsel.Rows.Count; string[,] result = new string[Arows, 2]; foreach (CustVsel.tdbv_custselRow Rwork in workDS.tdbv_custsel) { result[i,0] = Convert.ToString(Rwork.PERS_ID); result[i,1] = Rwork.NAME; i++; } return(result); } public void InsUpd(bool Ainsert, string Aname, int Alangid, int Akunt, string Atel, string Ahandy, string Afax, string Atlx, string Amail, string Aweb, int Aleiter, string Akonto, string Aa1, string Aa2, int Acurid, int Astaid, string Atext) { int rowsaffected; string sql; // set person to this new one code = Aname; text = Atext; curid = Acurid; langid = Alangid; staid = Astaid; tel = Atel; handy = Ahandy; fax = Afax; tlx = Atlx; email = Amail; web = Aweb; account = Akonto; manager = Aleiter; attr1 = Aa1; attr2 = Aa2; custtypid = Akunt; // Begin Trx BeginTrx(); if (Ainsert) { // first get a new unique ID for bez and then sai id = NewId("personen", "PERS_ID"); rowsaffected = InsText(); // insert sai sql = String.Format("insert into tdbadmin.personen values({0}, {1}, '{2}', {3}, {4}, {5})", id, perstyp, code, langid, staid, text_id); rowsaffected = DBcmd(sql); sql = String.Format("insert into tdbadmin.kunden values({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', {8}, '{9}', '{10}', {11}, {12})", id, tel, handy, fax, tlx, email, web, account, manager, attr1, attr2, custtypid, curid); rowsaffected = DBcmd(sql); } else { rowsaffected = UpdText(); // update sai sql = String.Format("update tdbadmin.personen set name = '{0}', s_id = {1}, sta_id = {2}, textid = {3} where pers_id = {4}", code, langid, staid, text_id, id); rowsaffected = DBcmd(sql); sql = String.Format("update tdbadmin.kunden set tel = '{0}', handy = '{1}', fax = '{2}', tlx = '{3}', email = '{4}', web = '{5}', konto = '{6}', leiter = {7}, attr1 = '{8}', attr2 = '{9}', k_typ_id = {10}, whr_id = {11} where pers_id = {12}", tel, handy, fax, tlx, email, web, account, manager, attr1, attr2, custtypid, curid, id); rowsaffected = DBcmd(sql); } // commit Commit(); } public override void Delete() { int rowsaffected; string sql; // delete Country sql = String.Format("delete from tdbadmin.persadr where pers_id = {0}", id); rowsaffected = DBcmd(sql); sql = String.Format("delete from tdbadmin.kunden where pers_id = {0}", id); rowsaffected = DBcmd(sql); sql = String.Format("delete from tdbadmin.personen where pers_id = {0}", id); rowsaffected = DBcmd(sql); // IMPLEMENT cascading deletion if still dependencies here ?? if (rowsaffected > 0) { // if textid is not set to undef (-1) delete text entries if (text_id > 0) { sql = String.Format("delete from tdbadmin.texte where textid = {0} and typ = {1}", text_id, typ); rowsaffected = DBcmd(sql); } } } #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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Runtime.Serialization { public abstract partial class DataContractResolver { protected DataContractResolver() { } public abstract System.Type ResolveName(string typeName, string typeNamespace, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver); public abstract bool TryResolveType(System.Type type, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace); } public sealed partial class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer { public DataContractSerializer(System.Type type) { } public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { } public DataContractSerializer(System.Type type, System.Runtime.Serialization.DataContractSerializerSettings settings) { } public DataContractSerializer(System.Type type, string rootName, string rootNamespace) { } public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { } public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace) { } public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { } public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } } public bool IgnoreExtensionDataObject { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection<System.Type> KnownTypes { get { throw null; } } public int MaxItemsInObjectGraph { get { throw null; } } public bool PreserveObjectReferences { get { throw null; } } public bool SerializeReadOnlyTypes { get { throw null; } } public override bool IsStartObject(System.Xml.XmlDictionaryReader reader) { throw null; } public override bool IsStartObject(System.Xml.XmlReader reader) { throw null; } public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; } public object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName, System.Runtime.Serialization.DataContractResolver dataContractResolver) { throw null; } public override object ReadObject(System.Xml.XmlReader reader) { throw null; } public override object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; } public override void WriteEndObject(System.Xml.XmlDictionaryWriter writer) { } public override void WriteEndObject(System.Xml.XmlWriter writer) { } public void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph, System.Runtime.Serialization.DataContractResolver dataContractResolver) { } public override void WriteObject(System.Xml.XmlWriter writer, object graph) { } public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph) { } public override void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { } public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { } public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { } } public static partial class DataContractSerializerExtensions { public static System.Runtime.Serialization.ISerializationSurrogateProvider GetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer) { throw null; } public static void SetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider provider) { } } public partial class DataContractSerializerSettings { public DataContractSerializerSettings() { } public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } set { } } public bool IgnoreExtensionDataObject { get { throw null; } set { } } public System.Collections.Generic.IEnumerable<System.Type> KnownTypes { get { throw null; } set { } } public int MaxItemsInObjectGraph { get { throw null; } set { } } public bool PreserveObjectReferences { get { throw null; } set { } } public System.Xml.XmlDictionaryString RootName { get { throw null; } set { } } public System.Xml.XmlDictionaryString RootNamespace { get { throw null; } set { } } public bool SerializeReadOnlyTypes { get { throw null; } set { } } } public partial class ExportOptions { public ExportOptions() { } public System.Collections.ObjectModel.Collection<System.Type> KnownTypes { get { throw null; } } } public sealed partial class ExtensionDataObject { internal ExtensionDataObject() { } } public partial interface IExtensibleDataObject { System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; } } public abstract partial class XmlObjectSerializer { protected XmlObjectSerializer() { } public abstract bool IsStartObject(System.Xml.XmlDictionaryReader reader); public virtual bool IsStartObject(System.Xml.XmlReader reader) { throw null; } public virtual object ReadObject(System.IO.Stream stream) { throw null; } public virtual object ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; } public abstract object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName); public virtual object ReadObject(System.Xml.XmlReader reader) { throw null; } public virtual object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; } public abstract void WriteEndObject(System.Xml.XmlDictionaryWriter writer); public virtual void WriteEndObject(System.Xml.XmlWriter writer) { } public virtual void WriteObject(System.IO.Stream stream, object graph) { } public virtual void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { } public virtual void WriteObject(System.Xml.XmlWriter writer, object graph) { } public abstract void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph); public virtual void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { } public abstract void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph); public virtual void WriteStartObject(System.Xml.XmlWriter writer, object graph) { } } public static partial class XmlSerializableServices { public static void AddDefaultSchema(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.XmlQualifiedName typeQName) { } public static System.Xml.XmlNode[] ReadNodes(System.Xml.XmlReader xmlReader) { throw null; } public static void WriteNodes(System.Xml.XmlWriter xmlWriter, System.Xml.XmlNode[] nodes) { } } public static partial class XPathQueryGenerator { public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { throw null; } public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { throw null; } } public partial class XsdDataContractExporter { public XsdDataContractExporter() { } public XsdDataContractExporter(System.Xml.Schema.XmlSchemaSet schemas) { } public System.Runtime.Serialization.ExportOptions Options { get { throw null; } set { } } public System.Xml.Schema.XmlSchemaSet Schemas { get { throw null; } } public bool CanExport(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { throw null; } public bool CanExport(System.Collections.Generic.ICollection<System.Type> types) { throw null; } public bool CanExport(System.Type type) { throw null; } public void Export(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { } public void Export(System.Collections.Generic.ICollection<System.Type> types) { } public void Export(System.Type type) { } public System.Xml.XmlQualifiedName GetRootElementName(System.Type type) { throw null; } public System.Xml.Schema.XmlSchemaType GetSchemaType(System.Type type) { throw null; } public System.Xml.XmlQualifiedName GetSchemaTypeName(System.Type type) { throw null; } } } namespace System.Xml { public partial interface IFragmentCapableXmlDictionaryWriter { bool CanFragment { get; } void EndFragment(); void StartFragment(System.IO.Stream stream, bool generateSelfContainedTextFragment); void WriteFragment(byte[] buffer, int offset, int count); } public partial interface IStreamProvider { System.IO.Stream GetStream(); void ReleaseStream(System.IO.Stream stream); } public partial interface IXmlBinaryReaderInitializer { void SetInput(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose); void SetInput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose); } public partial interface IXmlBinaryWriterInitializer { void SetOutput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream); } public partial interface IXmlDictionary { bool TryLookup(int key, out System.Xml.XmlDictionaryString result); bool TryLookup(string value, out System.Xml.XmlDictionaryString result); bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result); } public partial interface IXmlTextReaderInitializer { void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose); void SetInput(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose); } public partial interface IXmlTextWriterInitializer { void SetOutput(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream); } public delegate void OnXmlDictionaryReaderClose(System.Xml.XmlDictionaryReader reader); public partial class UniqueId { public UniqueId() { } public UniqueId(byte[] guid) { } public UniqueId(byte[] guid, int offset) { } public UniqueId(char[] chars, int offset, int count) { } public UniqueId(System.Guid guid) { } public UniqueId(string value) { } public int CharArrayLength { get { throw null; } } public bool IsGuid { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; } public static bool operator !=(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; } public int ToCharArray(char[] chars, int offset) { throw null; } public override string ToString() { throw null; } public bool TryGetGuid(byte[] buffer, int offset) { throw null; } public bool TryGetGuid(out System.Guid guid) { throw null; } } public partial class XmlBinaryReaderSession : System.Xml.IXmlDictionary { public XmlBinaryReaderSession() { } public System.Xml.XmlDictionaryString Add(int id, string value) { throw null; } public void Clear() { } public bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; } public bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; } public bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; } } public partial class XmlBinaryWriterSession { public XmlBinaryWriterSession() { } public void Reset() { } public virtual bool TryAdd(System.Xml.XmlDictionaryString value, out int key) { throw null; } } public partial class XmlDictionary : System.Xml.IXmlDictionary { public XmlDictionary() { } public XmlDictionary(int capacity) { } public static System.Xml.IXmlDictionary Empty { get { throw null; } } public virtual System.Xml.XmlDictionaryString Add(string value) { throw null; } public virtual bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; } public virtual bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; } public virtual bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; } } public abstract partial class XmlDictionaryReader : System.Xml.XmlReader { protected XmlDictionaryReader() { } public virtual bool CanCanonicalize { get { throw null; } } public virtual System.Xml.XmlDictionaryReaderQuotas Quotas { get { throw null; } } public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; } public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateDictionaryReader(System.Xml.XmlReader reader) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; } public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; } public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; } public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public virtual void EndCanonicalization() { } public virtual string GetAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { throw null; } public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { throw null; } public virtual int IndexOfLocalName(System.Xml.XmlDictionaryString[] localNames, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual bool IsLocalName(string localName) { throw null; } public virtual bool IsLocalName(System.Xml.XmlDictionaryString localName) { throw null; } public virtual bool IsNamespaceUri(string namespaceUri) { throw null; } public virtual bool IsNamespaceUri(System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual bool IsStartArray(out System.Type type) { throw null; } public virtual bool IsStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } protected bool IsTextNode(System.Xml.XmlNodeType nodeType) { throw null; } public virtual void MoveToStartElement() { } public virtual void MoveToStartElement(string name) { } public virtual void MoveToStartElement(string localName, string namespaceUri) { } public virtual void MoveToStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, System.Guid[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { throw null; } public virtual int ReadArray(string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { throw null; } public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; } public virtual bool[] ReadBooleanArray(string localName, string namespaceUri) { throw null; } public virtual bool[] ReadBooleanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public override object ReadContentAs(System.Type type, System.Xml.IXmlNamespaceResolver namespaceResolver) { throw null; } public virtual byte[] ReadContentAsBase64() { throw null; } public virtual byte[] ReadContentAsBinHex() { throw null; } protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength) { throw null; } public virtual int ReadContentAsChars(char[] chars, int offset, int count) { throw null; } public override decimal ReadContentAsDecimal() { throw null; } public override float ReadContentAsFloat() { throw null; } public virtual System.Guid ReadContentAsGuid() { throw null; } public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { throw null; } public override string ReadContentAsString() { throw null; } protected string ReadContentAsString(int maxStringContentLength) { throw null; } public virtual string ReadContentAsString(string[] strings, out int index) { throw null; } public virtual string ReadContentAsString(System.Xml.XmlDictionaryString[] strings, out int index) { throw null; } public virtual System.TimeSpan ReadContentAsTimeSpan() { throw null; } public virtual System.Xml.UniqueId ReadContentAsUniqueId() { throw null; } public virtual System.DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { throw null; } public virtual System.DateTime[] ReadDateTimeArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri) { throw null; } public virtual decimal[] ReadDecimalArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual double[] ReadDoubleArray(string localName, string namespaceUri) { throw null; } public virtual double[] ReadDoubleArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual byte[] ReadElementContentAsBase64() { throw null; } public virtual byte[] ReadElementContentAsBinHex() { throw null; } public override bool ReadElementContentAsBoolean() { throw null; } public override System.DateTime ReadElementContentAsDateTime() { throw null; } public override decimal ReadElementContentAsDecimal() { throw null; } public override double ReadElementContentAsDouble() { throw null; } public override float ReadElementContentAsFloat() { throw null; } public virtual System.Guid ReadElementContentAsGuid() { throw null; } public override int ReadElementContentAsInt() { throw null; } public override long ReadElementContentAsLong() { throw null; } public override string ReadElementContentAsString() { throw null; } public virtual System.TimeSpan ReadElementContentAsTimeSpan() { throw null; } public virtual System.Xml.UniqueId ReadElementContentAsUniqueId() { throw null; } public virtual void ReadFullStartElement() { } public virtual void ReadFullStartElement(string name) { } public virtual void ReadFullStartElement(string localName, string namespaceUri) { } public virtual void ReadFullStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public virtual System.Guid[] ReadGuidArray(string localName, string namespaceUri) { throw null; } public virtual System.Guid[] ReadGuidArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual short[] ReadInt16Array(string localName, string namespaceUri) { throw null; } public virtual short[] ReadInt16Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual int[] ReadInt32Array(string localName, string namespaceUri) { throw null; } public virtual int[] ReadInt32Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual long[] ReadInt64Array(string localName, string namespaceUri) { throw null; } public virtual long[] ReadInt64Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual float[] ReadSingleArray(string localName, string namespaceUri) { throw null; } public virtual float[] ReadSingleArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual void ReadStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public override string ReadString() { throw null; } protected string ReadString(int maxStringContentLength) { throw null; } public virtual System.TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { throw null; } public virtual System.TimeSpan[] ReadTimeSpanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw null; } public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { } public virtual bool TryGetArrayLength(out int count) { throw null; } public virtual bool TryGetBase64ContentLength(out int length) { throw null; } public virtual bool TryGetLocalNameAsDictionaryString(out System.Xml.XmlDictionaryString localName) { throw null; } public virtual bool TryGetNamespaceUriAsDictionaryString(out System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual bool TryGetValueAsDictionaryString(out System.Xml.XmlDictionaryString value) { throw null; } } public sealed partial class XmlDictionaryReaderQuotas { public XmlDictionaryReaderQuotas() { } public static System.Xml.XmlDictionaryReaderQuotas Max { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(16384)] public int MaxArrayLength { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(4096)] public int MaxBytesPerRead { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(32)] public int MaxDepth { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(16384)] public int MaxNameTableCharCount { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(8192)] public int MaxStringContentLength { get { throw null; } set { } } public System.Xml.XmlDictionaryReaderQuotaTypes ModifiedQuotas { get { throw null; } } public void CopyTo(System.Xml.XmlDictionaryReaderQuotas quotas) { } } [System.FlagsAttribute] public enum XmlDictionaryReaderQuotaTypes { MaxDepth = 1, MaxStringContentLength = 2, MaxArrayLength = 4, MaxBytesPerRead = 8, MaxNameTableCharCount = 16, } public partial class XmlDictionaryString { public XmlDictionaryString(System.Xml.IXmlDictionary dictionary, string value, int key) { } public System.Xml.IXmlDictionary Dictionary { get { throw null; } } public static System.Xml.XmlDictionaryString Empty { get { throw null; } } public int Key { get { throw null; } } public string Value { get { throw null; } } public override string ToString() { throw null; } } public abstract partial class XmlDictionaryWriter : System.Xml.XmlWriter { protected XmlDictionaryWriter() { } public virtual bool CanCanonicalize { get { throw null; } } public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream) { throw null; } public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary) { throw null; } public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session) { throw null; } public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream) { throw null; } public static System.Xml.XmlDictionaryWriter CreateDictionaryWriter(System.Xml.XmlWriter writer) { throw null; } public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo) { throw null; } public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { throw null; } public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream) { throw null; } public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding) { throw null; } public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream) { throw null; } public virtual void EndCanonicalization() { } public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.Guid[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { } public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { } public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { } public void WriteAttributeString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { } public void WriteAttributeString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { } public override System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { throw null; } public void WriteElementString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { } public void WriteElementString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { } public virtual void WriteNode(System.Xml.XmlDictionaryReader reader, bool defattr) { } public override void WriteNode(System.Xml.XmlReader reader, bool defattr) { } public virtual void WriteQualifiedName(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public virtual void WriteStartAttribute(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public void WriteStartAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public virtual void WriteStartElement(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public void WriteStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { } public virtual void WriteString(System.Xml.XmlDictionaryString value) { } protected virtual void WriteTextNode(System.Xml.XmlDictionaryReader reader, bool isAttribute) { } public virtual void WriteValue(System.Guid value) { } public virtual void WriteValue(System.TimeSpan value) { } public virtual void WriteValue(System.Xml.IStreamProvider value) { } public virtual void WriteValue(System.Xml.UniqueId value) { } public virtual void WriteValue(System.Xml.XmlDictionaryString value) { } public virtual System.Threading.Tasks.Task WriteValueAsync(System.Xml.IStreamProvider value) { throw null; } public virtual void WriteXmlAttribute(string localName, string value) { } public virtual void WriteXmlAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString value) { } public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) { } public virtual void WriteXmlnsAttribute(string prefix, System.Xml.XmlDictionaryString namespaceUri) { } } }
// // 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.IO; 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; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Tenant Policy. /// </summary> internal partial class TenantPolicyOperations : IServiceOperations<ApiManagementClient>, ITenantPolicyOperations { /// <summary> /// Initializes a new instance of the TenantPolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TenantPolicyOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Deletes tenant-level policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (etag == null) { throw new ArgumentNullException("etag"); } // 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("serviceName", serviceName); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "DeleteAsync", 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/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/tenant/policy"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // 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 && statusCode != HttpStatusCode.NoContent) { 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets tenant-level policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get policy output operation. /// </returns> public async Task<PolicyGetResponse> GetAsync(string resourceGroupName, string serviceName, string format, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (format == null) { throw new ArgumentNullException("format"); } // 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("serviceName", serviceName); tracingParameters.Add("format", format); 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/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/tenant/policy"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", format); // 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 PolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PolicyGetResponse(); result.PolicyBytes = Encoding.UTF8.GetBytes(responseContent); } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.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> /// Sets tenant-level policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <param name='policyStream'> /// Required. Policy stream. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> SetAsync(string resourceGroupName, string serviceName, string format, Stream policyStream, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (format == null) { throw new ArgumentNullException("format"); } if (policyStream == null) { throw new ArgumentNullException("policyStream"); } // 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("serviceName", serviceName); tracingParameters.Add("format", format); tracingParameters.Add("policyStream", policyStream); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "SetAsync", 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/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/tenant/policy"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request Stream requestContent = policyStream; httpRequest.Content = new StreamContent(requestContent); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(format); // 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.Created && statusCode != HttpStatusCode.NoContent) { 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using Bloom.Book; using BloomTests.TestDoubles.CollectionTab; using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; using SIL.IO; using SIL.Reporting; using SIL.TestUtilities; namespace BloomTests.CollectionTab { [TestFixture] [SuppressMessage("ReSharper", "LocalizableElement")] class LibraryModelTests { private TemporaryFolder _collection; private TemporaryFolder _folder; private FakeLibraryModel _testLibraryModel; [SetUp] public void Setup() { ErrorReport.IsOkToInteractWithUser = false; _folder = new TemporaryFolder("LibraryModelTests"); // ENHANCE: Sometimes making the FakeCollection temporary folder causes an UnauthorizedAccessException. // Not exactly sure why or what to do about it. Possibly it could be related to file system operations // being async in nature??? _collection = new TemporaryFolder(_folder, "FakeCollection"); MakeFakeCssFile(); _testLibraryModel = new FakeLibraryModel(_collection); } private void MakeFakeCssFile() { var cssName = Path.Combine(_collection.Path, "FakeCss.css"); File.WriteAllText(cssName, "Fake CSS file"); } private string MakeBook() { var f = new TemporaryFolder(_collection, "unittest-" + Guid.NewGuid()); File.WriteAllText(Path.Combine(f.Path, "one.htm"), "test"); File.WriteAllText(Path.Combine(f.Path, "one.css"), "test"); File.WriteAllText(Path.Combine(f.Path, "meta.json"), new BookMetaData().Json); return f.Path; } private void AddThumbsFile(string bookFolderPath) { File.WriteAllText(Path.Combine(bookFolderPath, "thumbs.db"), "test thumbs.db file"); } private void AddPdfFile(string bookFolderPath) { File.WriteAllText(Path.Combine(bookFolderPath, "xfile1.pdf"), "test pdf file"); } private void AddUnnecessaryHtmlFile(string srcBookPath) { string extraHtmDir = Path.Combine(srcBookPath, "unnecessaryExtraFiles"); Directory.CreateDirectory(extraHtmDir); string htmContents = "<html><body><w:sdtPr></w:sdtPr></body></html>"; File.WriteAllText(Path.Combine(extraHtmDir, "causesException.htm"), htmContents); } // Imitate LibraryModel.MakeBloomPack(), but bypasses the user interaction private void MakeTestBloomPack(string path, bool forReaderTools) { var (dirName, dirPrefix) = _testLibraryModel.GetDirNameAndPrefixForCollectionBloomPack(); _testLibraryModel.MakeBloomPackInternal(path, dirName, dirPrefix, forReaderTools, isCollection: true); } // Imitate LibraryModel.MakeBloomPack(), but bypasses the user interaction private void MakeTestSingleBookBloomPack(string path, string bookSrcPath, bool forReaderTools) { var (dirName, dirPrefix) = _testLibraryModel.GetDirNameAndPrefixForSingleBookBloomPack(bookSrcPath); _testLibraryModel.MakeBloomPackInternal(path, dirName, dirPrefix, forReaderTools, isCollection: false); } // Don't do anything with the zip file except read in the filenames private static List<string> GetActualFilenamesFromZipfile(string bloomPackName) { var actualFiles = new List<string>(); using (var zip = new ZipFile(bloomPackName)) { actualFiles.AddRange(from ZipEntry entry in zip select entry.Name); zip.Close(); } return actualFiles; } [Test] public void MakeBloomPack_DoesntIncludePdfFile() { var srcBookPath = MakeBook(); AddPdfFile(srcBookPath); const string excludedFile = "xfile1.pdf"; var bloomPackName = Path.Combine(_folder.Path, "testPack.BloomPack"); // Imitate LibraryModel.MakeBloomPack() without the user interaction MakeTestBloomPack(bloomPackName, false); // Don't do anything with the zip file except read in the filenames var actualFiles = GetActualFilenamesFromZipfile(bloomPackName); // +2 for collection-level CustomCollectionSettings and FakeCss.css file, -1 for pdf file, so the count is +1 Assert.That(actualFiles.Count, Is.EqualTo(Directory.GetFiles(srcBookPath).Count() + 1)); foreach (var filePath in actualFiles) { Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile)); } } [Test] public void MakeBloomPack_DoesntIncludeThumbsFile() { var srcBookPath = MakeBook(); AddThumbsFile(srcBookPath); const string excludedFile = "thumbs.db"; var bloomPackName = Path.Combine(_folder.Path, "testPack.BloomPack"); // Imitate LibraryModel.MakeBloomPack() without the user interaction MakeTestBloomPack(bloomPackName, false); // Don't do anything with the zip file except read in the filenames var actualFiles = GetActualFilenamesFromZipfile(bloomPackName); // +2 for collection-level CustomCollectionSettings and FakeCss.css file, -1 for thumbs file, so the count is +1 Assert.That(actualFiles.Count, Is.EqualTo(Directory.GetFiles(srcBookPath).Count() + 1)); foreach (var filePath in actualFiles) { Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile)); } } [Test] public void MakeBloomPack_DoesntIncludeCorrupt_Map_OrBakFiles() { var srcBookPath = MakeBook(); const string excludedFile1 = BookStorage.PrefixForCorruptHtmFiles + ".htm"; const string excludedFile2 = BookStorage.PrefixForCorruptHtmFiles + "2.htm"; const string excludedFile3 = "Basic Book.css.map"; string excludedBackup = Path.GetFileName(srcBookPath) + ".bak"; RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedFile1), "rubbish"); RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedFile2), "rubbish"); RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedFile3), "rubbish"); RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedBackup), "rubbish"); var bloomPackName = Path.Combine(_folder.Path, "testPack.BloomPack"); // Imitate LibraryModel.MakeBloomPack() without the user interaction MakeTestBloomPack(bloomPackName, false); // Don't do anything with the zip file except read in the filenames var actualFiles = GetActualFilenamesFromZipfile(bloomPackName); // +2 for collection-level CustomCollectionSettings and FakeCss.css file, -4 for corrupt, .map and .bak files, so the count is -2 Assert.That(actualFiles.Count, Is.EqualTo(Directory.GetFiles(srcBookPath).Length - 2)); foreach (var filePath in actualFiles) { Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile1)); Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile2)); Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile3)); Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedBackup)); } } [Test] public void MakeBloomPack_AddslockFormattingMetaTagToReader() { var srcBookPath = MakeBook(); // the html file needs to have the same name as its directory var testFileName = Path.GetFileName(srcBookPath) + ".htm"; var readerName = Path.Combine(srcBookPath, testFileName); var bloomPackName = Path.Combine(_folder.Path, "testReaderPack.BloomPack"); var sb = new StringBuilder(); sb.AppendLine("<!DOCTYPE html>"); sb.AppendLine("<html>"); sb.AppendLine("<head>"); sb.AppendLine(" <meta charset=\"UTF-8\"></meta>"); sb.AppendLine(" <meta name=\"Generator\" content=\"Bloom Version 3.3.0 (apparent build date: 28-Jul-2015)\"></meta>"); sb.AppendLine(" <meta name=\"BloomFormatVersion\" content=\"2.0\"></meta>"); sb.AppendLine(" <meta name=\"pageTemplateSource\" content=\"Leveled Reader\"></meta>"); sb.AppendLine(" <title>Leveled Reader</title>"); sb.AppendLine(" <link rel=\"stylesheet\" href=\"basePage.css\" type=\"text/css\"></link>"); sb.AppendLine("</head>"); sb.AppendLine("<body>"); sb.AppendLine("</body>"); sb.AppendLine("</html>"); File.WriteAllText(readerName, sb.ToString()); // make the BloomPack MakeTestBloomPack(bloomPackName, true); // get the reader file from the BloomPack var actualFiles = GetActualFilenamesFromZipfile(bloomPackName); var zipEntryName = actualFiles.FirstOrDefault(file => file.EndsWith(testFileName)); Assert.That(zipEntryName, Is.Not.Null.And.Not.Empty); string outputText; using (var zip = new ZipFile(bloomPackName)) { var ze = zip.GetEntry(zipEntryName); var buffer = new byte[4096]; using (var instream = zip.GetInputStream(ze)) using (var writer = new MemoryStream()) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(instream, writer, buffer); writer.Position = 0; using (var reader = new StreamReader(writer)) { outputText = reader.ReadToEnd(); } } } // check for the lockFormatting meta tag Assert.That(outputText, Is.Not.Null.And.Not.Empty); Assert.IsTrue(outputText.Contains("<meta name=\"lockFormatting\" content=\"true\">")); } [Test] public void MakeCollectionBloomPack_DoesntParseExtraHtmlFiles() { var srcBookPath = MakeBook(); AddUnnecessaryHtmlFile(srcBookPath); var bloomPackName = Path.Combine(_folder.Path, "testPack.BloomPack"); // System Under Test // Imitate LibraryModel.MakeBloomPack() without the user interaction MakeTestBloomPack(bloomPackName, false); // Verification // Just make sure it doesn't throw an exception. return; } [Test] public void MakeSingleBookBloomPack_DoesntParseExtraHtmlFiles() { var srcBookPath = MakeBook(); AddUnnecessaryHtmlFile(srcBookPath); var bloomPackName = Path.Combine(_folder.Path, "testPack.BloomPack"); // System Under Test // Imitate LibraryModel.MakeBloomPack() without the user interaction MakeTestSingleBookBloomPack(bloomPackName, srcBookPath, false); // Verification // Just make sure it doesn't throw an exception. return; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// InteractionResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Proxy.V1.Service.Session { public class InteractionResource : Resource { public sealed class TypeEnum : StringEnum { private TypeEnum(string value) : base(value) {} public TypeEnum() {} public static implicit operator TypeEnum(string value) { return new TypeEnum(value); } public static readonly TypeEnum Message = new TypeEnum("message"); public static readonly TypeEnum Voice = new TypeEnum("voice"); public static readonly TypeEnum Unknown = new TypeEnum("unknown"); } public sealed class ResourceStatusEnum : StringEnum { private ResourceStatusEnum(string value) : base(value) {} public ResourceStatusEnum() {} public static implicit operator ResourceStatusEnum(string value) { return new ResourceStatusEnum(value); } public static readonly ResourceStatusEnum Accepted = new ResourceStatusEnum("accepted"); public static readonly ResourceStatusEnum Answered = new ResourceStatusEnum("answered"); public static readonly ResourceStatusEnum Busy = new ResourceStatusEnum("busy"); public static readonly ResourceStatusEnum Canceled = new ResourceStatusEnum("canceled"); public static readonly ResourceStatusEnum Completed = new ResourceStatusEnum("completed"); public static readonly ResourceStatusEnum Deleted = new ResourceStatusEnum("deleted"); public static readonly ResourceStatusEnum Delivered = new ResourceStatusEnum("delivered"); public static readonly ResourceStatusEnum DeliveryUnknown = new ResourceStatusEnum("delivery-unknown"); public static readonly ResourceStatusEnum Failed = new ResourceStatusEnum("failed"); public static readonly ResourceStatusEnum InProgress = new ResourceStatusEnum("in-progress"); public static readonly ResourceStatusEnum Initiated = new ResourceStatusEnum("initiated"); public static readonly ResourceStatusEnum NoAnswer = new ResourceStatusEnum("no-answer"); public static readonly ResourceStatusEnum Queued = new ResourceStatusEnum("queued"); public static readonly ResourceStatusEnum Received = new ResourceStatusEnum("received"); public static readonly ResourceStatusEnum Receiving = new ResourceStatusEnum("receiving"); public static readonly ResourceStatusEnum Ringing = new ResourceStatusEnum("ringing"); public static readonly ResourceStatusEnum Scheduled = new ResourceStatusEnum("scheduled"); public static readonly ResourceStatusEnum Sending = new ResourceStatusEnum("sending"); public static readonly ResourceStatusEnum Sent = new ResourceStatusEnum("sent"); public static readonly ResourceStatusEnum Undelivered = new ResourceStatusEnum("undelivered"); public static readonly ResourceStatusEnum Unknown = new ResourceStatusEnum("unknown"); } private static Request BuildFetchRequest(FetchInteractionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Proxy, "/v1/Services/" + options.PathServiceSid + "/Sessions/" + options.PathSessionSid + "/Interactions/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of Interactions for a given [Session](https://www.twilio.com/docs/proxy/api/session). /// </summary> /// <param name="options"> Fetch Interaction parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Interaction </returns> public static InteractionResource Fetch(FetchInteractionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Retrieve a list of Interactions for a given [Session](https://www.twilio.com/docs/proxy/api/session). /// </summary> /// <param name="options"> Fetch Interaction parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Interaction </returns> public static async System.Threading.Tasks.Task<InteractionResource> FetchAsync(FetchInteractionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Retrieve a list of Interactions for a given [Session](https://www.twilio.com/docs/proxy/api/session). /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to fetch </param> /// <param name="pathSessionSid"> he SID of the parent Session of the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Interaction </returns> public static InteractionResource Fetch(string pathServiceSid, string pathSessionSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchInteractionOptions(pathServiceSid, pathSessionSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Retrieve a list of Interactions for a given [Session](https://www.twilio.com/docs/proxy/api/session). /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to fetch </param> /// <param name="pathSessionSid"> he SID of the parent Session of the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Interaction </returns> public static async System.Threading.Tasks.Task<InteractionResource> FetchAsync(string pathServiceSid, string pathSessionSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchInteractionOptions(pathServiceSid, pathSessionSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadInteractionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Proxy, "/v1/Services/" + options.PathServiceSid + "/Sessions/" + options.PathSessionSid + "/Interactions", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Interactions for a Session. A maximum of 100 records will be returned per page. /// </summary> /// <param name="options"> Read Interaction parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Interaction </returns> public static ResourceSet<InteractionResource> Read(ReadInteractionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<InteractionResource>.FromJson("interactions", response.Content); return new ResourceSet<InteractionResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Interactions for a Session. A maximum of 100 records will be returned per page. /// </summary> /// <param name="options"> Read Interaction parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Interaction </returns> public static async System.Threading.Tasks.Task<ResourceSet<InteractionResource>> ReadAsync(ReadInteractionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<InteractionResource>.FromJson("interactions", response.Content); return new ResourceSet<InteractionResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Interactions for a Session. A maximum of 100 records will be returned per page. /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service to read the resource from </param> /// <param name="pathSessionSid"> The SID of the parent Session to read the resource from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Interaction </returns> public static ResourceSet<InteractionResource> Read(string pathServiceSid, string pathSessionSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadInteractionOptions(pathServiceSid, pathSessionSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Interactions for a Session. A maximum of 100 records will be returned per page. /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service to read the resource from </param> /// <param name="pathSessionSid"> The SID of the parent Session to read the resource from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Interaction </returns> public static async System.Threading.Tasks.Task<ResourceSet<InteractionResource>> ReadAsync(string pathServiceSid, string pathSessionSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadInteractionOptions(pathServiceSid, pathSessionSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<InteractionResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<InteractionResource>.FromJson("interactions", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<InteractionResource> NextPage(Page<InteractionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Proxy) ); var response = client.Request(request); return Page<InteractionResource>.FromJson("interactions", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<InteractionResource> PreviousPage(Page<InteractionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Proxy) ); var response = client.Request(request); return Page<InteractionResource>.FromJson("interactions", response.Content); } private static Request BuildDeleteRequest(DeleteInteractionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Proxy, "/v1/Services/" + options.PathServiceSid + "/Sessions/" + options.PathSessionSid + "/Interactions/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific Interaction. /// </summary> /// <param name="options"> Delete Interaction parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Interaction </returns> public static bool Delete(DeleteInteractionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific Interaction. /// </summary> /// <param name="options"> Delete Interaction parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Interaction </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteInteractionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific Interaction. /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to delete </param> /// <param name="pathSessionSid"> he SID of the parent Session of the resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Interaction </returns> public static bool Delete(string pathServiceSid, string pathSessionSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteInteractionOptions(pathServiceSid, pathSessionSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific Interaction. /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to delete </param> /// <param name="pathSessionSid"> he SID of the parent Session of the resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Interaction </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSessionSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteInteractionOptions(pathServiceSid, pathSessionSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a InteractionResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> InteractionResource object represented by the provided JSON </returns> public static InteractionResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<InteractionResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the resource's parent Session /// </summary> [JsonProperty("session_sid")] public string SessionSid { get; private set; } /// <summary> /// The SID of the resource's parent Service /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// A JSON string that includes the message body of message interactions /// </summary> [JsonProperty("data")] public string Data { get; private set; } /// <summary> /// The Type of the Interaction /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public InteractionResource.TypeEnum Type { get; private set; } /// <summary> /// The SID of the inbound Participant resource /// </summary> [JsonProperty("inbound_participant_sid")] public string InboundParticipantSid { get; private set; } /// <summary> /// The SID of the inbound resource /// </summary> [JsonProperty("inbound_resource_sid")] public string InboundResourceSid { get; private set; } /// <summary> /// The inbound resource status of the Interaction /// </summary> [JsonProperty("inbound_resource_status")] [JsonConverter(typeof(StringEnumConverter))] public InteractionResource.ResourceStatusEnum InboundResourceStatus { get; private set; } /// <summary> /// The inbound resource type /// </summary> [JsonProperty("inbound_resource_type")] public string InboundResourceType { get; private set; } /// <summary> /// The URL of the Twilio inbound resource /// </summary> [JsonProperty("inbound_resource_url")] public Uri InboundResourceUrl { get; private set; } /// <summary> /// The SID of the outbound Participant /// </summary> [JsonProperty("outbound_participant_sid")] public string OutboundParticipantSid { get; private set; } /// <summary> /// The SID of the outbound resource /// </summary> [JsonProperty("outbound_resource_sid")] public string OutboundResourceSid { get; private set; } /// <summary> /// The outbound resource status of the Interaction /// </summary> [JsonProperty("outbound_resource_status")] [JsonConverter(typeof(StringEnumConverter))] public InteractionResource.ResourceStatusEnum OutboundResourceStatus { get; private set; } /// <summary> /// The outbound resource type /// </summary> [JsonProperty("outbound_resource_type")] public string OutboundResourceType { get; private set; } /// <summary> /// The URL of the Twilio outbound resource /// </summary> [JsonProperty("outbound_resource_url")] public Uri OutboundResourceUrl { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the Interaction was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the Interaction resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private InteractionResource() { } } }
using System; using System.Net; using System.IO; using System.Text; using System.Security.Cryptography; // JSON decoder: JavaScriptSerializer (requires: System.Web.Extensions) using System.Web.Script.Serialization; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Vingd { public class VingdOperationException : Exception { protected string context = null; protected HttpStatusCode code = HttpStatusCode.Conflict; public VingdOperationException(string message, string context) : this(message, context, HttpStatusCode.Conflict, null) {} public VingdOperationException(string message, string context, HttpStatusCode code) : this(message, context, code, null) {} public VingdOperationException(string message, string context, HttpStatusCode code, Exception inner) : base(message, inner) { this.context = context; this.code = code; } public override string ToString() { return this.GetType().Name + ": " + (context != null ? "[" + context + "]: " : "") + Message + " (" + (int)code + " " + code.ToString() + ")"; } } public class VingdTransportException : Exception { protected string context = null; protected HttpStatusCode code = HttpStatusCode.Conflict; public VingdTransportException(string message, Exception inner) : base(message, inner) {} public VingdTransportException(string message, string context) : this(message, HttpStatusCode.Conflict, context) {} public VingdTransportException(string message, HttpStatusCode code, Exception inner) : base(message, inner) { this.code = code; } public VingdTransportException(string message, HttpStatusCode code, string context) : this(message, code, (Exception)null) { this.context = context; } public override string ToString() { return this.GetType().Name + ": " + (context != null ? "[" + context + "]: " : "") + Message + " (" + (int)code + " " + code.ToString() + ")"; } } public class VingdClient { public const string userAgent = "vingd-api-csharp/1.1.1"; // note: mono by default has empty trusted CA store // Vingd uses DigiCert's certificate, so you should at least add their CA cert // (see http://www.mono-project.com/FAQ:_Security on how to do it) // production/default Vingd endpoint and Vingd user frontend base public const string productionEndpointURL = "https://api.vingd.com/broker/v1"; public const string productionFrontendURL = "https://www.vingd.com"; // sandbox/testing Vingd endpoint and Vingd user frontend base public const string sandboxEndpointURL = "https://api.vingd.com/sandbox/broker/v1"; public const string sandboxFrontendURL = "https://www.sandbox.vingd.com"; // default order lifespan: 15min public TimeSpan defaultOrderExpiry = new TimeSpan(0, 15, 0); // default voucher lifespan: 1 month (i.e. 31 day) public TimeSpan defaultVoucherExpiry = new TimeSpan(31, 0, 0, 0); public enum ObjectClassID { Generic = 0 } // connection parameters private string username = null; private string pwhash = null; private string backendURL = VingdClient.productionEndpointURL; private string frontendURL = VingdClient.productionFrontendURL; public VingdClient(string username, string pwhash, string backend, string frontend) { init(username, pwhash, backend, frontend); } public VingdClient(string username, string pwhash) { init(username, pwhash, VingdClient.productionEndpointURL, VingdClient.productionFrontendURL); } private void init(string username, string pwhash, string backendURL, string frontendURL) { this.username = username; this.pwhash = pwhash; this.backendURL = backendURL; this.frontendURL = frontendURL; } /** * Helper methods */ public static string SHA1(string buffer) { byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(buffer)); StringBuilder hex = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { hex.Append(hash[i].ToString("x2")); } return hex.ToString(); } public object JSONParse (string json) { // hack: mono parser fix! json = Regex.Replace(json, @"null\s+}", "null}"); json = Regex.Replace(json, @"true\s+}", "true}"); json = Regex.Replace(json, @"false\s+}", "false}"); JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.DeserializeObject(json); } public string JSONStringify (object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Serialize(obj); } /** * Makes a generic Vingd Broker request. * * Returns parsed JSON response in object; raises VingdTransportException or * VingdOperationException on failure. * */ public object Request (string method, string resource, object parameters) { UTF8Encoding encoder = new UTF8Encoding(false); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(backendURL + resource); req.Method = method; req.UserAgent = VingdClient.userAgent; // hack: seems like the standard Basic Http Auth in .NET sends auth header ONLY AFTER // it receives the "401 Unauthenticated" response. PreAuthenticate is correcting this // on all (subsequent) requests, but the first one! // So, we have to fail back to the low-level method. //req.Credentials = new NetworkCredential(username, pwhash); //req.PreAuthenticate = true; string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + pwhash)); req.Headers.Add("Authorization", "Basic " + credentials); if (parameters != null) { string strParameters = JSONStringify(parameters); byte[] byteParameters = encoder.GetBytes(strParameters); req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = byteParameters.Length; Stream rs = req.GetRequestStream(); rs.Write(byteParameters, 0, byteParameters.Length); rs.Close(); } HttpWebResponse res; try { res = (HttpWebResponse)req.GetResponse(); } catch (WebException e) { if (e.Status != WebExceptionStatus.ProtocolError || null == (res = e.Response as HttpWebResponse)) { throw new VingdTransportException("Connecting to Vingd Broker failed.", e); } } string jsonContent; try { StreamReader sr = new StreamReader(res.GetResponseStream(), encoder); jsonContent = sr.ReadToEnd(); } catch (Exception e) { throw new VingdTransportException("Communication with Vingd Broker failed.", e); } finally { res.Close(); } Dictionary<string, object> dictContent; try { dictContent = (Dictionary<string, object>)JSONParse(jsonContent); } catch (Exception e) { throw new VingdTransportException("Non-JSON response or unexpected JSON structure.", res.StatusCode, e); } // return data response if request successful int code = (int)res.StatusCode; if (code >= 200 && code < 300) { object data; try { data = (object)dictContent["data"]; } catch (Exception e) { throw new VingdTransportException("Invalid JSON data response.", res.StatusCode, e); } return data; } // raise exception describing the vingd error condition string message, context; try { message = (string)dictContent["message"]; context = (string)dictContent["context"]; } catch (Exception e) { throw new VingdTransportException("Invalid JSON error response.", res.StatusCode, e); } throw new VingdOperationException(message, context, res.StatusCode); } private object GetDictListElem(Dictionary<string, object> dict, string key, int index) { if (!dict.ContainsKey(key)) return null; if (!dict[key].GetType().IsArray) return null; object[] array = (object[])dict[key]; try { return array.GetValue(index); } catch (Exception) { return null; } } private Dictionary<string, object> ConvertToDict(object response) { if (response.GetType() != typeof(Dictionary<string, object>)) { throw new VingdTransportException("Unexpected service response; expecting JSON dictionary.", "Decode"); } return (Dictionary<string, object>)response; } /** * Registers (enrolls) an object into the Vingd Objects Registry. * * For minimal object description ({'name': <name>, 'url': <callback_url>}), * use RegisterObject(string name, string url) method. * */ public long CreateObject (object description) { var parameters = new Dictionary<string, object>(); parameters.Add("class", (int)ObjectClassID.Generic); parameters.Add("description", description); object responseRaw = Request("POST", "/registry/objects/", parameters); var response = ConvertToDict(responseRaw); var error = (Dictionary<string, object>)GetDictListElem(response, "errors", 0); if (error != null) { throw new VingdOperationException((string)error["desc"], (string)error["code"]); } object oid = GetDictListElem(response, "oids", 0); if (oid != null) { return Convert.ToInt64(oid); } throw new VingdTransportException("Unexpected service response.", "Decode"); } public long CreateObject (string name, string url) { var description = new Dictionary<string, string>(); description.Add("name", name); description.Add("url", url); return CreateObject((object)description); } /** * Contacts Vingd Broker and generates a new order for selling the object (oid) * under the defined terms (price). Order shall be valid until expiresLocal. * Context shall be stored with order and returned upon purchase verification. * */ public VingdOrder CreateOrder (long oid, double price, string context, DateTime expiresLocal) { DateTimeOffset expiresWithTimezone = new DateTimeOffset(expiresLocal, TimeZone.CurrentTimeZone.GetUtcOffset(expiresLocal)); var parameters = new Dictionary<string, object>(); parameters.Add("price", (int)(price * 100)); parameters.Add("context", context); parameters.Add("order_expires", expiresWithTimezone.ToString("o")); object responseRaw = Request("POST", "/objects/" + oid + "/orders", parameters); var response = ConvertToDict(responseRaw); var error = (Dictionary<string, object>)GetDictListElem(response, "errors", 0); if (error != null) { throw new VingdOperationException((string)error["desc"], (string)error["code"]); } object id = GetDictListElem(response, "ids", 0); if (id == null) { throw new VingdTransportException("Unexpected service response.", "Decode"); } long orderid = Convert.ToInt64(id); return new VingdOrder(orderid, oid, price, context, expiresWithTimezone, frontendURL); } public VingdOrder CreateOrder(long oid, double price, string context, TimeSpan expiry) { return CreateOrder(oid, price, context, DateTime.Now.Add(expiry)); } public VingdOrder CreateOrder(long oid, double price, string context) { return CreateOrder(oid, price, context, DateTime.Now.Add(defaultOrderExpiry)); } public VingdOrder CreateOrder(long oid, double price, TimeSpan expiry) { return CreateOrder(oid, price, null, DateTime.Now.Add(expiry)); } public VingdOrder CreateOrder(long oid, double price) { return CreateOrder(oid, price, null, DateTime.Now.Add(defaultOrderExpiry)); } /** * Verifies the token of purchase thru Vingd Broker. * * If token was invalid (purchase can not be verified), VingdOperationException is thrown. * */ public VingdPurchase VerifyPurchase(string token) { string oid, tid; try { var tokenDict = (Dictionary<string, object>)JSONParse(token); oid = (string)tokenDict["oid"]; tid = (string)tokenDict["tid"]; } catch { throw new VingdTransportException("Invalid token.", "TokenVerification"); } if (!IsTokenFormatValid(tid)) { throw new VingdTransportException("Invalid token format.", "TokenVerification"); } object responseRaw = Request("GET", "/objects/" + oid + "/tokens/" + tid, null); var response = ConvertToDict(responseRaw); return new VingdPurchase { huid = (string)response["huid"], oid = Convert.ToInt64(oid), orderid = Convert.ToInt64(response["orderid"]), context = (string)response["context"], purchaseid = Convert.ToInt64(response["purchaseid"]), transferid = Convert.ToInt64(response["transferid"]), reclaimed = Convert.ToBoolean(response["reclaimed"]) }; } public bool IsTokenFormatValid (string tid) { return Regex.Match(tid, "^[a-fA-F\\d]{1,40}$").Success; } /** * Commits user's reserved funds to seller account. Call CommitPurchase() upon * successful delivery of paid content to the user. * * If you do not call CommitPurchase() user shall be automatically refunded. * * On failure, VingdOperationException is thrown. * */ public void CommitPurchase(VingdPurchase purchase) { var parameters = new Dictionary<string, object>(); parameters.Add("transferid", purchase.transferid); Request("PUT", "/purchases/" + purchase.purchaseid, parameters); } /** * Creates a new Vingd voucher. * * The voucher created vouches the `amountVouched` (in VINGDs) to the bearer * of the voucher (if used until `expiresLocal`). * Upon claiming the vouched vingds, user shall be presented with `userMessage`. * * The key datum to present to the user is voucher claim URL on Vingd frontend, * or alternatively the voucher code (returned .code / .GetRedirectURL()). * */ public VingdVoucher CreateVoucher(double amountVouched, DateTime expiresLocal, string userMessage) { DateTimeOffset expiresWithTimezone = new DateTimeOffset(expiresLocal, TimeZone.CurrentTimeZone.GetUtcOffset(expiresLocal)); var parameters = new Dictionary<string, object>(); parameters.Add("amount", (int)(amountVouched * 100)); parameters.Add("until", expiresWithTimezone.ToString("o")); parameters.Add("message", userMessage); object responseRaw = Request("POST", "/vouchers/", parameters); var response = ConvertToDict(responseRaw); return new VingdVoucher( amountVouched, Convert.ToInt64(response["id_fort_transfer"]), expiresWithTimezone, (string)response["vid_encoded"], frontendURL ); } public VingdVoucher CreateVoucher(double amountVouched, TimeSpan expiry, string userMessage) { return CreateVoucher(amountVouched, DateTime.Now.Add(expiry), userMessage); } public VingdVoucher CreateVoucher(double amountVouched, string userMessage) { return CreateVoucher(amountVouched, DateTime.Now.Add(defaultVoucherExpiry), userMessage); } public VingdVoucher CreateVoucher(double amountVouched) { return CreateVoucher(amountVouched, DateTime.Now.Add(defaultVoucherExpiry), null); } /** * Rewards user identified with `huid`, directly with `amount` (in VINGDs). * * Hashed User ID (huid) is bound to account of the authenticated user * (making the request). Transaction description can be set via `description` * parameter. * * On failure, Vingd Exception is thrown. * */ public void RewardUser(string huid, double amount, string description) { var parameters = new Dictionary<string, object>(); parameters.Add("huid_to", huid); parameters.Add("amount", (int)(amount * 100)); parameters.Add("description", description); Request("POST", "/rewards/", parameters); } public void RewardUser(string huid, double amount) { RewardUser(huid, amount, null); } } public struct VingdOrder { public long id; public long oid; public double price; public string context; public DateTimeOffset expires; private string frontendURL; public VingdOrder(long id, long oid, double price, string context, DateTimeOffset expires, string frontendURL) { this.id = id; this.oid = oid; this.price = price; this.context = context; this.expires = expires; this.frontendURL = frontendURL; } public string GetRedirectURL() { return frontendURL + "/orders/" + id + "/add/"; } public string GetPopupURL() { return frontendURL + "/popup/orders/" + id + "/add/"; } } public struct VingdPurchase { public string huid; public long oid; public long orderid; public long purchaseid; public long transferid; public string context; public bool reclaimed; } public struct VingdVoucher { public double amount; public long transferid; public DateTimeOffset expires; public string code; private string frontendURL; public VingdVoucher(double amount, long transferid, DateTimeOffset expires, string code, string frontendURL) { this.amount = amount; this.transferid = transferid; this.expires = expires; this.code = code; this.frontendURL = frontendURL; } public string GetRedirectURL() { return frontendURL + "/vouchers/" + code; } public string GetPopupURL() { return frontendURL + "/popup/vouchers/" + code; } } }
// 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. using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; using System; using System.Text; class ZeroBranchRefinement { class TestValue { public int F; } TestValue DisjointEnsures(bool b) { Contract.Ensures(Contract.Result<TestValue>() == null || Contract.Result<TestValue>().F >= 5); if (b) return null; TestValue v = new TestValue(); v.F = 5; return v; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = (int)3, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = (int)23, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = (int)34, MethodILOffset = 0)] public void Test(bool b) { TestValue v = DisjointEnsures(b); if (v == null) return; Contract.Assert(v.F >= 5); } } public class Recursion { Recursion m_child; string s; public Recursion(string owner) { s = owner; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 6, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 15, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 21, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference \'this.s\'", PrimaryILOffset = 26, MethodILOffset = 0)] public Recursion() : this("foo") { this.m_child = this; // this.m_Parent = owner; // Stack overflow on next line analysis this.s.ToString(); //this.m_child.IsOpen = true; } } public class FaultFinallyContexts { static void M(object s) { Contract.Requires(s != null); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 39, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: s != null", PrimaryILOffset = 8, MethodILOffset = 54)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 8, MethodILOffset = 0)] public static void FFCTest1(FaultFinallyContexts obj) { try { Console.WriteLine("TEST"); if (obj == null) { goto End; } } finally { M(obj); Console.WriteLine(obj.ToString()); } End: Console.WriteLine("TEST"); } } class ArrayElements { [Pure] static bool LessThan(int x, int y) { Contract.Ensures(Contract.Result<bool>() == (x < y)); return x < y; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 66, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 66, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 69, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 69, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 83, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 83, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 87, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 87, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 29, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 54, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 66, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 69, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 83, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 87, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 93, MethodILOffset = 0)] void Test2(int[] arr, int i, int j) { Contract.Requires(arr != null); Contract.Requires(i >= 0); Contract.Requires(i < arr.Length); Contract.Requires(j >= 0); Contract.Requires(j < arr.Length); Contract.Requires(LessThan(arr[i], arr[j])); int x = arr[i]; int y = arr[j]; Contract.Assert(x < y); } } namespace OldHandlingOfStack { public struct S { public T t; } public struct T { public int x; } public class Config { [Pure] [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=13,MethodILOffset=28)] public static bool PureMethod(int a, int b, int c, int d, int e, int f) { Contract.Ensures(Contract.Result<bool>() == f > b); return f > b; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=44,MethodILOffset=55)] static int Test(S s) { Contract.Requires(s.t.x > 0); Contract.Ensures(PureMethod(1, 0, 3, 4, 5, s.t.x)); return 0; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=17,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=16,MethodILOffset=23)] static void Main() { S s = new S(); s.t.x = 1; Test(s); } } } namespace RecursiveExpressions { class Repro { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=26,MethodILOffset=71)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=57,MethodILOffset=71)] public static bool Test(out string result) { Contract.Ensures(!(!Contract.Result<bool>() == (Contract.ValueAtReturn(out result) != null))); Contract.Ensures(!(!Contract.Result<bool>() == (Contract.ValueAtReturn(out result) != null))); result = null; return false; } } }
// // Copyright 2011-2013, Xamarin 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 Geolocator.Plugin.Abstractions; using System; using System.Threading.Tasks; using Android.Locations; using System.Threading; using System.Collections.Generic; using Android.App; using Android.OS; using System.Linq; using Android.Content; using Android.Content.PM; namespace Geolocator.Plugin { /// <summary> /// Implementation for Feature /// </summary> public class GeolocatorImplementation : IGeolocator { public GeolocatorImplementation() { DesiredAccuracy = 50; this.manager = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService); this.providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } /// <inheritdoc/> public event EventHandler<PositionErrorEventArgs> PositionError; /// <inheritdoc/> public event EventHandler<PositionEventArgs> PositionChanged; /// <inheritdoc/> public bool IsListening { get { return this.listener != null; } } /// <inheritdoc/> public double DesiredAccuracy { get; set; } /// <inheritdoc/> public bool SupportsHeading { get { return false; // if (this.headingProvider == null || !this.manager.IsProviderEnabled (this.headingProvider)) // { // Criteria c = new Criteria { BearingRequired = true }; // string providerName = this.manager.GetBestProvider (c, enabledOnly: false); // // LocationProvider provider = this.manager.GetProvider (providerName); // // if (provider.SupportsBearing()) // { // this.headingProvider = providerName; // return true; // } // else // { // this.headingProvider = null; // return false; // } // } // else // return true; } } /// <inheritdoc/> public bool IsGeolocationAvailable { get { return this.providers.Length > 0; } } /// <inheritdoc/> public bool IsGeolocationEnabled { get { return this.providers.Any(this.manager.IsProviderEnabled); } } private bool CheckPermission(string permission) { var res = Android.App.Application.Context.CheckCallingOrSelfPermission(permission); return (res == Permission.Granted); } /// <inheritdoc/> public Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? cancelToken = null, bool includeHeading = false) { if (!CheckPermission("android.permission.ACCESS_COARSE_LOCATION")) { Console.WriteLine("Unable to get location, ACCESS_COARSE_LOCATION not set."); return null; } if (!CheckPermission("android.permission.ACCESS_FINE_LOCATION")) { Console.WriteLine("Unable to get location, ACCESS_FINE_LOCATION not set."); return null; } if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite) throw new ArgumentOutOfRangeException("timeoutMilliseconds", "timeout must be greater than or equal to 0"); if (!cancelToken.HasValue) cancelToken = CancellationToken.None; var tcs = new TaskCompletionSource<Position>(); if (!IsListening) { GeolocationSingleListener singleListener = null; singleListener = new GeolocationSingleListener((float)DesiredAccuracy, timeoutMilliseconds, this.providers.Where(this.manager.IsProviderEnabled), finishedCallback: () => { for (int i = 0; i < this.providers.Length; ++i) this.manager.RemoveUpdates(singleListener); }); if (cancelToken != CancellationToken.None) { cancelToken.Value.Register(() => { singleListener.Cancel(); for (int i = 0; i < this.providers.Length; ++i) this.manager.RemoveUpdates(singleListener); }, true); } try { Looper looper = Looper.MyLooper() ?? Looper.MainLooper; int enabled = 0; for (int i = 0; i < this.providers.Length; ++i) { if (this.manager.IsProviderEnabled(this.providers[i])) enabled++; this.manager.RequestLocationUpdates(this.providers[i], 0, 0, singleListener, looper); } if (enabled == 0) { for (int i = 0; i < this.providers.Length; ++i) this.manager.RemoveUpdates(singleListener); tcs.SetException(new GeolocationException(GeolocationError.PositionUnavailable)); return tcs.Task; } } catch (Java.Lang.SecurityException ex) { tcs.SetException(new GeolocationException(GeolocationError.Unauthorized, ex)); return tcs.Task; } return singleListener.Task; } // If we're already listening, just use the current listener lock (this.positionSync) { if (this.lastPosition == null) { if (cancelToken != CancellationToken.None) { cancelToken.Value.Register(() => tcs.TrySetCanceled()); } EventHandler<PositionEventArgs> gotPosition = null; gotPosition = (s, e) => { tcs.TrySetResult(e.Position); PositionChanged -= gotPosition; }; PositionChanged += gotPosition; } else { tcs.SetResult(this.lastPosition); } } return tcs.Task; } /// <inheritdoc/> public void StartListening(int minTime, double minDistance, bool includeHeading = false) { if (minTime < 0) throw new ArgumentOutOfRangeException("minTime"); if (minDistance < 0) throw new ArgumentOutOfRangeException("minDistance"); if (IsListening) throw new InvalidOperationException("This Geolocator is already listening"); this.listener = new GeolocationContinuousListener(this.manager, TimeSpan.FromMilliseconds(minTime), this.providers); this.listener.PositionChanged += OnListenerPositionChanged; this.listener.PositionError += OnListenerPositionError; Looper looper = Looper.MyLooper() ?? Looper.MainLooper; for (int i = 0; i < this.providers.Length; ++i) this.manager.RequestLocationUpdates(providers[i], minTime, (float)minDistance, listener, looper); } /// <inheritdoc/> public void StopListening() { if (this.listener == null) return; this.listener.PositionChanged -= OnListenerPositionChanged; this.listener.PositionError -= OnListenerPositionError; for (int i = 0; i < this.providers.Length; ++i) this.manager.RemoveUpdates(this.listener); this.listener = null; } private readonly string[] providers; private readonly LocationManager manager; private string headingProvider; private GeolocationContinuousListener listener; private readonly object positionSync = new object(); private Position lastPosition; /// <inheritdoc/> private void OnListenerPositionChanged(object sender, PositionEventArgs e) { if (!IsListening) // ignore anything that might come in afterwards return; lock (this.positionSync) { this.lastPosition = e.Position; var changed = PositionChanged; if (changed != null) changed(this, e); } } /// <inheritdoc/> private void OnListenerPositionError(object sender, PositionErrorEventArgs e) { StopListening(); var error = PositionError; if (error != null) error(this, e); } private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static DateTimeOffset GetTimestamp(Location location) { return new DateTimeOffset(Epoch.AddMilliseconds(location.Time)); } } }
#region copyright // VZF // Copyright (C) 2014-2016 Vladimir Zakharov // // http://www.code.coolhobby.ru/ // File DB.cs created on 2.6.2015 in 6:31 AM. // Last changed on 5.21.2016 in 1:10 PM. // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion namespace YAF.Providers.Membership { using System; using System.Text; using System.Data; using System.Web.Security; using VZF.Data.DAL; using YAF.Classes; using YAF.Classes.Pattern; using YAF.Core; /// <summary> /// The fb db. /// </summary> public class FbDB { // private FbDbAccess FbDbAccess = new FbDbAccess(); /// <summary> /// Gets the current. /// </summary> public static FbDB Current { get { return PageSingleton<FbDB>.Instance; } } /// <summary> /// The upgrade membership. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="I_PREVIOUSVERSION"> /// The previous version. /// </param> /// <param name="I_NEWVERSION"> /// The new version. /// </param> public void UpgradeMembership(string connectionStringName, int I_PREVIOUSVERSION, int I_NEWVERSION) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { // sc.DataSource.ProviderName sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PREVIOUSVERSION", I_PREVIOUSVERSION)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_NEWVERSION", I_NEWVERSION)); sc.CommandText.AppendObjectQuery("p_upgrade", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); } } /// <summary> /// The change password. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="newPassword"> /// The new password. /// </param> /// <param name="newSalt"> /// The new salt. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="newPasswordAnswer"> /// The new password answer. /// </param> public void ChangePassword(string connectionStringName, string appName, string username, string newPassword, string newSalt, int passwordFormat, string newPasswordAnswer) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); // sc.DataSource.ProviderName sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", username)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORD", newPassword)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDSALT", newSalt)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDFORMAT", passwordFormat)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDANSWER", newPasswordAnswer)); sc.CommandText.AppendObjectQuery("P_changepassword", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); } } /// <summary> /// The change password question and answer. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="passwordQuestion"> /// The password question. /// </param> /// <param name="passwordAnswer"> /// The password answer. /// </param> public void ChangePasswordQuestionAndAnswer(string connectionStringName, string appName, string username, string passwordQuestion, string passwordAnswer) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); // sc.DataSource.ProviderName sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", username)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDQUESTION", passwordQuestion)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDANSWER", passwordAnswer)); sc.CommandText.AppendObjectQuery("P_CHANGEPASSQUESTIONANDANSWER", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); } } /// <summary> /// The create user. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="password"> /// The password. /// </param> /// <param name="passwordSalt"> /// The password salt. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="email"> /// The email. /// </param> /// <param name="passwordQuestion"> /// The password question. /// </param> /// <param name="passwordAnswer"> /// The password answer. /// </param> /// <param name="isApproved"> /// The is approved. /// </param> /// <param name="providerUserKey"> /// The provider user key. /// </param> public void CreateUser(string connectionStringName, string appName, string username, string password, string passwordSalt, int passwordFormat, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", username)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORD", password)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDSALT", passwordSalt)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDFORMAT", passwordFormat.ToString())); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_EMAIL", email)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDQUESTION", passwordQuestion)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_PASSWORDANSWER", passwordAnswer)); sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "I_ISAPPROVED", isApproved)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERKEY", providerUserKey)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_UTCTIMESTAMP", DateTime.UtcNow)); sc.CommandText.AppendObjectQuery("P_CREATEUSER", connectionStringName); providerUserKey = sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false).Rows[0][0]; } } /// <summary> /// The delete user. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="deleteAllRelatedData"> /// The delete all related data. /// </param> public void DeleteUser(string connectionStringName, string appName, string username, bool deleteAllRelatedData) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", username)); sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_deleteallrelated", deleteAllRelatedData)); sc.CommandText.AppendObjectQuery("P_deleteuser", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); } } /// <summary> /// The find users by email. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="emailToMatch"> /// The email to match. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable FindUsersByEmail(string connectionStringName, string appName, string emailToMatch, int pageIndex, int pageSize) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_emailaddress", emailToMatch)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pageindex", pageIndex)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pagesize", pageSize)); sc.CommandText.AppendObjectQuery("P_FINDUSERSBYEMAIL", connectionStringName); return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false); } } /// <summary> /// The find users by name. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="usernameToMatch"> /// The username to match. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable FindUsersByName(string connectionStringName, string appName, string usernameToMatch, int pageIndex, int pageSize) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", usernameToMatch)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pageindex", pageIndex)); // TODO:fix overflow bug sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pagesize", pageSize == int.MaxValue ? 1 : pageSize)); sc.CommandText.AppendObjectQuery("P_FINDUSERSBYNAME", connectionStringName); return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false); } } /// <summary> /// The get all users. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable GetAllUsers(string connectionStringName, string appName, int pageIndex, int pageSize) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pageindex", pageIndex)); // TODO:fix overflow bug sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pagesize", pageSize == int.MaxValue ? 1 : pageSize)); sc.CommandText.AppendObjectQuery("P_getallusers", connectionStringName); return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false); } } /// <summary> /// The get number of users online. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="TimeWindow"> /// The time window. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int GetNumberOfUsersOnline(string connectionStringName, string appName, int TimeWindow) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "I_TIMEWINDOW", TimeWindow)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_currenttimeutc", DateTime.UtcNow)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_returnvalue", null, ParameterDirection.ReturnValue)); sc.CommandText.AppendObjectQuery("P_getnumberofusersonline", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); return Convert.ToInt32(sc.Parameters["@i_returnvalue"].Value); } } /// <summary> /// The get user. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="providerUserKey"> /// The provider user key. /// </param> /// <param name="userName"> /// The user name. /// </param> /// <param name="userIsOnline"> /// The user is online. /// </param> /// <returns> /// The <see cref="DataRow"/>. /// </returns> public DataRow GetUser(string connectionStringName, string appName, object providerUserKey, string userName, bool userIsOnline) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { // sc.DataSource.ProviderName sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", userName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERKEY", providerUserKey)); sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "I_USERISONLINE", Convert.ToInt32(userIsOnline))); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_UTCTIMESTAMP", DateTime.UtcNow)); sc.CommandText.AppendObjectQuery("P_GETUSER", connectionStringName); using (var dt = sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, true)) { var dr = dt.Rows[0]; return dr["UserID"] != DBNull.Value ? dt.Rows[0] : null; } } } /// <summary> /// The get user password info. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="updateUser"> /// The update user. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable GetUserPasswordInfo(string connectionStringName, string appName, string username, bool updateUser) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", username)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERKEY", DBNull.Value)); sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "I_USERISONLINE", updateUser)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_UTCTIMESTAMP", DateTime.UtcNow)); sc.CommandText.AppendObjectQuery("P_getuser", connectionStringName); return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false); } } /// <summary> /// The get user name by email. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="email"> /// The email. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable GetUserNameByEmail(string connectionStringName, string appName, string email) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_EMAIL", email)); sc.CommandText.AppendObjectQuery("P_GETUSERNAMEBYEMAL", connectionStringName); return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false); } } /// <summary> /// The reset password. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="userName"> /// The user name. /// </param> /// <param name="password"> /// The password. /// </param> /// <param name="passwordSalt"> /// The password salt. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="maxInvalidPasswordAttempts"> /// The max invalid password attempts. /// </param> /// <param name="passwordAttemptWindow"> /// The password attempt window. /// </param> public void ResetPassword(string connectionStringName, string appName, string userName, string password, string passwordSalt, int passwordFormat, int maxInvalidPasswordAttempts, int passwordAttemptWindow) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", userName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_password", password)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordsalt", passwordSalt)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordformat", passwordFormat)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_maxinvalidattempts", maxInvalidPasswordAttempts)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_passwordattemptwindow", passwordAttemptWindow)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_currenttimeutc", DateTime.UtcNow)); sc.CommandText.AppendObjectQuery("P_resetpassword", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); } } /// <summary> /// The unlock user. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="userName"> /// The user name. /// </param> public void UnlockUser(string connectionStringName, string appName, string userName) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", userName)); sc.CommandText.AppendObjectQuery("P_unlockuser", connectionStringName); sc.ExecuteNonQuery(CommandType.StoredProcedure); } } /// <summary> /// The update user. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="user"> /// The user. /// </param> /// <param name="requiresUniqueEmail"> /// The requires unique email. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int UpdateUser(string connectionStringName, object appName, MembershipUser user, bool requiresUniqueEmail) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_userkey", user.ProviderUserKey)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", user.UserName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_EMAIL", user.Email)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_COMMENT", user.Comment)); sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_isapproved", user.IsApproved)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_LASTLOGIN", user.LastLoginDate)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_LASTACTIVITY", user.LastActivityDate)); sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "I_UNIQUEEMAIL", requiresUniqueEmail)); sc.CommandText.AppendObjectQuery("P_updateuser", connectionStringName); return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure)); } } } }
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using System.Collections.Generic; namespace UIWidgets { /// <summary> /// Centered slider base class (zero at center, positive and negative parts have different scales). /// </summary> public abstract class CenteredSliderBase<T> : UIBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler where T : struct { /// <summary> /// OnChangeEvent /// </summary> [System.Serializable] public class OnChangeEvent: UnityEvent<T> { } /// <summary> /// Value. /// </summary> [SerializeField] protected T _value; /// <summary> /// Gets or sets the value. /// </summary> /// <value>Value.</value> public T Value { get { return _value; } set { SetValue(value); } } /// <summary> /// The minimum limit. /// </summary> [SerializeField] protected T limitMin; /// <summary> /// Gets or sets the minimum limit. /// </summary> /// <value>The minimum limit.</value> public T LimitMin { get { return limitMin; } set { limitMin = value; SetValue(_value); } } /// <summary> /// The maximum limit. /// </summary> [SerializeField] protected T limitMax; /// <summary> /// Gets or sets the maximum limit. /// </summary> /// <value>The maximum limit.</value> public T LimitMax { get { return limitMax; } set { limitMax = value; SetValue(_value); } } /// <summary> /// The use value limits. /// </summary> [SerializeField] protected bool useValueLimits; /// <summary> /// Gets or sets use value limits. /// </summary> /// <value><c>true</c> if use value limits; otherwise, <c>false</c>.</value> public bool UseValueLimits { get { return useValueLimits; } set { useValueLimits = value; SetValue(_value); } } /// <summary> /// The value minimum limit. /// </summary> [SerializeField] protected T valueMin; /// <summary> /// Gets or sets the value minimum limit. /// </summary> /// <value>The value minimum limit.</value> public T ValueMin { get { return valueMin; } set { valueMin = value; SetValue(_value); } } /// <summary> /// The value maximum limit. /// </summary> [SerializeField] protected T valueMax; /// <summary> /// Gets or sets the value maximum limit. /// </summary> /// <value>The maximum limit.</value> public T ValueMax { get { return valueMax; } set { valueMax = value; SetValue(_value); } } /// <summary> /// The step. /// </summary> [SerializeField] protected T step; /// <summary> /// Gets or sets the step. /// </summary> /// <value>The step.</value> public T Step { get { return step; } set { step = value; } } /// <summary> /// Whole number of steps. /// </summary> public bool WholeNumberOfSteps = false; /// <summary> /// The handle. /// </summary> [SerializeField] protected RangeSliderHandle handle; /// <summary> /// The handle rect. /// </summary> protected RectTransform handleRect; /// <summary> /// Gets the handle rect. /// </summary> /// <value>The handle rect.</value> public RectTransform HandleRect { get { if (handle!=null && handleRect==null) { handleRect = handle.transform as RectTransform; } return handleRect; } } /// <summary> /// Gets or sets the handle. /// </summary> /// <value>The handle.</value> public RangeSliderHandle Handle { get { return handle; } set { SetHandle(value); } } /// <summary> /// The usable range rect. /// </summary> [SerializeField] protected RectTransform UsableRangeRect; /// <summary> /// The fill rect. /// </summary> [SerializeField] protected RectTransform FillRect; /// <summary> /// The range slider rect. /// </summary> protected RectTransform rangeSliderRect; /// <summary> /// Gets the handle maximum rect. /// </summary> /// <value>The handle maximum rect.</value> public RectTransform RangeSliderRect { get { if (rangeSliderRect==null) { rangeSliderRect = transform as RectTransform; } return rangeSliderRect; } } /// <summary> /// OnValuesChange event. /// </summary> public OnChangeEvent OnValuesChange = new OnChangeEvent(); /// <summary> /// OnChange event. /// </summary> public UnityEvent OnChange = new UnityEvent(); /// <summary> /// Is init called? /// </summary> bool isInitCalled; /// <summary> /// Init this instance. /// </summary> protected virtual void Init() { if (isInitCalled) { return ; } isInitCalled = true; SetHandle(handle); UpdateHandle(); UpdateFill(); } /// <summary> /// Implementation of a callback that is sent if an associated RectTransform has it's dimensions changed. /// </summary> protected override void OnRectTransformDimensionsChange() { UpdateHandle(); UpdateFill(); } /// <summary> /// Called by a BaseInputModule when an OnPointerDown event occurs. /// </summary> /// <param name="eventData">Event data.</param> public void OnPointerDown(PointerEventData eventData) { } /// <summary> /// Called by a BaseInputModule when an OnPointerUp event occurs. /// </summary> /// <param name="eventData">Event data.</param> public void OnPointerUp(PointerEventData eventData) { } /// <summary> /// Sets the value. /// </summary> /// <param name="value">Value.</param> protected virtual void SetValue(T value) { if (!EqualityComparer<T>.Default.Equals(_value, InBounds(value))) { _value = InBounds(value); UpdateHandle(); OnValuesChange.Invoke(_value); OnChange.Invoke(); } } /// <summary> /// Sets the handle. /// </summary> /// <param name="value">Value.</param> protected virtual void SetHandle(RangeSliderHandle value) { handle = value; handle.IsHorizontal = IsHorizontal; handle.PositionLimits = PositionLimits; handle.PositionChanged = UpdateValue; handle.Increase = Increase; handle.Decrease = Decrease; } /// <summary> /// Start this instance. /// </summary> protected override void Start() { Init(); } /// <summary> /// Sets the limits. /// </summary> /// <param name="min">Minimum.</param> /// <param name="max">Max.</param> public void SetLimit(T min, T max) { // set limits to skip InBounds check limitMin = min; limitMax = max; // set limits with InBounds check and update handle's positions LimitMin = limitMin; LimitMax = limitMax; } /// <summary> /// Sets the value limits. /// </summary> /// <param name="min">Minimum.</param> /// <param name="max">Max.</param> public void SetValueLimit(T min, T max) { // set limits to skip InBounds check valueMin = min; valueMax = max; // set limits with InBounds check and update handle's positions ValueMin = valueMin; ValueMax = valueMax; } /// <summary> /// Determines whether this instance is horizontal. /// </summary> /// <returns><c>true</c> if this instance is horizontal; otherwise, <c>false</c>.</returns> protected virtual bool IsHorizontal() { return true; } /// <summary> /// Returns size of usable rect. /// </summary> /// <returns>The size.</returns> protected float RangeSize() { return (IsHorizontal()) ? UsableRangeRect.rect.width : UsableRangeRect.rect.height; } /// <summary> /// Size of the handle. /// </summary> /// <returns>The handle size.</returns> protected float HandleSize() { return (IsHorizontal()) ? HandleRect.rect.width : HandleRect.rect.height; } /// <summary> /// Updates the minimum value. /// </summary> /// <param name="position">Position.</param> protected void UpdateValue(float position) { _value = PositionToValue(position - GetStartPoint()); UpdateHandle(); OnValuesChange.Invoke(_value); OnChange.Invoke(); } /// <summary> /// Value to position. /// </summary> /// <returns>Position.</returns> /// <param name="value">Value.</param> protected abstract float ValueToPosition(T value); /// <summary> /// Position to value. /// </summary> /// <returns>Value.</returns> /// <param name="position">Position.</param> protected abstract T PositionToValue(float position); /// <summary> /// Gets the start point. /// </summary> /// <returns>The start point.</returns> protected float GetStartPoint() { return IsHorizontal() ? -UsableRangeRect.sizeDelta.x / 2f : -UsableRangeRect.sizeDelta.y / 2f; } /// <summary> /// Position range for minimum handle. /// </summary> /// <returns>The position limits.</returns> protected abstract Vector2 PositionLimits(); /// <summary> /// Fit value to bounds. /// </summary> /// <returns>Value.</returns> /// <param name="value">Value.</param> protected abstract T InBounds(T value); /// <summary> /// Increases the minimum value. /// </summary> protected abstract void Increase(); /// <summary> /// Decreases the minimum value. /// </summary> protected abstract void Decrease(); /// <summary> /// Updates the handle. /// </summary> protected void UpdateHandle() { var new_position = HandleRect.anchoredPosition; if (IsHorizontal()) { new_position.x = ValueToPosition(_value) + HandleRect.rect.width * (HandleRect.pivot.x - 0.5f); } else { new_position.y = ValueToPosition(_value) + HandleRect.rect.width * (HandleRect.pivot.x - 0.5f); } HandleRect.anchoredPosition = new_position; UpdateFill(); } /// <summary> /// Determines whether this instance is positive value. /// </summary> /// <returns><c>true</c> if this instance is positive value; otherwise, <c>false</c>.</returns> protected abstract bool IsPositiveValue(); /// <summary> /// Updates the fill size. /// </summary> protected virtual void UpdateFill() { FillRect.anchorMin = new Vector2(0.5f, 0.5f); FillRect.anchorMax = new Vector2(0.5f, 0.5f);//1.0 if (IsHorizontal()) { if (IsPositiveValue()) { FillRect.pivot = new Vector2(0.0f, 0.5f); FillRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, HandleRect.localPosition.x - UsableRangeRect.localPosition.x); } else { FillRect.pivot = new Vector2(1.0f, 0.5f); FillRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, UsableRangeRect.localPosition.x - HandleRect.localPosition.x); } } else { if (IsPositiveValue()) { FillRect.pivot = new Vector2(0.5f, 0.0f); FillRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, HandleRect.localPosition.y - UsableRangeRect.localPosition.y); } else { FillRect.pivot = new Vector2(0.5f, 1.0f); FillRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, UsableRangeRect.localPosition.y - HandleRect.localPosition.y); } } } /// <summary> /// Raises the pointer click event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnPointerClick(PointerEventData eventData) { if (eventData.button!=PointerEventData.InputButton.Left) { return; } Vector2 curCursor; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(UsableRangeRect, eventData.position, eventData.pressEventCamera, out curCursor)) { return ; } curCursor -= UsableRangeRect.rect.position; var new_position = (IsHorizontal() ? curCursor.x : curCursor.y) + GetStartPoint(); UpdateValue(new_position); } #if UNITY_EDITOR /// <summary> /// Handle values change from editor. /// </summary> public void EditorUpdate() { if (handle!=null && UsableRangeRect!=null && FillRect!=null) { UpdateHandle(); } } #endif } }
using YAF.Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Diagnostics; namespace YAF.Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Access to the Field Info file that describes document fields and whether or /// not they are indexed. Each segment has a separate Field Info file. Objects /// of this class are thread-safe for multiple readers, but only one thread can /// be adding documents at a time, with no other reader or writer threads /// accessing this object. /// </summary> public sealed class FieldInfo { /// <summary> /// Field's name </summary> public string Name { get; private set; } /// <summary> /// Internal field number </summary> public int Number { get; private set; } private bool indexed; private DocValuesType docValueType; // True if any document indexed term vectors private bool storeTermVector; private DocValuesType normType; private bool omitNorms; // omit norms associated with indexed fields private IndexOptions indexOptions; private bool storePayloads; // whether this field stores payloads together with term positions private IDictionary<string, string> attributes; private long dvGen = -1; // the DocValues generation of this field // LUCENENET specific: De-nested the IndexOptions and DocValuesType enums from this class to prevent naming conflicts /// <summary> /// Sole Constructor. /// <para/> /// @lucene.experimental /// </summary> public FieldInfo(string name, bool indexed, int number, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions, DocValuesType docValues, DocValuesType normsType, IDictionary<string, string> attributes) { this.Name = name; this.indexed = indexed; this.Number = number; this.docValueType = docValues; if (indexed) { this.storeTermVector = storeTermVector; this.storePayloads = storePayloads; this.omitNorms = omitNorms; this.indexOptions = indexOptions; this.normType = !omitNorms ? normsType : DocValuesType.NONE; } // for non-indexed fields, leave defaults else { this.storeTermVector = false; this.storePayloads = false; this.omitNorms = false; this.indexOptions = IndexOptions.NONE; this.normType = DocValuesType.NONE; } this.attributes = attributes; if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency()); } private bool CheckConsistency() { if (!indexed) { if (Debugging.AssertsEnabled) { Debugging.Assert(!storeTermVector); Debugging.Assert(!storePayloads); Debugging.Assert(!omitNorms); Debugging.Assert(normType == DocValuesType.NONE); Debugging.Assert(indexOptions == IndexOptions.NONE); } } else { if (Debugging.AssertsEnabled) Debugging.Assert(indexOptions != IndexOptions.NONE); if (omitNorms) { if (Debugging.AssertsEnabled) Debugging.Assert(normType == DocValuesType.NONE); } // Cannot store payloads unless positions are indexed: // LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare() if (Debugging.AssertsEnabled) Debugging.Assert(IndexOptionsComparer.Default.Compare(indexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 || !this.storePayloads); } return true; } internal void Update(IIndexableFieldType ft) { Update(ft.IsIndexed, false, ft.OmitNorms, false, ft.IndexOptions); } // should only be called by FieldInfos#addOrUpdate internal void Update(bool indexed, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions) { //System.out.println("FI.update field=" + name + " indexed=" + indexed + " omitNorms=" + omitNorms + " this.omitNorms=" + this.omitNorms); if (this.indexed != indexed) { this.indexed = true; // once indexed, always index } if (indexed) // if updated field data is not for indexing, leave the updates out { if (this.storeTermVector != storeTermVector) { this.storeTermVector = true; // once vector, always vector } if (this.storePayloads != storePayloads) { this.storePayloads = true; } if (this.omitNorms != omitNorms) { this.omitNorms = true; // if one require omitNorms at least once, it remains off for life this.normType = DocValuesType.NONE; } if (this.indexOptions != indexOptions) { if (this.indexOptions == IndexOptions.NONE) { this.indexOptions = indexOptions; } else { // downgrade // LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare() this.indexOptions = IndexOptionsComparer.Default.Compare(this.indexOptions, indexOptions) < 0 ? this.indexOptions : indexOptions; } // LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare() if (IndexOptionsComparer.Default.Compare(this.indexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) { // cannot store payloads if we don't store positions: this.storePayloads = false; } } } if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency()); } public DocValuesType DocValuesType { get => docValueType; internal set { if (docValueType != DocValuesType.NONE && docValueType != value) { throw new ArgumentException("cannot change DocValues type from " + docValueType + " to " + value + " for field \"" + Name + "\""); } docValueType = value; if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency()); } } /// <summary> /// Returns <see cref="Index.IndexOptions"/> for the field, or <c>null</c> if the field is not indexed </summary> public IndexOptions IndexOptions => indexOptions; /// <summary> /// Returns <c>true</c> if this field has any docValues. /// </summary> public bool HasDocValues => docValueType != DocValuesType.NONE; /// <summary> /// Gets or Sets the docValues generation of this field, or -1 if no docValues. </summary> public long DocValuesGen { get => dvGen; set => this.dvGen = value; } /// <summary> /// Returns <see cref="Index.DocValuesType"/> of the norm. This may be <see cref="DocValuesType.NONE"/> if the field has no norms. /// </summary> public DocValuesType NormType { get => normType; internal set { if (normType != DocValuesType.NONE && normType != value) { throw new ArgumentException("cannot change Norm type from " + normType + " to " + value + " for field \"" + Name + "\""); } normType = value; if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency()); } } internal void SetStoreTermVectors() { storeTermVector = true; if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency()); } internal void SetStorePayloads() { // LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare() if (indexed && IndexOptionsComparer.Default.Compare(indexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) { storePayloads = true; } if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency()); } /// <summary> /// Returns <c>true</c> if norms are explicitly omitted for this field /// </summary> public bool OmitsNorms => omitNorms; /// <summary> /// Returns <c>true</c> if this field actually has any norms. /// </summary> public bool HasNorms => normType != DocValuesType.NONE; /// <summary> /// Returns <c>true</c> if this field is indexed. /// </summary> public bool IsIndexed => indexed; /// <summary> /// Returns <c>true</c> if any payloads exist for this field. /// </summary> public bool HasPayloads => storePayloads; /// <summary> /// Returns <c>true</c> if any term vectors exist for this field. /// </summary> public bool HasVectors => storeTermVector; /// <summary> /// Get a codec attribute value, or <c>null</c> if it does not exist /// </summary> public string GetAttribute(string key) { if (attributes is null) { return null; } else { attributes.TryGetValue(key, out string ret); return ret; } } /// <summary> /// Puts a codec attribute value. /// <para/> /// this is a key-value mapping for the field that the codec can use /// to store additional metadata, and will be available to the codec /// when reading the segment via <see cref="GetAttribute(string)"/> /// <para/> /// If a value already exists for the field, it will be replaced with /// the new value. /// </summary> public string PutAttribute(string key, string value) { if (attributes is null) { attributes = new Dictionary<string, string>(); } // The key was not previously assigned, null will be returned if (!attributes.TryGetValue(key, out string ret)) { ret = null; } attributes[key] = value; return ret; } /// <summary> /// Returns internal codec attributes map. May be <c>null</c> if no mappings exist. /// </summary> public IDictionary<string, string> Attributes => attributes; } /// <summary> /// Controls how much information is stored in the postings lists. /// <para/> /// @lucene.experimental /// </summary> public enum IndexOptions // LUCENENET specific: de-nested from FieldInfo to prevent naming collisions { // NOTE: order is important here; FieldInfo uses this // order to merge two conflicting IndexOptions (always // "downgrades" by picking the lowest). /// <summary> /// No index options will be used. /// <para/> /// NOTE: This is the same as setting to <c>null</c> in Lucene /// </summary> // LUCENENET specific NONE, /// <summary> /// Only documents are indexed: term frequencies and positions are omitted. /// Phrase and other positional queries on the field will throw an exception, and scoring /// will behave as if any term in the document appears only once. /// </summary> // TODO: maybe rename to just DOCS? DOCS_ONLY, /// <summary> /// Only documents and term frequencies are indexed: positions are omitted. /// this enables normal scoring, except Phrase and other positional queries /// will throw an exception. /// </summary> DOCS_AND_FREQS, /// <summary> /// Indexes documents, frequencies and positions. /// this is a typical default for full-text search: full scoring is enabled /// and positional queries are supported. /// </summary> DOCS_AND_FREQS_AND_POSITIONS, /// <summary> /// Indexes documents, frequencies, positions and offsets. /// Character offsets are encoded alongside the positions. /// </summary> DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS } /// <summary> /// DocValues types. /// Note that DocValues is strongly typed, so a field cannot have different types /// across different documents. /// </summary> public enum DocValuesType // LUCENENET specific: de-nested from FieldInfo to prevent naming collisions { /// <summary> /// No doc values type will be used. /// <para/> /// NOTE: This is the same as setting to <c>null</c> in Lucene /// </summary> // LUCENENET specific NONE, // LUCENENET NOTE: The value of this option is 0, which is the default value for any .NET value type /// <summary> /// A per-document numeric type /// </summary> NUMERIC, /// <summary> /// A per-document <see cref="T:byte[]"/>. Values may be larger than /// 32766 bytes, but different codecs may enforce their own limits. /// </summary> BINARY, /// <summary> /// A pre-sorted <see cref="T:byte[]"/>. Fields with this type only store distinct byte values /// and store an additional offset pointer per document to dereference the shared /// byte[]. The stored byte[] is presorted and allows access via document id, /// ordinal and by-value. Values must be &lt;= 32766 bytes. /// </summary> SORTED, /// <summary> /// A pre-sorted ISet&lt;byte[]&gt;. Fields with this type only store distinct byte values /// and store additional offset pointers per document to dereference the shared /// <see cref="T:byte[]"/>s. The stored <see cref="T:byte[]"/> is presorted and allows access via document id, /// ordinal and by-value. Values must be &lt;= 32766 bytes. /// </summary> SORTED_SET } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class RemoveMemberDecoder { public const ushort BLOCK_LENGTH = 8; public const ushort TEMPLATE_ID = 35; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private RemoveMemberDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public RemoveMemberDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public RemoveMemberDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int MemberIdId() { return 1; } public static int MemberIdSinceVersion() { return 0; } public static int MemberIdEncodingOffset() { return 0; } public static int MemberIdEncodingLength() { return 4; } public static string MemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int MemberIdNullValue() { return -2147483648; } public static int MemberIdMinValue() { return -2147483647; } public static int MemberIdMaxValue() { return 2147483647; } public int MemberId() { return _buffer.GetInt(_offset + 0, ByteOrder.LittleEndian); } public static int IsPassiveId() { return 2; } public static int IsPassiveSinceVersion() { return 0; } public static int IsPassiveEncodingOffset() { return 4; } public static int IsPassiveEncodingLength() { return 4; } public static string IsPassiveMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public BooleanType IsPassive() { return (BooleanType)_buffer.GetInt(_offset + 4, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[RemoveMember](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("MemberId="); builder.Append(MemberId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='isPassive', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=4, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=BEGIN_ENUM, name='BooleanType', referencedName='null', description='Language independent boolean type.', id=-1, version=0, deprecated=0, encodedLength=4, offset=4, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}} builder.Append("IsPassive="); builder.Append(IsPassive()); Limit(originalLimit); return builder; } } }
// Copyright Structured Solutions using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text.RegularExpressions; using System.Web.UI; using System.Web.UI.WebControls; using BVSoftware.Bvc5.Core.Catalog; using BVSoftware.Bvc5.Core.Contacts; using BVSoftware.Bvc5.Core.Content; using BVSoftware.Bvc5.Core.Shipping; using StructuredSolutions.Bvc5.Shipping.Providers.Controls; using StructuredSolutions.Bvc5.Shipping.Providers.Settings; using ASPNET = System.Web.UI.WebControls; using ListItem = System.Web.UI.WebControls.ListItem; public partial class BVModules_Shipping_Package_Rules_PackageMatchEditor : UserControl { #region Properties public object DataSource { get { return ViewState["DataSource"]; } set { ViewState["DataSource"] = value; } } public ShippingMethod ShippingMethod { get { return ((BVShippingModule) NamingContainer.NamingContainer.NamingContainer.NamingContainer).ShippingMethod; } } public string Prompt { get { object value = ViewState["Prompt"]; if (value == null) return string.Empty; else return (string) value; } set { ViewState["Prompt"] = value; } } public string RuleId { get { object value = ViewState["RuleId"]; if (value == null) return string.Empty; else return (string) value; } set { ViewState["RuleId"] = value; } } #endregion #region Event Handlers protected void LimitItemPropertyField_SelectedIndexChanged(object sender, EventArgs e) { if (sender != null) { DropDownList itemPropertyField = (DropDownList) sender; ItemProperties itemProperty = (ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue); DropDownList customPropertyField = (DropDownList) itemPropertyField.NamingContainer.FindControl("LimitCustomPropertyField"); HelpLabel customPropertyLabel = (HelpLabel) itemPropertyField.NamingContainer.FindControl("LimitCustomPropertyLabel"); Label multiplierLabel = (Label) itemPropertyField.NamingContainer.FindControl("LimitMultiplierLabel"); HelpLabel limitLabel = (HelpLabel) itemPropertyField.NamingContainer.FindControl("LimitLabel"); TextBox limitField = (TextBox) itemPropertyField.NamingContainer.FindControl("LimitField"); BaseValidator limitRequired = (BaseValidator) itemPropertyField.NamingContainer.FindControl("LimitRequired"); BaseValidator limitNumeric = (BaseValidator) itemPropertyField.NamingContainer.FindControl("LimitNumeric"); PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty); PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, itemProperty); } } protected void LimitPackagePropertyField_SelectedIndexChanged(object sender, EventArgs e) { if (sender != null) { DropDownList propertyField = (DropDownList) sender; PackageProperties packageProperty = (PackageProperties) Enum.Parse(typeof (PackageProperties), propertyField.SelectedValue); DropDownList itemPropertyField = (DropDownList) propertyField.NamingContainer.FindControl("LimitItemPropertyField"); ItemProperties itemProperty = (ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue); DropDownList customPropertyField = (DropDownList) propertyField.NamingContainer.FindControl("LimitCustomPropertyField"); HelpLabel customPropertyLabel = (HelpLabel) propertyField.NamingContainer.FindControl("LimitCustomPropertyLabel"); Label multiplierLabel = (Label) propertyField.NamingContainer.FindControl("LimitMultiplierLabel"); HelpLabel limitLabel = (HelpLabel) propertyField.NamingContainer.FindControl("LimitLabel"); TextBox limitField = (TextBox) propertyField.NamingContainer.FindControl("LimitField"); BaseValidator limitRequired = (BaseValidator) propertyField.NamingContainer.FindControl("LimitRequired"); BaseValidator limitNumeric = (BaseValidator) propertyField.NamingContainer.FindControl("LimitNumeric"); if (packageProperty == PackageProperties.ItemProperty) { itemPropertyField.Visible = true; PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty); PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, itemProperty); } else { itemPropertyField.Visible = false; customPropertyField.Visible = false; PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, packageProperty); Page.Validate("RuleGroup"); if (Page.IsValid) { PrepareCustomPropertyField(customPropertyLabel, customPropertyField, packageProperty); } } } } protected void LimitValidator_Validate(object sender, ServerValidateEventArgs e) { // Do not validate fixed values DropDownList propertyField = (DropDownList) ((Control) sender).NamingContainer.FindControl("LimitPackagePropertyField"); PackageProperties packageProperty = (PackageProperties) Enum.Parse(typeof (PackageProperties), propertyField.SelectedValue); if (packageProperty != PackageProperties.FixedAmountOne && packageProperty != PackageProperties.Separator0) { if (string.IsNullOrEmpty(e.Value)) { e.IsValid = false; } else { Decimal result; e.IsValid = Decimal.TryParse(e.Value, out result); } } else { e.IsValid = true; } } protected void Matches_ItemCommand(object sender, RepeaterCommandEventArgs e) { if (e.CommandName == "New") { PackageMatchList matches = GetMatches(); PackageMatch match = new PackageMatch(); matches.Insert(e.Item.ItemIndex + 1, match); DataSource = matches; DataBindChildren(); } else if (e.CommandName == "Delete") { PackageMatchList matches = GetMatches(); matches.RemoveAt(e.Item.ItemIndex); DataSource = matches; DataBindChildren(); } } protected void Matches_ItemCreated(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { PackageMatchList matches = (PackageMatchList) DataSource; PackageMatch match = matches[e.Item.ItemIndex]; DropDownList packagePropertyList = (DropDownList) e.Item.FindControl("MatchPackagePropertyField"); DropDownList itemPropertyList = (DropDownList) e.Item.FindControl("MatchItemPropertyField"); DropDownList customPropertyList = (DropDownList) e.Item.FindControl("MatchCustomPropertyField"); DropDownList comparisonList = (DropDownList) e.Item.FindControl("MatchComparisonTypeField"); DropDownList limitPackagePropertyList = (DropDownList) e.Item.FindControl("LimitPackagePropertyField"); DropDownList limitItemPropertyList = (DropDownList) e.Item.FindControl("LimitItemPropertyField"); DropDownList limitCustomPropertyList = (DropDownList) e.Item.FindControl("LimitCustomPropertyField"); HelpLabel customPropertyLabel = (HelpLabel) e.Item.FindControl("MatchCustomPropertyLabel"); HelpLabel limitCustomPropertyLabel = (HelpLabel) e.Item.FindControl("LimitCustomPropertyLabel"); Label multiplierLabel = (Label) e.Item.FindControl("LimitMultiplierLabel"); HelpLabel limitLabel = (HelpLabel) e.Item.FindControl("LimitLabel"); TextBox limitField = (TextBox) e.Item.FindControl("LimitField"); BaseValidator limitRequired = (BaseValidator) e.Item.FindControl("LimitRequired"); BaseValidator limitNumeric = (BaseValidator) e.Item.FindControl("LimitNumeric"); packagePropertyList.Items.Clear(); packagePropertyList.Items.AddRange(GetMatchPackageProperties()); itemPropertyList.Items.Clear(); itemPropertyList.Items.AddRange(GetItemProperties()); itemPropertyList.Visible = false; customPropertyList.Visible = false; if (match.PackageProperty == PackageProperties.ItemProperty) { itemPropertyList.Visible = true; PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.ItemProperty); } else { PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.PackageProperty); } if (customPropertyList.Items.Count == 0) customPropertyList.Items.Add(new ListItem("", match.CustomProperty)); if (customPropertyList.Items.FindByValue(match.CustomProperty) == null) match.CustomProperty = customPropertyList.Items[0].Value; comparisonList.Items.Clear(); comparisonList.Items.AddRange(GetComparisons()); limitPackagePropertyList.Items.Clear(); limitPackagePropertyList.Items.AddRange(GetLimitPackageProperties()); limitItemPropertyList.Items.Clear(); limitItemPropertyList.Items.AddRange(GetItemProperties()); limitItemPropertyList.Visible = false; limitCustomPropertyList.Visible = false; multiplierLabel.Visible = match.LimitPackageProperty != PackageProperties.FixedAmountOne; if (match.LimitPackageProperty == PackageProperties.ItemProperty) { limitItemPropertyList.Visible = true; PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitItemProperty); PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, match.LimitItemProperty); } else { PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitPackageProperty); PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, match.LimitPackageProperty); } if (limitCustomPropertyList.Items.Count == 0) limitCustomPropertyList.Items.Add(new ListItem("", match.LimitCustomProperty)); if (limitCustomPropertyList.Items.FindByValue(match.LimitCustomProperty) == null) match.LimitCustomProperty = limitCustomPropertyList.Items[0].Value; } } protected void MatchItemPropertyField_SelectedIndexChanged(object sender, EventArgs e) { if (sender != null) { DropDownList itemPropertyField = (DropDownList) sender; ItemProperties itemProperty = (ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue); DropDownList customPropertyField = (DropDownList) itemPropertyField.NamingContainer.FindControl("MatchCustomPropertyField"); HelpLabel customPropertyLabel = (HelpLabel) itemPropertyField.NamingContainer.FindControl("MatchCustomPropertyLabel"); PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty); } } protected void MatchPackagePropertyField_SelectedIndexChanged(object sender, EventArgs e) { if (sender != null) { DropDownList propertyField = (DropDownList) sender; PackageProperties matchProperty = (PackageProperties) Enum.Parse(typeof (PackageProperties), propertyField.SelectedValue); DropDownList itemPropertyField = (DropDownList) propertyField.NamingContainer.FindControl("MatchItemPropertyField"); ItemProperties itemProperty = (ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue); DropDownList customPropertyField = (DropDownList) propertyField.NamingContainer.FindControl("MatchCustomPropertyField"); HelpLabel customPropertyLabel = (HelpLabel) propertyField.NamingContainer.FindControl("MatchCustomPropertyLabel"); if (matchProperty == PackageProperties.ItemProperty) { itemPropertyField.Visible = true; PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty); } else { itemPropertyField.Visible = false; customPropertyField.Visible = false; Page.Validate("RuleGroup"); if (Page.IsValid) { PrepareCustomPropertyField(customPropertyLabel, customPropertyField, matchProperty); } } } } #endregion #region Methods private readonly Regex hiddenAddressProperties = new Regex("bvin|lastupdated", RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly Regex hiddenItemProperties = new Regex("FixedAmountOne", RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly Regex hiddenLimitPackageProperties = new Regex("Invisible", RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly Regex hiddenMatchPackageProperties = new Regex("FixedAmountOne|Invisible", RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly Regex hiddenVendorManufacturerProperties = new Regex("address|bvin|lastupdated|dropshipemailtemplateid", RegexOptions.IgnoreCase | RegexOptions.Compiled); protected override void DataBindChildren() { Matches.RuleId = RuleId; Matches.DataSource = DataSource; base.DataBindChildren(); } private ListItem[] GetAddressProperties() { List<ListItem> properties = new List<ListItem>(); foreach (PropertyInfo property in typeof (Address).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (!hiddenAddressProperties.IsMatch(property.Name)) properties.Add(new ListItem(property.Name, property.Name)); } properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); }); return properties.ToArray(); } private static ListItem[] GetComparisons() { List<ListItem> comparisons = new List<ListItem>(); foreach (RuleComparisons comparison in Enum.GetValues(typeof(RuleComparisons))) { comparisons.Add(new ListItem(RuleComparisonsHelper.GetDisplayName(comparison), comparison.ToString())); } return comparisons.ToArray(); } private ListItem[] GetItemProperties() { List<ListItem> properties = new List<ListItem>(); foreach (ItemProperties property in Enum.GetValues(typeof (ItemProperties))) { if (!hiddenItemProperties.IsMatch(property.ToString())) { properties.Add(new ListItem(ItemPropertiesHelper.GetDisplayName(property), property.ToString())); } } return properties.ToArray(); } public PackageMatchList GetMatches() { return Matches.GetMatches(); } private ListItem[] GetLimitPackageProperties() { List<ListItem> properties = new List<ListItem>(); foreach (PackageProperties property in Enum.GetValues(typeof (PackageProperties))) { if (!hiddenLimitPackageProperties.IsMatch(property.ToString())) { properties.Add(new ListItem(PackagePropertiesHelper.GetDisplayName(property), property.ToString())); } } return properties.ToArray(); } private ListItem[] GetMatchPackageProperties() { List<ListItem> properties = new List<ListItem>(); foreach (PackageProperties property in Enum.GetValues(typeof (PackageProperties))) { if (!hiddenMatchPackageProperties.IsMatch(property.ToString())) { properties.Add(new ListItem(PackagePropertiesHelper.GetDisplayName(property), property.ToString())); } } return properties.ToArray(); } private static ListItem[] GetPropertyTypes() { List<ListItem> propertyTypes = new List<ListItem>(); Collection<ProductProperty> properties = ProductProperty.FindAll(); foreach (ProductProperty property in properties) { propertyTypes.Add(new ListItem(property.DisplayName, property.Bvin)); } if (propertyTypes.Count == 0) { propertyTypes.Add(new ListItem("- n/a -", string.Empty)); } return propertyTypes.ToArray(); } private ListItem[] GetShippingMethods() { List<ListItem> methods = new List<ListItem>(); methods.Add(new ListItem("-n/a-", "")); foreach (ShippingMethod method in ShippingMethod.FindAll()) { if (String.Compare(method.Bvin, ShippingMethod.Bvin, true) != 0) { methods.Add(new ListItem(method.Name, method.Bvin)); } } return methods.ToArray(); } private ListItem[] GetVendorManufacturerProperties() { List<ListItem> properties = new List<ListItem>(); foreach ( PropertyInfo property in typeof (VendorManufacturerBase).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (!hiddenVendorManufacturerProperties.IsMatch(property.Name)) properties.Add(new ListItem(property.Name, property.Name)); } properties.AddRange(GetAddressProperties()); properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); }); return properties.ToArray(); } private void PrepareCustomPropertyField(WebControl label, ListControl list, ItemProperties property) { list.Items.Clear(); if (property == ItemProperties.CustomProperty) { label.ToolTip = "<p>Select the custom property to use.</p>"; list.Items.AddRange(GetPropertyTypes()); list.Visible = true; } else if (property == ItemProperties.Manufacturer || property == ItemProperties.Vendor) { label.ToolTip = string.Format("<p>Select the {0} property to use.</p>", property.ToString().ToLower()); list.Items.AddRange(GetVendorManufacturerProperties()); list.Visible = true; } else { label.ToolTip = ""; list.Items.Add(new ListItem("n/a", "")); list.Visible = false; } } private void PrepareCustomPropertyField(WebControl label, ListControl list, PackageProperties property) { list.Items.Clear(); if (property == PackageProperties.DestinationAddress || property == PackageProperties.SourceAddress) { label.ToolTip = "<p>Select the address property to use.</p>"; list.Items.AddRange(GetAddressProperties()); list.Visible = true; } else if (property == PackageProperties.UseMethod) { label.ToolTip = "<p>Select the shipping method to use.</p>"; list.Items.AddRange(GetShippingMethods()); list.Visible = true; } else { label.ToolTip = ""; list.Items.Add(new ListItem("n/a", "")); list.Visible = false; } } private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, ItemProperties property) { PropertyTypes propertyType = ItemPropertiesHelper.GetPropertyType(property); PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType); } private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, PackageProperties property) { PropertyTypes propertyType = PackagePropertiesHelper.GetPropertyType(property); PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType); } private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, PropertyTypes propertyType) { if (propertyType == PropertyTypes.Numeric) { multiplier.Visible = true; field.Visible = true; label.Text = "Multiplier"; label.ToolTip = "<p>Enter the multiplier.</p>"; requiredValidator.Enabled = true; numericValidator.Enabled = true; } else if (propertyType == PropertyTypes.Fixed) { multiplier.Visible = false; field.Visible = true; label.Text = "Limit"; label.ToolTip = "<p>Enter the limit used in the comparison.</p>"; requiredValidator.Enabled = false; numericValidator.Enabled = false; } else { multiplier.Visible = false; field.Visible = false; requiredValidator.Enabled = false; numericValidator.Enabled = false; } } #endregion }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph.Test.Requests.Generated { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Graph; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class CollectionWithReferencesRequestTests : RequestTestBase { /// <summary> /// Tests building a request for an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void BuildRequest() { var expectedRequestUri = new Uri(string.Format(Constants.Url.GraphBaseUrlFormatString, "v1.0") + "/groups/groupId/members"); var membersCollectionRequestBuilder = this.graphServiceClient.Groups["groupId"].Members as GroupMembersCollectionWithReferencesRequestBuilder; Assert.IsNotNull(membersCollectionRequestBuilder, "Unexpected request builder."); Assert.AreEqual(expectedRequestUri, new Uri(membersCollectionRequestBuilder.RequestUrl), "Unexpected request URL."); var membersCollectionRequest = membersCollectionRequestBuilder.Request() as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(membersCollectionRequest, "Unexpected request."); Assert.AreEqual(expectedRequestUri, new Uri(membersCollectionRequest.RequestUrl), "Unexpected request URL."); } /// <summary> /// Tests the GetAsync() method on the request for an entity collection that has a $ref navigation. /// </summary> [TestMethod] public async System.Threading.Tasks.Task GetAsync() { using (var httpResponseMessage = new HttpResponseMessage()) using (var responseStream = new MemoryStream()) using (var streamContent = new StreamContent(responseStream)) { httpResponseMessage.Content = streamContent; var nextQueryKey = "key"; var nextQueryValue = "value"; var requestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var nextPageRequestUrl = string.Format("{0}?{1}={2}", requestUrl, nextQueryKey, nextQueryValue); this.httpProvider.Setup( provider => provider.SendAsync( It.Is<HttpRequestMessage>( request => request.RequestUri.ToString().StartsWith(requestUrl) && request.Method == HttpMethod.Get), HttpCompletionOption.ResponseContentRead, CancellationToken.None)) .Returns(System.Threading.Tasks.Task.FromResult(httpResponseMessage)); var membersCollectionPage = new GroupMembersCollectionWithReferencesPage { new User(), }; var membersCollectionResponse = new GroupMembersCollectionWithReferencesResponse { Value = membersCollectionPage, AdditionalData = new Dictionary<string, object> { { "@odata.nextLink", nextPageRequestUrl } }, }; this.serializer.Setup( serializer => serializer.DeserializeObject<GroupMembersCollectionWithReferencesResponse>(It.IsAny<string>())) .Returns(membersCollectionResponse); var returnedCollectionPage = await this.graphServiceClient.Groups["groupId"].Members.Request().GetAsync() as GroupMembersCollectionWithReferencesPage; Assert.IsNotNull(returnedCollectionPage, "Collection page not returned."); Assert.AreEqual(membersCollectionPage, returnedCollectionPage, "Unexpected collection page returned."); Assert.AreEqual( membersCollectionResponse.AdditionalData, returnedCollectionPage.AdditionalData, "Additional data not initialized on collection page."); var nextPageRequest = returnedCollectionPage.NextPageRequest as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(nextPageRequest, "Next page request not returned."); Assert.AreEqual(new Uri(requestUrl), new Uri(nextPageRequest.RequestUrl), "Unexpected URL initialized for next page request."); Assert.AreEqual(1, nextPageRequest.QueryOptions.Count, "Unexpected query options initialized."); Assert.AreEqual(nextQueryKey, nextPageRequest.QueryOptions[0].Name, "Unexpected query option name initialized."); Assert.AreEqual(nextQueryValue, nextPageRequest.QueryOptions[0].Value, "Unexpected query option value initialized."); } } #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows expand. /// <summary> /// Tests the Expand() method on the request for an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Expand() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Expand("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$expand", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows select. /// <summary> /// Tests the Select() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Select() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Select("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$select", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif /// <summary> /// Tests the Top() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Top() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Top(1) as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$top", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("1", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows filter. /// <summary> /// Tests the Filter() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Filter() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Filter("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$filter", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows skip. /// <summary> /// Tests the Skip() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Skip() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Skip(1) as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$skip", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("1", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif /// <summary> /// Tests the OrderBy() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void OrderBy() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().OrderBy("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$orderby", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnNomencladorDetalle class. /// </summary> [Serializable] public partial class PnNomencladorDetalleCollection : ActiveList<PnNomencladorDetalle, PnNomencladorDetalleCollection> { public PnNomencladorDetalleCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnNomencladorDetalleCollection</returns> public PnNomencladorDetalleCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnNomencladorDetalle o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_nomenclador_detalle table. /// </summary> [Serializable] public partial class PnNomencladorDetalle : ActiveRecord<PnNomencladorDetalle>, IActiveRecord { #region .ctors and Default Settings public PnNomencladorDetalle() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnNomencladorDetalle(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnNomencladorDetalle(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnNomencladorDetalle(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_nomenclador_detalle", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdNomencladorDetalle = new TableSchema.TableColumn(schema); colvarIdNomencladorDetalle.ColumnName = "id_nomenclador_detalle"; colvarIdNomencladorDetalle.DataType = DbType.Int32; colvarIdNomencladorDetalle.MaxLength = 0; colvarIdNomencladorDetalle.AutoIncrement = true; colvarIdNomencladorDetalle.IsNullable = false; colvarIdNomencladorDetalle.IsPrimaryKey = true; colvarIdNomencladorDetalle.IsForeignKey = false; colvarIdNomencladorDetalle.IsReadOnly = false; colvarIdNomencladorDetalle.DefaultSetting = @""; colvarIdNomencladorDetalle.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNomencladorDetalle); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = -1; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = true; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarFechaDesde = new TableSchema.TableColumn(schema); colvarFechaDesde.ColumnName = "fecha_desde"; colvarFechaDesde.DataType = DbType.DateTime; colvarFechaDesde.MaxLength = 0; colvarFechaDesde.AutoIncrement = false; colvarFechaDesde.IsNullable = true; colvarFechaDesde.IsPrimaryKey = false; colvarFechaDesde.IsForeignKey = false; colvarFechaDesde.IsReadOnly = false; colvarFechaDesde.DefaultSetting = @""; colvarFechaDesde.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaDesde); TableSchema.TableColumn colvarFechaHasta = new TableSchema.TableColumn(schema); colvarFechaHasta.ColumnName = "fecha_hasta"; colvarFechaHasta.DataType = DbType.DateTime; colvarFechaHasta.MaxLength = 0; colvarFechaHasta.AutoIncrement = false; colvarFechaHasta.IsNullable = true; colvarFechaHasta.IsPrimaryKey = false; colvarFechaHasta.IsForeignKey = false; colvarFechaHasta.IsReadOnly = false; colvarFechaHasta.DefaultSetting = @""; colvarFechaHasta.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaHasta); TableSchema.TableColumn colvarModoFacturacion = new TableSchema.TableColumn(schema); colvarModoFacturacion.ColumnName = "modo_facturacion"; colvarModoFacturacion.DataType = DbType.Int32; colvarModoFacturacion.MaxLength = 0; colvarModoFacturacion.AutoIncrement = false; colvarModoFacturacion.IsNullable = false; colvarModoFacturacion.IsPrimaryKey = false; colvarModoFacturacion.IsForeignKey = false; colvarModoFacturacion.IsReadOnly = false; colvarModoFacturacion.DefaultSetting = @"((0))"; colvarModoFacturacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarModoFacturacion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_nomenclador_detalle",schema); } } #endregion #region Props [XmlAttribute("IdNomencladorDetalle")] [Bindable(true)] public int IdNomencladorDetalle { get { return GetColumnValue<int>(Columns.IdNomencladorDetalle); } set { SetColumnValue(Columns.IdNomencladorDetalle, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("FechaDesde")] [Bindable(true)] public DateTime? FechaDesde { get { return GetColumnValue<DateTime?>(Columns.FechaDesde); } set { SetColumnValue(Columns.FechaDesde, value); } } [XmlAttribute("FechaHasta")] [Bindable(true)] public DateTime? FechaHasta { get { return GetColumnValue<DateTime?>(Columns.FechaHasta); } set { SetColumnValue(Columns.FechaHasta, value); } } [XmlAttribute("ModoFacturacion")] [Bindable(true)] public int ModoFacturacion { get { return GetColumnValue<int>(Columns.ModoFacturacion); } set { SetColumnValue(Columns.ModoFacturacion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.PnNomencladorCollection colPnNomencladorRecords; public DalSic.PnNomencladorCollection PnNomencladorRecords { get { if(colPnNomencladorRecords == null) { colPnNomencladorRecords = new DalSic.PnNomencladorCollection().Where(PnNomenclador.Columns.IdNomencladorDetalle, IdNomencladorDetalle).Load(); colPnNomencladorRecords.ListChanged += new ListChangedEventHandler(colPnNomencladorRecords_ListChanged); } return colPnNomencladorRecords; } set { colPnNomencladorRecords = value; colPnNomencladorRecords.ListChanged += new ListChangedEventHandler(colPnNomencladorRecords_ListChanged); } } void colPnNomencladorRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnNomencladorRecords[e.NewIndex].IdNomencladorDetalle = IdNomencladorDetalle; } } private DalSic.PnTipoDePrestacionCollection colPnTipoDePrestacionRecords; public DalSic.PnTipoDePrestacionCollection PnTipoDePrestacionRecords { get { if(colPnTipoDePrestacionRecords == null) { colPnTipoDePrestacionRecords = new DalSic.PnTipoDePrestacionCollection().Where(PnTipoDePrestacion.Columns.IdNomencladorDetalle, IdNomencladorDetalle).Load(); colPnTipoDePrestacionRecords.ListChanged += new ListChangedEventHandler(colPnTipoDePrestacionRecords_ListChanged); } return colPnTipoDePrestacionRecords; } set { colPnTipoDePrestacionRecords = value; colPnTipoDePrestacionRecords.ListChanged += new ListChangedEventHandler(colPnTipoDePrestacionRecords_ListChanged); } } void colPnTipoDePrestacionRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnTipoDePrestacionRecords[e.NewIndex].IdNomencladorDetalle = IdNomencladorDetalle; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcion,DateTime? varFechaDesde,DateTime? varFechaHasta,int varModoFacturacion) { PnNomencladorDetalle item = new PnNomencladorDetalle(); item.Descripcion = varDescripcion; item.FechaDesde = varFechaDesde; item.FechaHasta = varFechaHasta; item.ModoFacturacion = varModoFacturacion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdNomencladorDetalle,string varDescripcion,DateTime? varFechaDesde,DateTime? varFechaHasta,int varModoFacturacion) { PnNomencladorDetalle item = new PnNomencladorDetalle(); item.IdNomencladorDetalle = varIdNomencladorDetalle; item.Descripcion = varDescripcion; item.FechaDesde = varFechaDesde; item.FechaHasta = varFechaHasta; item.ModoFacturacion = varModoFacturacion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdNomencladorDetalleColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn FechaDesdeColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn FechaHastaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn ModoFacturacionColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdNomencladorDetalle = @"id_nomenclador_detalle"; public static string Descripcion = @"descripcion"; public static string FechaDesde = @"fecha_desde"; public static string FechaHasta = @"fecha_hasta"; public static string ModoFacturacion = @"modo_facturacion"; } #endregion #region Update PK Collections public void SetPKValues() { if (colPnNomencladorRecords != null) { foreach (DalSic.PnNomenclador item in colPnNomencladorRecords) { if (item.IdNomencladorDetalle != IdNomencladorDetalle) { item.IdNomencladorDetalle = IdNomencladorDetalle; } } } if (colPnTipoDePrestacionRecords != null) { foreach (DalSic.PnTipoDePrestacion item in colPnTipoDePrestacionRecords) { if (item.IdNomencladorDetalle != IdNomencladorDetalle) { item.IdNomencladorDetalle = IdNomencladorDetalle; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colPnNomencladorRecords != null) { colPnNomencladorRecords.SaveAll(); } if (colPnTipoDePrestacionRecords != null) { colPnTipoDePrestacionRecords.SaveAll(); } } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.ComponentModel; using System.Threading; using System.Web; using System.Windows.Forms; using mshtml; using OpenLiveWriter.CoreServices.Progress; namespace OpenLiveWriter.CoreServices { /// <summary> /// Gets HTMLDocuments for a given URL. It gets two versions of the Document, /// one that can be used to get a list of references in the Document and one that /// can used to extract the literal HTML that should be used when saving or dealing /// with the HTML directly. /// </summary> public class HTMLDocumentDownloader : IDisposable { /// <summary> /// Constructs a new HTMLDocument downloader /// </summary> /// <param name="parentControl">The control that parents the downloader (must be on a STA thread)</param> public HTMLDocumentDownloader(Control parentControl) { if (parentControl != null) _parentControl = parentControl; } public HTMLDocumentDownloader(Control parentControl, string url, string title, string cookieString, int timeOutMs, bool permitScriptExecution) : this(parentControl, url, title, cookieString, timeOutMs, permitScriptExecution, null) { } /// <summary> /// Creates a new HTMLDocumentDownloader /// </summary> /// <param name="synchronizeInvoke">The control that parents the downloader (must be on a STA thread)</param> /// <param name="url">The url to download</param> public HTMLDocumentDownloader(Control parentControl, string url, string title, string cookieString, int timeOutMs, bool permitScriptExecution, byte[] postData) : this(parentControl) { _timeoutMs = timeOutMs; _cookieString = cookieString; _title = title; _permitScriptExecution = permitScriptExecution; _postData = postData; _url = url; } public bool PermitScriptExecution { get { return _permitScriptExecution; } set { _permitScriptExecution = value; } } private bool _permitScriptExecution = true; private readonly byte[] _postData; private string CleanUrl(string url) { if (url == null) return url; url = UrlHelper.GetUrlWithoutAnchorIdentifier(url); if (UrlHelper.IsFileUrl(url)) url = HttpUtility.UrlDecode(url); return url; } /// <summary> /// The url to download /// </summary> public string Url { get { return _url; } set { _url = value; } } public string Title { get { if (_title == null) return _url; else return _title; } set { _title = value; } } private string _title = null; public int TimeoutMs { get { return _timeoutMs; } set { _timeoutMs = value; } } private int _timeoutMs = 120000; public IHTMLDocument2 HtmlDocument { get { return _htmlDocument; } } private IHTMLDocument2 _htmlDocument = null; private delegate void Download(IProgressHost progressHost); /// <summary> /// Initiate a download, using the progressHost to provide progress feedback /// </summary> /// <param name="progressHost">The progressHost to provide feedback to</param> /// <returns>this</returns> public object DownloadHTMLDocument(IProgressHost progressHost) { _downloadComplete = false; // Call the download method on the parent STA thread // Then wait for it to complete (the Monitor will be pulsed upon completion) _parentControl.Invoke(new Download(DoDownload), new object[] { progressHost }); lock (this) { if (_downloadComplete) return this; DateTime endDateTime = DateTime.Now.AddMilliseconds(TimeoutMs); while (!_downloadComplete) { if (!Monitor.Wait(this, Math.Max(0, (int)endDateTime.Subtract(DateTime.Now).TotalMilliseconds))) throw new OperationTimedOutException(); } if (_downloader.Result.Exception != null) throw _downloader.Result.Exception; progressHost.UpdateProgress(1, 1); return this; } } private bool _downloadComplete = false; private void CleanupDownloader() { if (_downloader != null) { _downloader.DownloadComplete -= new EventHandler(downloader_DownloadComplete); _parentControl.BeginInvoke(new ThreadStart(_downloader.Dispose)); _downloader = null; } } /// <summary> /// Initiate the download providing no progress /// </summary> public void DownloadHTMLDocument() { DownloadHTMLDocument(SilentProgressHost.Instance); } /// <summary> /// Indicates whether the selected URL is downloadable by this control /// (for example, a javascript URL isn't really downloadable by this control) /// </summary> /// <param name="url">The url to download</param> /// <returns>true if the url is downloadable, otherwise false</returns> public static bool IsDownloadableUrl(string url) { try { Uri uri = new Uri(url); foreach (string scheme in DownloadableSchemes) if (uri.Scheme == scheme) return true; } catch (Exception) { //may occur if the URL is malformed } return false; } /// <summary> /// The list of well known schemes /// </summary> private static string[] DownloadableSchemes = new string[] { Uri.UriSchemeFile, Uri.UriSchemeHttp, Uri.UriSchemeHttps }; /// <summary> /// Downloads the Document for a particular URL /// </summary> private void DoDownload(IProgressHost progressHost) { if (_downloader == null) _downloader = new WebPageDownloader(_parentControl); // Configure the downloader, hook its complete event and start the download _downloader.Title = _title; _downloader.Url = CleanUrl(_url); _downloader.ExecuteScripts = _permitScriptExecution; _downloader.CookieString = CookieString; _downloader.PostData = _postData; _downloader.DownloadComplete += new EventHandler(downloader_DownloadComplete); _downloader.DownloadFromUrl(progressHost); } /// <summary> /// Handles the download complete event from the downloader /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void downloader_DownloadComplete(object sender, EventArgs e) { // If we're downloading the first DOM, save the HTMLSourceDom and start the Reference DOM download if (_downloader.Result == WebPageDownloader.WebPageDownloaderResult.Ok) { _url = _downloader.HTMLDocument.url; this._htmlDocument = _downloader.HTMLDocument; } MarkDownloadComplete(); } private void MarkDownloadComplete() { lock (this) { _downloadComplete = true; Monitor.PulseAll(this); } } #region IDisposable Members /// <summary> /// Disposes of this object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~HTMLDocumentDownloader() { Dispose(false); } /// <summary> /// Disposes this object /// </summary> /// <param name="disposing">Indicates whether this was called from dispose</param> private void Dispose(bool disposing) { if (!disposing) Debug.Fail("You must dispose of HTMLDocumentDownloader"); CleanupDownloader(); } #endregion private WebPageDownloader _downloader; private Control _parentControl = null; private string _url; public string CookieString { get { return _cookieString; } set { _cookieString = value; } } private string _cookieString = null; } public class OperationTimedOutException : Exception { } }
// Copyright 2012 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Linq; using NodaTime.Testing.TimeZones; using NodaTime.TimeZones; using NUnit.Framework; namespace NodaTime.Test.TimeZones { /// <summary> /// Tests for DateTimeZoneCache. /// </summary> [TestFixture] public class DateTimeZoneCacheTest { [Test] public void Construction_NullProvider() { Assert.Throws<ArgumentNullException>(() => new DateTimeZoneCache(null)); } [Test] public void InvalidProvider_NullVersionId() { var source = new TestDateTimeZoneSource("Test1", "Test2") { VersionId = null }; Assert.Throws<InvalidDateTimeZoneSourceException>(() => new DateTimeZoneCache(source)); } [Test] public void InvalidProvider_NullIdSequence() { string[] ids = null; var source = new TestDateTimeZoneSource(ids); Assert.Throws<InvalidDateTimeZoneSourceException>(() => new DateTimeZoneCache(source)); } [Test] public void InvalidProvider_NullIdWithinSequence() { var source = new TestDateTimeZoneSource("Test1", null); Assert.Throws<InvalidDateTimeZoneSourceException>(() => new DateTimeZoneCache(source)); } [Test] public void CachingForPresentValues() { var source = new TestDateTimeZoneSource("Test1", "Test2"); var provider = new DateTimeZoneCache(source); var zone1a = provider["Test1"]; Assert.IsNotNull(zone1a); Assert.AreEqual("Test1", source.LastRequestedId); // Hit up the cache (and thus the source) for Test2 Assert.IsNotNull(provider["Test2"]); Assert.AreEqual("Test2", source.LastRequestedId); // Ask for Test1 again var zone1b = provider["Test1"]; // We won't have consulted the source again Assert.AreEqual("Test2", source.LastRequestedId); Assert.AreSame(zone1a, zone1b); } [Test] public void SourceIsNotAskedForUtcIfNotAdvertised() { var source = new TestDateTimeZoneSource("Test1", "Test2"); var provider = new DateTimeZoneCache(source); var zone = provider[DateTimeZone.UtcId]; Assert.IsNotNull(zone); Assert.IsNull(source.LastRequestedId); } [Test] public void SourceIsNotAskedForUtcIfAdvertised() { var source = new TestDateTimeZoneSource("Test1", "Test2", "UTC"); var provider = new DateTimeZoneCache(source); var zone = provider[DateTimeZone.UtcId]; Assert.IsNotNull(zone); Assert.IsNull(source.LastRequestedId); } [Test] public void SourceIsNotAskedForUnknownIds() { var source = new TestDateTimeZoneSource("Test1", "Test2"); var provider = new DateTimeZoneCache(source); Assert.Throws<DateTimeZoneNotFoundException>(() => { var ignored = provider["Unknown"]; }); Assert.IsNull(source.LastRequestedId); } [Test] public void UtcIsReturnedInIdsIfAdvertisedByProvider() { var source = new TestDateTimeZoneSource("Test1", "Test2", "UTC"); var provider = new DateTimeZoneCache(source); Assert.True(provider.Ids.Contains(DateTimeZone.UtcId)); } [Test] public void UtcIsNotReturnedInIdsIfNotAdvertisedByProvider() { var source = new TestDateTimeZoneSource("Test1", "Test2"); var provider = new DateTimeZoneCache(source); Assert.False(provider.Ids.Contains(DateTimeZone.UtcId)); } [Test] public void FixedOffsetSucceedsWhenNotAdvertised() { var source = new TestDateTimeZoneSource("Test1", "Test2"); var provider = new DateTimeZoneCache(source); string id = "UTC+05:30"; DateTimeZone zone = provider[id]; Assert.AreEqual(DateTimeZone.ForOffset(Offset.FromHoursAndMinutes(5, 30)), zone); Assert.AreEqual(id, zone.Id); Assert.IsNull(source.LastRequestedId); } [Test] public void FixedOffsetSucceedsWithoutConsultingSourceWhenAdvertised() { string id = "UTC+05:30"; var source = new TestDateTimeZoneSource("Test1", "Test2", id); var provider = new DateTimeZoneCache(source); DateTimeZone zone = provider[id]; Assert.AreEqual(DateTimeZone.ForOffset(Offset.FromHoursAndMinutes(5, 30)), zone); Assert.AreEqual(id, zone.Id); Assert.IsNull(source.LastRequestedId); } [Test] public void FixedOffsetUncached() { string id = "UTC+05:26"; var source = new TestDateTimeZoneSource("Test1", "Test2"); var provider = new DateTimeZoneCache(source); DateTimeZone zone1 = provider[id]; DateTimeZone zone2 = provider[id]; Assert.AreNotSame(zone1, zone2); Assert.AreEqual(zone1, zone2); } [Test] public void FixedOffsetZeroReturnsUtc() { string id = "UTC+00:00"; var source = new TestDateTimeZoneSource("Test1", "Test2", id); var provider = new DateTimeZoneCache(source); DateTimeZone zone = provider[id]; Assert.AreEqual(DateTimeZone.Utc, zone); Assert.IsNull(source.LastRequestedId); } [Test] public void Tzdb_Indexer_InvalidFixedOffset() { Assert.Throws<DateTimeZoneNotFoundException>(() => { var ignored = DateTimeZoneProviders.Tzdb["UTC+5Months"]; }); } [Test] public void NullIdRejected() { var provider = new DateTimeZoneCache(new TestDateTimeZoneSource("Test1", "Test2")); // GetType call just to avoid trying to use a property as a statement... Assert.Throws<ArgumentNullException>(() => provider[null].GetType()); } [Test] public void EmptyIdAccepted() { var provider = new DateTimeZoneCache(new TestDateTimeZoneSource("Test1", "Test2")); Assert.Throws<DateTimeZoneNotFoundException>(() => { var ignored = provider[""]; }); } [Test] public void VersionIdPassThrough() { var provider = new DateTimeZoneCache(new TestDateTimeZoneSource("Test1", "Test2") { VersionId = "foo" }); Assert.AreEqual("foo", provider.VersionId); } [Test(Description = "Test for issue 7 in bug tracker")] public void Tzdb_IterateOverIds() { // According to bug, this would go bang int count = DateTimeZoneProviders.Tzdb.Ids.Count(); Assert.IsTrue(count > 1); int utcCount = DateTimeZoneProviders.Tzdb.Ids.Count(id => id == DateTimeZone.UtcId); Assert.AreEqual(1, utcCount); } [Test] public void Tzdb_Indexer_UtcId() { Assert.AreEqual(DateTimeZone.Utc, DateTimeZoneProviders.Tzdb[DateTimeZone.UtcId]); } [Test] public void Tzdb_Indexer_AmericaLosAngeles() { const string americaLosAngeles = "America/Los_Angeles"; var actual = DateTimeZoneProviders.Tzdb[americaLosAngeles]; Assert.IsNotNull(actual); Assert.AreNotEqual(DateTimeZone.Utc, actual); Assert.AreEqual(americaLosAngeles, actual.Id); } [Test] public void Tzdb_Ids_All() { var actual = DateTimeZoneProviders.Tzdb.Ids; var actualCount = actual.Count(); Assert.IsTrue(actualCount > 1); var utc = actual.Single(id => id == DateTimeZone.UtcId); Assert.AreEqual(DateTimeZone.UtcId, utc); } /// <summary> /// Simply tests that every ID in the built-in database can be fetched. This is also /// helpful for diagnostic debugging when we want to check that some potential /// invariant holds for all time zones... /// </summary> [Test] public void Tzdb_Indexer_AllIds() { foreach (string id in DateTimeZoneProviders.Tzdb.Ids) { Assert.IsNotNull(DateTimeZoneProviders.Tzdb[id]); } } private class TestDateTimeZoneSource : IDateTimeZoneSource { public string LastRequestedId { get; set; } private readonly string[] ids; public TestDateTimeZoneSource(params string[] ids) { this.ids = ids; this.VersionId = "test version"; } public IEnumerable<string> GetIds() { return ids; } public DateTimeZone ForId(string id) { LastRequestedId = id; return new SingleTransitionDateTimeZone(NodaConstants.UnixEpoch, 0, id.GetHashCode() % 18); } public string VersionId { get; set; } public string MapTimeZoneId(TimeZoneInfo timeZone) { return "map"; } } } }
using System; using UnityEngine; using System.Collections; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; using UnityStandardAssets.Characters.FirstPerson; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. public float flySpeed; private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { if (CrossPlatformInputManager.GetButton ("Jump")) { GetComponent<Rigidbody>().AddForce(Vector3.up * flySpeed, ForceMode.Acceleration); if (Input.GetKey(KeyCode.LeftShift)) { GetComponent<Rigidbody>().AddForce(Vector3.up * flySpeed * 2, ForceMode.Acceleration); } } if (Input.GetKey(KeyCode.LeftControl)) { GetComponent<Rigidbody>().AddForce(Vector3.down * flySpeed, ForceMode.Acceleration); if (Input.GetKey(KeyCode.LeftShift)) { GetComponent<Rigidbody>().AddForce(Vector3.down * flySpeed * 2, ForceMode.Acceleration); } } RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { if (!Input.GetKey (KeyCode.Q)) { m_MouseLook.LookRotation (transform, m_Camera.transform); } else { Cursor.lockState = CursorLockMode.None; } } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// // TranslateLanguageWindow.cs // // The MIT License (MIT) // // Copyright (c) 2013 Niklas Borglund // // 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 UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Globalization; using System; public class TranslateLanguageWindow : EditorWindow { #region Members [SerializeField] private Dictionary<string,LocalizedObject> rootValues; [SerializeField] private List<SerializableLocalizationObjectPair> thisLanguageValues = new List<SerializableLocalizationObjectPair>(); [SerializeField] private string thisLanguage; [SerializeField] private CultureInfo thisCultureInfo; /// <summary> A bool that is set if the root file have been changed </summary> [SerializeField] private bool rootFileChanged = false; /// <summary> The scroll view position </summary> [SerializeField] private Vector2 scrollPosition = Vector2.zero; /// <summary> Did the GUI change? </summary> [SerializeField] private bool guiChanged = false; [SerializeField] ///<summary> is the language available for translation?</summary> private bool canLanguageBeTranslated = false; ///<summary> Languages available to translate from</summary> private List<CultureInfo> availableTranslateFromLanguages = new List<CultureInfo>(); ///<summary> For the translateFromLanguage from popup</summary> private string[] availableTranslateLangEnglishNames; ///<summary> Popup index for translateFromLanguage</summary> private int translateFromLanguageValue = 0; private int oldTranslateFromLanguageValue = 0; private string translateFromLanguage = "None"; ///<summary> The language dictionary to translate from</summary> private Dictionary<string,LocalizedObject> translateFromDictionary; private string searchText = ""; private HOEditorUndoManager undoManager; private SmartLocalizationWindow smartLocWindow; #endregion #region Initialization public void Initialize(CultureInfo thisCultureInfo, bool checkTranslation = false) { if(smartLocWindow != null && !Application.isPlaying && thisCultureInfo != null) { if(undoManager == null) { // Instantiate Undo Manager undoManager = new HOEditorUndoManager(this, "Smart Localization - Translate Language Window"); } if(thisCultureInfo != null) { bool newLanguage = thisCultureInfo != this.thisCultureInfo ? true : false; this.thisCultureInfo = thisCultureInfo; if(thisLanguageValues == null || thisLanguageValues.Count < 1 || newLanguage) { InitializeLanguage(thisCultureInfo, LocFileUtility.LoadParsedLanguageFile(null), LocFileUtility.LoadParsedLanguageFile(thisCultureInfo.Name)); } } if(checkTranslation) { //Check if the language can be translated canLanguageBeTranslated = false; CheckIfCanBeTranslated(); if(translateFromDictionary != null) { translateFromDictionary.Clear(); translateFromDictionary = null; } } } } /// <summary> /// Initializes the Language /// </summary> void InitializeLanguage(CultureInfo info, Dictionary<string, LocalizedObject> rootValues, Dictionary<string, LocalizedObject> thisLanguageValues) { this.rootValues = rootValues; this.thisLanguageValues.Clear(); this.thisLanguageValues = LocFileUtility.CreateSerializableLocalizationList(thisLanguageValues); //Load assets LocFileUtility.LoadAllAssets(this.thisLanguageValues); this.thisLanguage = (thisCultureInfo.EnglishName + " - " + thisCultureInfo.Name); rootFileChanged = false; } #endregion #region EditorWindow Overrides void OnEnable() { EditRootLanguageFileWindow.OnRootFileChanged += OnRootFileChanged; Initialize(thisCultureInfo); } void OnDisable() { EditRootLanguageFileWindow.OnRootFileChanged -= OnRootFileChanged; } void OnProjectChange() { Initialize(thisCultureInfo); } void OnFocus() { Initialize(thisCultureInfo, true); } void OnGUI() { if(EditorWindowUtility.ShowWindow()) { if(smartLocWindow == null || thisCultureInfo == null) { this.Close();// Temp fix } else if(!rootFileChanged) { undoManager.CheckUndo(); GUILayout.Label("Language - " + thisLanguage, EditorStyles.boldLabel, GUILayout.Width(200)); //Copy all the Base Values GUILayout.Label("If you want to copy all the base values from the root file", EditorStyles.miniLabel); if(GUILayout.Button("Copy All Base Values", GUILayout.Width(150))) { int count = 0; foreach(KeyValuePair<string,LocalizedObject> rootValue in rootValues) { if(rootValue.Value.ObjectType == LocalizedObjectType.STRING) { thisLanguageValues[count].changedValue.TextValue = rootValue.Value.TextValue; } count++; } } GUILayout.Label("Microsoft Translator", EditorStyles.boldLabel); if(!smartLocWindow.MicrosoftTranslator.IsInitialized) { GUILayout.Label("Microsoft Translator is not authenticated", EditorStyles.miniLabel); } else { if(canLanguageBeTranslated) { EditorGUILayout.BeginHorizontal(); GUILayout.Label("Translate From:", GUILayout.Width(100)); translateFromLanguageValue = EditorGUILayout.Popup(translateFromLanguageValue, availableTranslateLangEnglishNames); EditorGUILayout.EndHorizontal(); if(oldTranslateFromLanguageValue != translateFromLanguageValue) { oldTranslateFromLanguageValue = translateFromLanguageValue; //The value have been changed, load the language file of the other language that you want to translate from //I load it like this to show the translate buttons only on the ones that can be translated i.e some values //in the "from" language could be an empty string - no use in translating that if(translateFromDictionary != null) { translateFromDictionary.Clear(); translateFromDictionary = null; } if(translateFromLanguageValue != 0) { string englishName = availableTranslateLangEnglishNames[translateFromLanguageValue]; foreach(CultureInfo info in availableTranslateFromLanguages) { if(info.EnglishName == englishName) { translateFromDictionary = LocFileUtility.LoadParsedLanguageFile(info.Name); translateFromLanguage = info.Name; break; } } } } //Translate all the available keys if(translateFromLanguageValue != 0 && GUILayout.Button("Translate all text", GUILayout.Width(150))) { List<string> keys = new List<string>(); List<string> textsToTranslate = new List<string>(); int characterCount = 0; foreach(KeyValuePair<string,LocalizedObject> stringPair in translateFromDictionary) { if(stringPair.Value.ObjectType == LocalizedObjectType.STRING && stringPair.Value.TextValue != null && stringPair.Value.TextValue != "") { int textLength = stringPair.Value.TextValue.Length; //Microsoft translator only support translations below 1000 character //I'll cap it to 700, which gives 300 extra if the translated value is longer if(textLength < 700) { characterCount += textLength; keys.Add(stringPair.Key); textsToTranslate.Add(stringPair.Value.TextValue); } } //Microsoft translator only support translations with 100 array values and a total // character cap of 10000, // I'll cap it to 7000, which gives 3000 extra if the translated value is longer if(keys.Count >= 99 || characterCount >= 7000) { //Create a new reference to the list with keys, because we need it non-cleared in the callback List<string> keysToSend = new List<string>(); keysToSend.AddRange(keysToSend.ToArray()); //Send the values smartLocWindow.MicrosoftTranslator.TranslateArray(textsToTranslate, translateFromLanguage, thisCultureInfo.Name, keysToSend, new TranslateCompleteArrayCallback(TranslatedTextArrayCompleted)); //Reset values characterCount = 0; keys.Clear(); textsToTranslate.Clear(); } } if(keys.Count != 0) { smartLocWindow.MicrosoftTranslator.TranslateArray(textsToTranslate, translateFromLanguage, thisCultureInfo.Name, keys, new TranslateCompleteArrayCallback(TranslatedTextArrayCompleted)); //Reset values characterCount = 0; keys.Clear(); textsToTranslate.Clear(); } } } else { GUILayout.Label(thisCultureInfo.EnglishName + " is not available for translation", EditorStyles.miniLabel); } } GUILayout.Label("Language Values", EditorStyles.boldLabel); //Search field EditorGUILayout.BeginHorizontal(); GUILayout.Label("Search for Key:", GUILayout.Width(100)); searchText = EditorGUILayout.TextField(searchText); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Key", EditorStyles.boldLabel, GUILayout.Width(120)); GUILayout.Label("Base Value", EditorStyles.boldLabel, GUILayout.Width(120)); GUILayout.Label("Copy Base", EditorStyles.miniLabel, GUILayout.Width(70)); if(canLanguageBeTranslated) { //TODO::Change to small picture GUILayout.Label("T", EditorStyles.miniLabel, GUILayout.Width(20)); } GUILayout.Label(thisLanguage + " Value", EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); //Check if the user searched for a value bool didSearch = false; if(searchText != "") { didSearch = true; GUILayout.Label("Search Results - \"" + searchText + "\":", EditorStyles.boldLabel); } //Start the scroll view scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); int iterationCount = 0; foreach(KeyValuePair<string,LocalizedObject> rootValue in rootValues) { if(didSearch) { //If the name of the key doesn't contain the search value, then skip a value if(!rootValue.Key.ToLower().Contains(searchText.ToLower())) { continue; } } if(rootValue.Value.ObjectType == LocalizedObjectType.STRING) { OnTextFieldGUI(rootValue, iterationCount); } else if(rootValue.Value.ObjectType == LocalizedObjectType.AUDIO) { OnAudioGUI(rootValue, iterationCount); } else if(rootValue.Value.ObjectType == LocalizedObjectType.GAME_OBJECT) { OnGameObjectGUI(rootValue, iterationCount); } else if(rootValue.Value.ObjectType == LocalizedObjectType.TEXTURE) { OnTextureGUI(rootValue, iterationCount); } iterationCount++; } //End the scroll view EditorGUILayout.EndScrollView(); if(guiChanged) { GUILayout.Label("- You have unsaved changes", EditorStyles.miniLabel); } //If any changes to the gui is made if(GUI.changed) { guiChanged = true; } GUILayout.Label("Save Changes", EditorStyles.boldLabel); GUILayout.Label("Remember to always press save when you have changed values", EditorStyles.miniLabel); if(GUILayout.Button("Save/Rebuild")) { //Copy everything into a dictionary Dictionary<string,string> newLanguageValues = new Dictionary<string, string>(); foreach(SerializableLocalizationObjectPair objectPair in this.thisLanguageValues) { if(objectPair.changedValue.ObjectType == LocalizedObjectType.STRING) { newLanguageValues.Add(objectPair.changedValue.GetFullKey(objectPair.keyValue), objectPair.changedValue.TextValue); } else { //Delete the file in case there was a file there previously LocFileUtility.DeleteFileFromResources(objectPair.changedValue.GetFullKey(objectPair.keyValue), thisCultureInfo); //Store the path to the file string pathValue = LocFileUtility.CopyFileIntoResources(objectPair, thisCultureInfo); newLanguageValues.Add(objectPair.changedValue.GetFullKey(objectPair.keyValue), pathValue); } } LocFileUtility.SaveLanguageFile(newLanguageValues, LocFileUtility.rootLanguageFilePath + "." + thisCultureInfo.Name + LocFileUtility.resXFileEnding); guiChanged = false; } undoManager.CheckDirty(); } else { //The root file did change, which means that you have to reload. A key might have changed //We can't have language files with different keys GUILayout.Label("The root file might have changed", EditorStyles.boldLabel); GUILayout.Label("The root file did save, which means that you have to reload. A key might have changed.", EditorStyles.miniLabel); GUILayout.Label("You can't have language files with different keys", EditorStyles.miniLabel); if(GUILayout.Button("Reload Language File")) { InitializeLanguage(thisCultureInfo, LocFileUtility.LoadParsedLanguageFile(null), LocFileUtility.LoadParsedLanguageFile(thisCultureInfo.Name)); } } } } #endregion #region Translation Check /// <summary> /// Checks if this language can be translated by Microsoft Translator /// </summary> private void CheckIfCanBeTranslated() { availableTranslateFromLanguages.Clear(); //Clear the array if(availableTranslateLangEnglishNames != null) { Array.Clear(availableTranslateLangEnglishNames, 0, availableTranslateLangEnglishNames.Length); availableTranslateLangEnglishNames = null; } if(translateFromDictionary != null) { translateFromDictionary.Clear(); translateFromDictionary = null; } translateFromLanguageValue = 0; oldTranslateFromLanguageValue = 0; //Create a list that will store the english names List<string> englishNames = new List<string>(); englishNames.Add("None"); if(smartLocWindow.MicrosoftTranslator.IsInitialized) { if(smartLocWindow.MicrosoftTranslator.LanguagesAvailableForTranslation.Contains(thisCultureInfo.Name)) { canLanguageBeTranslated = true; foreach(CultureInfo cultureInfo in smartLocWindow.AvailableLanguages) { if(cultureInfo != thisCultureInfo && smartLocWindow.MicrosoftTranslator.LanguagesAvailableForTranslation.Contains(cultureInfo.Name)) { availableTranslateFromLanguages.Add(cultureInfo); englishNames.Add(cultureInfo.EnglishName); } } } else { canLanguageBeTranslated = false; } } availableTranslateLangEnglishNames = englishNames.ToArray(); } #endregion #region GUI Functions /// <summary> /// Shows the GUI for a key with the type of STRING /// </summary> /// <param name='rootValue'> /// Root value. /// </param> private void OnTextFieldGUI(KeyValuePair<string,LocalizedObject> rootValue, int iterationCount) { EditorGUILayout.BeginHorizontal(); GUILayout.Label(rootValue.Key, GUILayout.Width(120)); GUILayout.Label(rootValue.Value.TextValue,GUILayout.Width(120)); //If the user wants to copy the base value of this key if(GUILayout.Button("Copy Base", GUILayout.Width(70))) { thisLanguageValues[iterationCount].changedValue = rootValue.Value; } //If the language can be translated if(canLanguageBeTranslated) { if(translateFromDictionary != null && translateFromDictionary[rootValue.Key].TextValue != null && translateFromDictionary[rootValue.Key].TextValue != "") { if(GUILayout.Button("T", GUILayout.Width(20))) { smartLocWindow.MicrosoftTranslator.TranslateText(translateFromDictionary[rootValue.Key].TextValue,translateFromLanguage, thisCultureInfo.Name, rootValue.Key, new TranslateCompleteCallback(TranslatedTextCompleted)); } } else { GUILayout.Label("T", GUILayout.Width(20)); } } thisLanguageValues[iterationCount].changedValue.TextValue = EditorGUILayout.TextField(thisLanguageValues[iterationCount].changedValue.TextValue); EditorGUILayout.EndHorizontal(); } /// <summary> /// Shows the GUI for a key with the type of GAME_OBJECT /// </summary> /// <param name='rootValue'> /// Root value. /// </param> private void OnGameObjectGUI(KeyValuePair<string,LocalizedObject> rootValue, int iterationCount) { EditorGUILayout.BeginHorizontal(); GUILayout.Label(rootValue.Key, GUILayout.Width(120)); GUILayout.Label(rootValue.Value.TextValue,GUILayout.Width(120)); //If the user wants to copy the base value of this key GUILayout.Label("Copy Base", GUILayout.Width(70)); //If the language can be translated(PlaceHolder for now) GUILayout.Label("T", GUILayout.Width(20)); thisLanguageValues[iterationCount].changedValue.ThisGameObject = (GameObject)EditorGUILayout.ObjectField( thisLanguageValues[iterationCount].changedValue.ThisGameObject, typeof(GameObject),false); EditorGUILayout.EndHorizontal(); } /// <summary> /// Shows the GUI for a key with the type of AUDIO /// </summary> /// <param name='rootValue'> /// Root value. /// </param> private void OnAudioGUI(KeyValuePair<string,LocalizedObject> rootValue, int iterationCount) { EditorGUILayout.BeginHorizontal(); GUILayout.Label(rootValue.Key, GUILayout.Width(120)); GUILayout.Label(rootValue.Value.TextValue,GUILayout.Width(120)); //If the user wants to copy the base value of this key GUILayout.Label("Copy Base", GUILayout.Width(70)); //If the language can be translated(PlaceHolder for now) GUILayout.Label("T", GUILayout.Width(20)); thisLanguageValues[iterationCount].changedValue.ThisAudioClip = (AudioClip)EditorGUILayout.ObjectField( thisLanguageValues[iterationCount].changedValue.ThisAudioClip, typeof(AudioClip),false); EditorGUILayout.EndHorizontal(); } /// <summary> /// Shows the GUI for a key with the type of TEXTURE /// </summary> /// <param name='rootValue'> /// Root value. /// </param> private void OnTextureGUI(KeyValuePair<string,LocalizedObject> rootValue, int iterationCount) { EditorGUILayout.BeginHorizontal(); GUILayout.Label(rootValue.Key, GUILayout.Width(120)); GUILayout.Label(rootValue.Value.TextValue,GUILayout.Width(120)); //If the user wants to copy the base value of this key GUILayout.Label("Copy Base", GUILayout.Width(70)); //If the language can be translated(PlaceHolder for now) GUILayout.Label("T", GUILayout.Width(20)); thisLanguageValues[iterationCount].changedValue.ThisTexture = (Texture)EditorGUILayout.ObjectField( thisLanguageValues[iterationCount].changedValue.ThisTexture, typeof(Texture),false); EditorGUILayout.EndHorizontal(); } #endregion #region Event Callbacks void OnRootFileChanged() { rootFileChanged = true; } /// <summary> /// Callback when the translated text is translated /// </summary> /// <param name='key'> /// The key of the translated value /// </param> /// <param name='translatedValue'> /// Translated value. /// </param> public void TranslatedTextCompleted(string key, string translatedValue) { for(int i = 0; i < thisLanguageValues.Count; i++) { SerializableLocalizationObjectPair objectPair = thisLanguageValues[i]; if(objectPair.keyValue == key) { objectPair.changedValue.TextValue = translatedValue; break; } } } /// <summary> /// Callback when the translated array of texts is completed /// </summary> /// <param name='keys'> /// Keys. /// </param> /// <param name='translatedValues'> /// Translated values. /// </param> public void TranslatedTextArrayCompleted(List<string> keys, List<string> translatedValues) { for(int j = 0; j < keys.Count; j++) { for(int i = 0; i < thisLanguageValues.Count; i++) { SerializableLocalizationObjectPair objectPair = thisLanguageValues[i]; if(objectPair.keyValue == keys[j]) { objectPair.changedValue.TextValue = translatedValues[j]; break; } } } } #endregion /// <summary> /// Shows the translate window window. /// </summary> public static TranslateLanguageWindow ShowWindow(CultureInfo info, SmartLocalizationWindow smartLocWindow) { TranslateLanguageWindow thisWindow = (TranslateLanguageWindow)EditorWindow.GetWindow<TranslateLanguageWindow>("Translate Language",true,typeof(SmartLocalizationWindow)); thisWindow.smartLocWindow = smartLocWindow; thisWindow.Initialize(info); return thisWindow; } }
// 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.Linq; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class StackTests { [Fact] public static void Ctor_Empty() { var stack = new Stack(); Assert.Equal(0, stack.Count); Assert.False(stack.IsSynchronized); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Ctor_Int(int initialCapacity) { var stack = new Stack(initialCapacity); Assert.Equal(0, stack.Count); Assert.False(stack.IsSynchronized); } [Fact] public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new Stack(-1)); // InitialCapacity < 0 } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] [InlineData(10000)] public static void Ctor_ICollection(int count) { var array = new object[count]; for (int i = 0; i < count; i++) { array[i] = i; } var stack = new Stack(array); Assert.Equal(count, stack.Count); Assert.False(stack.IsSynchronized); for (int i = 0; i < count; i++) { Assert.Equal(count - i - 1, stack.Pop()); } } [Fact] public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("col", () => new Stack(null)); // Collection is null } [Fact] public static void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Stack()); var stack = new Stack(); stack.Push("a"); stack.Push(1); stack.Push("b"); stack.Push(2); DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(stack); PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items"); object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance); Assert.Equal(stack.ToArray(), items); } [Fact] public static void DebuggerAttribute_NullStack_ThrowsArgumentNullException() { bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Stack), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public static void Clear() { Stack stack1 = Helpers.CreateIntStack(100); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { stack2.Clear(); Assert.Equal(0, stack2.Count); stack2.Clear(); Assert.Equal(0, stack2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Clone(int count) { Stack stack1 = Helpers.CreateIntStack(count); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { Stack stackClone = (Stack)stack2.Clone(); Assert.Equal(stack2.Count, stackClone.Count); Assert.Equal(stack2.IsSynchronized, stackClone.IsSynchronized); for (int i = 0; i < stackClone.Count; i++) { Assert.Equal(stack2.Pop(), stackClone.Pop()); } }); } [Fact] public static void Clone_IsShallowCopy() { var stack1 = new Stack(); stack1.Push(new Foo(10)); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { Stack stackClone = (Stack)stack2.Clone(); Foo a1 = (Foo)stack2.Pop(); a1.IntValue = 50; Foo a2 = (Foo)stackClone.Pop(); Assert.Equal(50, a1.IntValue); }); } [Fact] public static void Contains() { Stack stack1 = Helpers.CreateIntStack(100); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { for (int i = 0; i < stack2.Count; i++) { Assert.True(stack2.Contains(i)); } Assert.False(stack2.Contains(101)); Assert.False(stack2.Contains("hello")); Assert.False(stack2.Contains(null)); stack2.Push(null); Assert.True(stack2.Contains(null)); Assert.False(stack2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(1000, 0)] [InlineData(10, 5)] [InlineData(100, 50)] [InlineData(1000, 500)] public static void CopyTo_ObjectArray(int count, int index) { Stack stack1 = Helpers.CreateIntStack(count); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { object[] oArray = new object[index + count]; stack2.CopyTo(oArray, index); Assert.Equal(index + count, oArray.Length); for (int i = index; i < count; i++) { Assert.Equal(stack2.Pop(), oArray[i]); } }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(1000, 0)] [InlineData(10, 5)] [InlineData(100, 50)] [InlineData(1000, 500)] public static void CopyTo_IntArray(int count, int index) { Stack stack1 = Helpers.CreateIntStack(count); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { int[] iArray = new int[index + count]; stack2.CopyTo(iArray, index); Assert.Equal(index + count, iArray.Length); for (int i = index; i < count; i++) { Assert.Equal(stack2.Pop(), iArray[i]); } }); } [Fact] public static void CopyTo_Invalid() { Stack stack1 = Helpers.CreateIntStack(100); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { AssertExtensions.Throws<ArgumentNullException>("array", () => stack2.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => stack2.CopyTo(new object[10, 10], 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => stack2.CopyTo(new object[100], -1)); // Index < 0 AssertExtensions.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[0], 0)); // Index >= array.Count AssertExtensions.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[100], 1)); // Index + array.Count > stack.Count AssertExtensions.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[150], 51)); // Index + array.Count > stack.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetEnumerator(int count) { Stack stack1 = Helpers.CreateIntStack(count); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { Assert.NotSame(stack2.GetEnumerator(), stack2.GetEnumerator()); IEnumerator enumerator = stack2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { counter++; Assert.NotNull(enumerator.Current); } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public static void GetEnumerator_StartOfEnumeration_Clone() { Stack stack = Helpers.CreateIntStack(10); IEnumerator enumerator = stack.GetEnumerator(); ICloneable cloneableEnumerator = (ICloneable)enumerator; IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone(); Assert.NotSame(enumerator, clonedEnumerator); // Cloned and original enumerators should enumerate separately. Assert.True(enumerator.MoveNext()); Assert.Equal(stack.Count - 1, enumerator.Current); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(stack.Count - 1, enumerator.Current); Assert.Equal(stack.Count - 1, clonedEnumerator.Current); // Cloned and original enumerators should enumerate in the same sequence. for (int i = 1; i < stack.Count; i++) { Assert.True(enumerator.MoveNext()); Assert.NotEqual(enumerator.Current, clonedEnumerator.Current); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(enumerator.Current, clonedEnumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Equal(0, clonedEnumerator.Current); Assert.False(clonedEnumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current); } [Fact] public static void GetEnumerator_InMiddleOfEnumeration_Clone() { Stack stack = Helpers.CreateIntStack(10); IEnumerator enumerator = stack.GetEnumerator(); enumerator.MoveNext(); ICloneable cloneableEnumerator = (ICloneable)enumerator; // Cloned and original enumerators should start at the same spot, even // if the original is in the middle of enumeration. IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone(); Assert.Equal(enumerator.Current, clonedEnumerator.Current); for (int i = 0; i < stack.Count - 1; i++) { Assert.True(clonedEnumerator.MoveNext()); } Assert.False(clonedEnumerator.MoveNext()); } [Fact] public static void GetEnumerator_Invalid() { Stack stack1 = Helpers.CreateIntStack(100); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { IEnumerator enumerator = stack2.GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index > dictionary.Count while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // MoveNext and Reset throws after stack is modified, but current doesn't enumerator = stack2.GetEnumerator(); enumerator.MoveNext(); stack2.Push("hi"); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.NotNull(enumerator.Current); enumerator = stack2.GetEnumerator(); enumerator.MoveNext(); stack2.Pop(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.NotNull(enumerator.Current); }); } [Fact] public static void Peek() { int count = 100; Stack stack1 = Helpers.CreateIntStack(count); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { for (int i = 0; i < count; i++) { int peek1 = (int)stack2.Peek(); int peek2 = (int)stack2.Peek(); Assert.Equal(peek1, peek2); Assert.Equal(stack2.Pop(), peek1); Assert.Equal(count - i - 1, peek1); } }); } [Fact] public static void Peek_EmptyStack_ThrowsInvalidOperationException() { var stack1 = new Stack(); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { Assert.Throws<InvalidOperationException>(() => stack2.Peek()); // Empty stack for (int i = 0; i < 1000; i++) { stack2.Push(i); } for (int i = 0; i < 1000; i++) { stack2.Pop(); } Assert.Throws<InvalidOperationException>(() => stack2.Peek()); // Empty stack }); } [Theory] [InlineData(1, 1)] [InlineData(10, 10)] [InlineData(100, 100)] [InlineData(1000, 1000)] [InlineData(10, 5)] [InlineData(100, 50)] [InlineData(1000, 500)] public static void Pop(int pushCount, int popCount) { Stack stack1 = Helpers.CreateIntStack(pushCount); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { for (int i = 0; i < popCount; i++) { Assert.Equal(pushCount - i - 1, stack2.Pop()); Assert.Equal(pushCount - i - 1, stack2.Count); } Assert.Equal(pushCount - popCount, stack2.Count); }); } [Fact] public static void Pop_Null() { var stack1 = new Stack(); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { stack2.Push(null); stack2.Push(-1); stack2.Push(null); Assert.Null(stack2.Pop()); Assert.Equal(-1, stack2.Pop()); Assert.Null(stack2.Pop()); }); } [Fact] public static void Pop_EmptyStack_ThrowsInvalidOperationException() { var stack1 = new Stack(); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { Assert.Throws<InvalidOperationException>(() => stack2.Pop()); // Empty stack }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Push(int count) { var stack1 = new Stack(); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { for (int i = 0; i < count; i++) { stack2.Push(i); Assert.Equal(i + 1, stack2.Count); } Assert.Equal(count, stack2.Count); }); } [Fact] public static void Push_Null() { var stack1 = new Stack(); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { stack2.Push(null); stack2.Push(-1); stack2.Push(null); Assert.True(stack2.Contains(null)); Assert.True(stack2.Contains(-1)); }); } [Fact] public static void Synchronized_IsSynchronized() { Stack stack = Stack.Synchronized(new Stack()); Assert.True(stack.IsSynchronized); } [Fact] public static void Synchronized_NullStack_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("stack", () => Stack.Synchronized(null)); // Stack is null } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void ToArray(int count) { Stack stack1 = Helpers.CreateIntStack(count); Helpers.PerformActionOnAllStackWrappers(stack1, stack2 => { object[] array = stack2.ToArray(); Assert.Equal(stack2.Count, array.Length); for (int i = 0; i < array.Length; i++) { Assert.Equal(stack2.Pop(), array[i]); } }); } private class Foo { public Foo(int intValue) { IntValue = intValue; } public int IntValue { get; set; } } } public class Stack_SyncRootTests { private Stack _stackDaughter; private Stack _stackGrandDaughter; private const int NumberOfElements = 100; [Fact] public void GetSyncRootBasic() { // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother Stack // 2) Get a Fixed wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var stackMother = new Stack(); for (int i = 0; i < NumberOfElements; i++) { stackMother.Push(i); } Assert.IsType<Stack>(stackMother.SyncRoot); Stack stackSon = Stack.Synchronized(stackMother); _stackGrandDaughter = Stack.Synchronized(stackSon); _stackDaughter = Stack.Synchronized(stackMother); Assert.Equal(stackSon.SyncRoot, stackMother.SyncRoot); Assert.Equal(_stackGrandDaughter.SyncRoot, stackMother.SyncRoot); Assert.Equal(_stackDaughter.SyncRoot, stackMother.SyncRoot); Assert.Equal(stackSon.SyncRoot, stackMother.SyncRoot); // We are going to rumble with the Stacks with 2 threads Action ts1 = SortElements; Action ts2 = ReverseElements; var tasks = new Task[4]; for (int iThreads = 0; iThreads < tasks.Length; iThreads += 2) { tasks[iThreads] = Task.Run(ts1); tasks[iThreads + 1] = Task.Run(ts2); } Task.WaitAll(tasks); } private void SortElements() { _stackGrandDaughter.Clear(); for (int i = 0; i < NumberOfElements; i++) { _stackGrandDaughter.Push(i); } } private void ReverseElements() { _stackDaughter.Clear(); for (int i = 0; i < NumberOfElements; i++) { _stackDaughter.Push(i); } } } }
// // System.Web.Compilation.BaseCompiler // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (c) Copyright 2002,2003 Ximian, Inc (http://www.ximian.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.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Reflection; using System.Text; using System.Web.UI; using System.Web.Configuration; using System.IO; namespace System.Web.Compilation { abstract class BaseCompiler { protected static string dynamicBase = AppDomain.CurrentDomain.SetupInformation.DynamicBase; TemplateParser parser; CodeDomProvider provider; ICodeCompiler compiler; CodeCompileUnit unit; CodeNamespace mainNS; CompilerParameters compilerParameters; protected CodeTypeDeclaration mainClass; protected CodeTypeReferenceExpression mainClassExpr; protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression (); protected BaseCompiler (TemplateParser parser) { compilerParameters = new CompilerParameters (); this.parser = parser; } void Init () { unit = new CodeCompileUnit (); mainNS = new CodeNamespace ("ASP"); unit.Namespaces.Add (mainNS); mainClass = new CodeTypeDeclaration (parser.ClassName); mainClass.TypeAttributes = TypeAttributes.Public; mainNS.Types.Add (mainClass); mainClass.BaseTypes.Add (new CodeTypeReference (parser.BaseType.FullName)); mainClassExpr = new CodeTypeReferenceExpression ("ASP." + parser.ClassName); foreach (object o in parser.Imports) { if (o is string) mainNS.Imports.Add (new CodeNamespaceImport ((string) o)); } if (parser.Assemblies != null) { foreach (object o in parser.Assemblies) { if (o is string) unit.ReferencedAssemblies.Add ((string) o); } } // Late-bound generators specifics (as for MonoBASIC/VB.NET) unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn; unit.UserData["AllowLateBound"] = !parser.StrictOn; AddInterfaces (); AddClassAttributes (); CreateStaticFields (); AddApplicationAndSessionObjects (); AddScripts (); CreateConstructor (null, null); } protected virtual void CreateStaticFields () { CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized"); fld.Attributes = MemberAttributes.Private | MemberAttributes.Static; fld.InitExpression = new CodePrimitiveExpression (false); mainClass.Members.Add (fld); } protected virtual void CreateConstructor (CodeStatementCollection localVars, CodeStatementCollection trueStmt) { CodeConstructor ctor = new CodeConstructor (); ctor.Attributes = MemberAttributes.Public; mainClass.Members.Add (ctor); if (localVars != null) ctor.Statements.AddRange (localVars); CodeTypeReferenceExpression r; r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name); CodeFieldReferenceExpression intialized; intialized = new CodeFieldReferenceExpression (r, "__intialized"); CodeBinaryOperatorExpression bin; bin = new CodeBinaryOperatorExpression (intialized, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)); CodeAssignStatement assign = new CodeAssignStatement (intialized, new CodePrimitiveExpression (true)); CodeConditionStatement cond = new CodeConditionStatement (bin, assign); if (trueStmt != null) cond.TrueStatements.AddRange (trueStmt); ctor.Statements.Add (cond); } void AddScripts () { if (parser.Scripts == null || parser.Scripts.Count == 0) return; foreach (object o in parser.Scripts) { if (o is string) mainClass.Members.Add (new CodeSnippetTypeMember ((string) o)); } } protected virtual void CreateMethods () { } protected virtual void AddInterfaces () { if (parser.Interfaces == null) return; foreach (object o in parser.Interfaces) { if (o is string) mainClass.BaseTypes.Add (new CodeTypeReference ((string) o)); } } protected virtual void AddClassAttributes () { } protected virtual void AddApplicationAndSessionObjects () { } /* Utility methods for <object> stuff */ protected void CreateApplicationOrSessionPropertyForObject (Type type, string propName, bool isApplication, bool isPublic) { /* if isApplication this generates (the 'cachedapp' field is created earlier): private MyNS.MyClass app { get { if ((this.cachedapp == null)) { this.cachedapp = ((MyNS.MyClass) (this.Application.StaticObjects.GetObject("app"))); } return this.cachedapp; } } else, this is for Session: private MyNS.MyClass ses { get { return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses"))); } } */ CodeExpression result = null; CodeMemberProperty prop = new CodeMemberProperty (); prop.Type = new CodeTypeReference (type); prop.Name = propName; if (isPublic) prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; else prop.Attributes = MemberAttributes.Private | MemberAttributes.Final; CodePropertyReferenceExpression p1; if (isApplication) p1 = new CodePropertyReferenceExpression (thisRef, "Application"); else p1 = new CodePropertyReferenceExpression (thisRef, "Session"); CodePropertyReferenceExpression p2; p2 = new CodePropertyReferenceExpression (p1, "StaticObjects"); CodeMethodReferenceExpression getobject; getobject = new CodeMethodReferenceExpression (p2, "GetObject"); CodeMethodInvokeExpression invoker; invoker = new CodeMethodInvokeExpression (getobject, new CodePrimitiveExpression (propName)); CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker); if (isApplication) { CodeFieldReferenceExpression field; field = new CodeFieldReferenceExpression (thisRef, "cached" + propName); CodeConditionStatement stmt = new CodeConditionStatement(); stmt.Condition = new CodeBinaryOperatorExpression (field, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression (null)); CodeAssignStatement assign = new CodeAssignStatement (); assign.Left = field; assign.Right = cast; stmt.TrueStatements.Add (assign); prop.GetStatements.Add (stmt); result = field; } else { result = cast; } prop.GetStatements.Add (new CodeMethodReturnStatement (result)); mainClass.Members.Add (prop); } protected string CreateFieldForObject (Type type, string name) { string fieldName = "cached" + name; CodeMemberField f = new CodeMemberField (type, fieldName); f.Attributes = MemberAttributes.Private; mainClass.Members.Add (f); return fieldName; } protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic) { CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName); CodeMemberProperty prop = new CodeMemberProperty (); prop.Type = new CodeTypeReference (type); prop.Name = propName; if (isPublic) prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; else prop.Attributes = MemberAttributes.Private | MemberAttributes.Final; CodeConditionStatement stmt = new CodeConditionStatement(); stmt.Condition = new CodeBinaryOperatorExpression (field, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression (null)); CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type); stmt.TrueStatements.Add (new CodeAssignStatement (field, create)); prop.GetStatements.Add (stmt); prop.GetStatements.Add (new CodeMethodReturnStatement (field)); mainClass.Members.Add (prop); } /******/ void CheckCompilerErrors (CompilerResults results) { if (results.NativeCompilerReturnValue == 0) return; StringWriter writer = new StringWriter(); provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null); throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ()); } public virtual Type GetCompiledType () { Type type = CachingCompiler.GetTypeFromCache (parser.InputFile); if (type != null) return type; Init (); string lang = parser.Language; CompilationConfiguration config; config = CompilationConfiguration.GetInstance (parser.Context); provider = config.GetProvider (lang); if (provider == null) throw new HttpException ("Configuration error. Language not supported: " + lang, 500); compiler = provider.CreateCompiler (); CreateMethods (); compilerParameters.IncludeDebugInformation = parser.Debug; compilerParameters.CompilerOptions = config.GetCompilerOptions (lang) + " " + parser.CompilerOptions; compilerParameters.WarningLevel = config.GetWarningLevel (lang); bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null); if (!Directory.Exists (dynamicBase)) Directory.CreateDirectory (dynamicBase); TempFileCollection tempcoll = new TempFileCollection (config.TempDirectory, keepFiles); compilerParameters.TempFiles = tempcoll; string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true)); compilerParameters.OutputAssembly = Path.Combine (dynamicBase, dllfilename); CompilerResults results = CachingCompiler.Compile (this); CheckCompilerErrors (results); Assembly assembly = results.CompiledAssembly; if (assembly == null) { if (!File.Exists (compilerParameters.OutputAssembly)) throw new CompilationException (parser.InputFile, results.Errors, "No assembly returned after compilation!?"); assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly); } results.TempFiles.Delete (); return assembly.GetType (mainClassExpr.Type.BaseType, true); } internal CompilerParameters CompilerParameters { get { return compilerParameters; } } internal CodeCompileUnit Unit { get { return unit; } } internal virtual ICodeCompiler Compiler { get { return compiler; } } internal TemplateParser Parser { get { return parser; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Authentication { public class AuthenticationServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAuthenticationService m_AuthenticationService; private bool m_AllowGetAuthInfo = false; private bool m_AllowSetAuthInfo = false; private bool m_AllowSetPassword = false; public AuthenticationServerPostHandler(IAuthenticationService service) : this(service, null, null) {} public AuthenticationServerPostHandler(IAuthenticationService service, IConfig config, IServiceAuth auth) : base("POST", "/auth", auth) { m_AuthenticationService = service; if (config != null) { m_AllowGetAuthInfo = config.GetBoolean("AllowGetAuthInfo", m_AllowGetAuthInfo); m_AllowSetAuthInfo = config.GetBoolean("AllowSetAuthInfo", m_AllowSetAuthInfo); m_AllowSetPassword = config.GetBoolean("AllowSetPassword", m_AllowSetPassword); } } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.Error("[XXX]: Authenticating..."); string[] p = SplitParams(path); if (p.Length > 0) { switch (p[0]) { case "plain": StreamReader sr = new StreamReader(request); string body = sr.ReadToEnd(); sr.Close(); return DoPlainMethods(body); case "crypt": byte[] buffer = new byte[request.Length]; long length = request.Length; if (length > 16384) length = 16384; request.Read(buffer, 0, (int)length); return DoEncryptedMethods(buffer); } } return new byte[0]; } private byte[] DoPlainMethods(string body) { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); int lifetime = 30; if (request.ContainsKey("LIFETIME")) { lifetime = Convert.ToInt32(request["LIFETIME"].ToString()); if (lifetime > 30) lifetime = 30; } if (!request.ContainsKey("METHOD")) return FailureResult(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); string method = request["METHOD"].ToString(); UUID principalID; string token; if (!UUID.TryParse(request["PRINCIPAL"].ToString(), out principalID)) return FailureResult(); switch (method) { case "authenticate": if (!request.ContainsKey("PASSWORD")) return FailureResult(); token = m_AuthenticationService.Authenticate(principalID, request["PASSWORD"].ToString(), lifetime); if (token != String.Empty) return SuccessResult(token); return FailureResult(); case "setpassword": if (!m_AllowSetPassword) return FailureResult(); if (!request.ContainsKey("PASSWORD")) return FailureResult(); if (m_AuthenticationService.SetPassword(principalID, request["PASSWORD"].ToString())) return SuccessResult(); else return FailureResult(); case "verify": if (!request.ContainsKey("TOKEN")) return FailureResult(); if (m_AuthenticationService.Verify(principalID, request["TOKEN"].ToString(), lifetime)) return SuccessResult(); return FailureResult(); case "release": if (!request.ContainsKey("TOKEN")) return FailureResult(); if (m_AuthenticationService.Release(principalID, request["TOKEN"].ToString())) return SuccessResult(); return FailureResult(); case "getauthinfo": if (m_AllowGetAuthInfo) return GetAuthInfo(principalID); break; case "setauthinfo": if (m_AllowSetAuthInfo) return SetAuthInfo(principalID, request); break; } return FailureResult(); } private byte[] DoEncryptedMethods(byte[] ciphertext) { return new byte[0]; } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } byte[] GetAuthInfo(UUID principalID) { AuthInfo info = m_AuthenticationService.GetAuthInfo(principalID); if (info != null) { Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = info.ToKeyValuePairs(); return ResultToBytes(result); } else { return FailureResult(); } } byte[] SetAuthInfo(UUID principalID, Dictionary<string, object> request) { AuthInfo existingInfo = m_AuthenticationService.GetAuthInfo(principalID); if (existingInfo == null) return FailureResult(); if (request.ContainsKey("AccountType")) existingInfo.AccountType = request["AccountType"].ToString(); if (request.ContainsKey("PasswordHash")) existingInfo.PasswordHash = request["PasswordHash"].ToString(); if (request.ContainsKey("PasswordSalt")) existingInfo.PasswordSalt = request["PasswordSalt"].ToString(); if (request.ContainsKey("WebLoginKey")) existingInfo.WebLoginKey = request["WebLoginKey"].ToString(); if (!m_AuthenticationService.SetAuthInfo(existingInfo)) { m_log.ErrorFormat( "[AUTHENTICATION SERVER POST HANDLER]: Authentication info store failed for account {0} {1} {2}", existingInfo.PrincipalID); return FailureResult(); } return SuccessResult(); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] SuccessResult(string token) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); XmlElement t = doc.CreateElement("", "Token", ""); t.AppendChild(doc.CreateTextNode(token)); rootElement.AppendChild(t); return Util.DocToBytes(doc); } private byte[] ResultToBytes(Dictionary<string, object> result) { string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } } }
#region License /* * Copyright 2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; #if NET_2_0 using System.Collections.Generic; #endif using System.Reflection; using System.Runtime.Serialization; using System.Security.Policy; using NUnit.Framework; using Spring.Objects; using Spring.Objects.Factory; using Spring.Util; #endregion namespace Spring.Util { /// <summary> /// Unit tests for the ObjectUtils class. /// </summary> /// <author>Rick Evans (.NET)</author> [TestFixture] public class ObjectUtilsTests { [Test] public void NullSafeEqualsWithBothNull() { string first = null; string second = null; Assert.IsTrue(ObjectUtils.NullSafeEquals(first, second)); } [Test] public void NullSafeEqualsWithFirstNull() { string first = null; string second = ""; Assert.IsFalse(ObjectUtils.NullSafeEquals(first, second)); } [Test] public void NullSafeEqualsWithSecondNull() { string first = ""; string second = null; Assert.IsFalse(ObjectUtils.NullSafeEquals(first, second)); } [Test] public void NullSafeEqualsBothEquals() { string first = "this is it"; string second = "this is it"; Assert.IsTrue(ObjectUtils.NullSafeEquals(first, second)); } [Test] public void NullSafeEqualsNotEqual() { string first = "this is it"; int second = 12; Assert.IsFalse(ObjectUtils.NullSafeEquals(first, second)); } [Test] public void IsAssignableAndNotTransparentProxyWithProxy() { AppDomain domain = null; try { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Environment.CurrentDirectory; domain = AppDomain.CreateDomain("Spring", new Evidence(AppDomain.CurrentDomain.Evidence), setup); object foo = domain.CreateInstanceAndUnwrap(GetType().Assembly.FullName, typeof(Foo).FullName); // the instance is definitely assignable to the supplied interface type... bool isAssignable = ObjectUtils.IsAssignableAndNotTransparentProxy(typeof (IFoo), foo); Assert.IsFalse(isAssignable, "Proxied instance was not recognized as such."); } finally { AppDomain.Unload(domain); } } [Test] [ExpectedException(typeof(ArgumentNullException))] public void InstantiateTypeWithNullType() { ObjectUtils.InstantiateType(null); } [Test] public void InstantiateType() { object foo = ObjectUtils.InstantiateType(typeof (TestObject)); Assert.IsNotNull(foo, "Failed to instantiate an instance of a valid Type."); Assert.IsTrue(foo is TestObject, "The instantiated instance was not an instance of the type that was passed in."); } [Test] public void InstantiateTypeThrowingWithinPublicConstructor() { try { ObjectUtils.InstantiateType(typeof(ThrowingWithinConstructor)); Assert.Fail(); } catch(FatalReflectionException ex) { // no nasty "TargetInvocationException" is in between! Assert.AreEqual( typeof(ThrowingWithinConstructorException), ex.InnerException.GetType() ); } } #if NET_2_0 [Test] [ExpectedException(typeof(FatalReflectionException))] public void InstantiateTypeWithOpenGenericType() { ObjectUtils.InstantiateType(typeof(Dictionary<,>)); } [Test] public void InstantiateGenericTypeWithArguments() { // ObjectUtils.InstantiateType(typeof(Dictionary<string, int>), new object[] { new object() } ); } #endif [Test] [ExpectedException(typeof(FatalReflectionException))] public void InstantiateTypeWithAbstractType() { ObjectUtils.InstantiateType(typeof (AbstractType)); } [Test] [ExpectedException(typeof(FatalReflectionException))] public void InstantiateTypeWithInterfaceType() { ObjectUtils.InstantiateType(typeof (IList)); } [Test] [ExpectedException(typeof(FatalReflectionException))] public void InstantiateTypeWithTypeExposingNoZeroArgCtor() { ObjectUtils.InstantiateType(typeof(NoZeroArgConstructorType)); } [Test] public void InstantiateTypeWithPrivateCtor() { ConstructorInfo ctor = typeof (OnlyPrivateCtor).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] {typeof (string)}, null); object foo = ObjectUtils.InstantiateType(ctor, new object[] {"Chungking Express"}); Assert.IsNotNull(foo, "Failed to instantiate an instance of a valid Type."); Assert.IsTrue(foo is OnlyPrivateCtor, "The instantiated instance was not an instance of the type that was passed in."); Assert.AreEqual("Chungking Express", ((OnlyPrivateCtor) foo).Name); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void InstantiateTypeWithNullCtor() { ObjectUtils.InstantiateType(typeof(IList).GetConstructor(Type.EmptyTypes), new object[] { }); } [Test] public void InstantiateTypeWithCtorWithNoArgs() { Type type = typeof (TestObject); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); object foo = ObjectUtils.InstantiateType(ctor, ObjectUtils.EmptyObjects); Assert.IsNotNull(foo, "Failed to instantiate an instance of a valid Type."); Assert.IsTrue(foo is TestObject, "The instantiated instance was not an instance of the Type that was passed in."); } [Test] public void InstantiateTypeWithCtorArgs() { Type type = typeof (TestObject); ConstructorInfo ctor = type.GetConstructor(new Type[] {typeof (string), typeof (int)}); object foo = ObjectUtils.InstantiateType(ctor, new object[] {"Yakov Petrovich Golyadkin", 39}); Assert.IsNotNull(foo, "Failed to instantiate an instance of a valid Type."); Assert.IsTrue(foo is TestObject, "The instantiated instance was not an instance of the Type that was passed in."); TestObject obj = foo as TestObject; Assert.AreEqual("Yakov Petrovich Golyadkin", obj.Name); Assert.AreEqual(39, obj.Age); } [Test] public void InstantiateTypeWithBadCtorArgs() { Type type = typeof (TestObject); ConstructorInfo ctor = type.GetConstructor(new Type[] {typeof(string), typeof(int)}); try { ObjectUtils.InstantiateType(ctor, new object[] { 39, "Yakov Petrovich Golyadkin" }); Assert.Fail("Should throw an error"); } catch { // ok... } } [Test] public void IsSimpleProperty() { Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (string))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (long))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (bool))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (int))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (float))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (ushort))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (double))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (ulong))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (char))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (uint))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (string[]))); Assert.IsTrue(ObjectUtils.IsSimpleProperty(typeof (Type))); Assert.IsFalse(ObjectUtils.IsSimpleProperty(typeof (TestObject))); Assert.IsFalse(ObjectUtils.IsSimpleProperty(typeof (IList[]))); } [Test] public void EnumerateFirstElement() { string expected = "Hiya"; IList list = new string[] {expected, "Aw!", "Man!"}; IEnumerator enumerator = list.GetEnumerator(); object actual = ObjectUtils.EnumerateFirstElement(enumerator); Assert.AreEqual(expected, actual); } [Test] public void EnumerateElementAtIndex() { string expected = "Mmm..."; IList list = new string[] {"Aw!", "Man!", expected}; IEnumerator enumerator = list.GetEnumerator(); object actual = ObjectUtils.EnumerateElementAtIndex(enumerator, 2); Assert.AreEqual(expected, actual); } [Test] public void EnumerateElementAtIndexViaIEnumerable() { string expected = "Mmm..."; IList list = new string[] {"Aw!", "Man!", expected}; object actual = ObjectUtils.EnumerateElementAtIndex(list, 2); Assert.AreEqual(expected, actual); } [Test] [ExpectedException(typeof (ArgumentOutOfRangeException))] public void EnumerateElementAtOutOfRangeIndex() { string expected = "Mmm..."; IList list = new string[] {"Aw!", "Man!", expected}; IEnumerator enumerator = list.GetEnumerator(); object actual = ObjectUtils.EnumerateElementAtIndex(enumerator, 12); Assert.AreEqual(expected, actual); } [Test] [ExpectedException(typeof (ArgumentOutOfRangeException))] public void EnumerateElementAtOutOfRangeIndexViaIEnumerable() { string expected = "Mmm..."; IList list = new string[] {"Aw!", "Man!", expected}; object actual = ObjectUtils.EnumerateElementAtIndex(list, 12); Assert.AreEqual(expected, actual); } [Test] [ExpectedException(typeof (ArgumentOutOfRangeException))] public void EnumerateElementAtNegativeIndex() { string expected = "Mmm..."; IList list = new string[] {"Aw!", "Man!", expected}; IEnumerator enumerator = list.GetEnumerator(); object actual = ObjectUtils.EnumerateElementAtIndex(enumerator, -10); Assert.AreEqual(expected, actual); } [Test] [ExpectedException(typeof (ArgumentOutOfRangeException))] public void EnumerateElementAtNegativeIndexViaIEnumerable() { string expected = "Mmm..."; IList list = new string[] {"Aw!", "Man!", expected}; object actual = ObjectUtils.EnumerateElementAtIndex(list, -10); Assert.AreEqual(expected, actual); } #region Helper Classes private interface IFoo { } private sealed class Foo : MarshalByRefObject, IFoo { } /// <summary> /// A class that doesn't have a parameterless constructor. /// </summary> private class NoZeroArgConstructorType { /// <summary> /// Creates a new instance of the NoZeroArgConstructorType class. /// </summary> /// <param name="foo">A spurious argument (ignored).</param> public NoZeroArgConstructorType(string foo) { } } /// <summary> /// An abstract class. Doh! /// </summary> private abstract class AbstractType { /// <summary> /// Creates a new instance of the AbstractType class. /// </summary> public AbstractType() { } } private class OnlyPrivateCtor { private OnlyPrivateCtor(string name) { _name = name; } public string Name { get { return _name; } set { _name = value; } } private string _name; } [Serializable] private class ThrowingWithinConstructorException : TestException { public ThrowingWithinConstructorException() {} public ThrowingWithinConstructorException(string message) : base(message) {} public ThrowingWithinConstructorException(string message, Exception inner) : base(message, inner) {} protected ThrowingWithinConstructorException(SerializationInfo info, StreamingContext context) : base(info, context) {} } public class ThrowingWithinConstructor { public ThrowingWithinConstructor() { throw new ThrowingWithinConstructorException(); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; namespace OpenSim.Grid.AgentDomain.Modules { /// <summary> /// Abstract base class used by local and grid implementations of an inventory service. /// </summary> public abstract class InventoryServiceBase : IInterServiceInventoryServices { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected List<IInventoryDataPlugin> m_plugins = new List<IInventoryDataPlugin>(); #region Plugin methods /// <summary> /// Add a new inventory data plugin - plugins will be requested in the order they were added. /// </summary> /// <param name="plugin">The plugin that will provide data</param> public void AddPlugin(IInventoryDataPlugin plugin) { m_plugins.Add(plugin); } /// <summary> /// Adds a list of inventory data plugins, as described by `provider' /// and `connect', to `m_plugins'. /// </summary> /// <param name="provider"> /// The filename of the inventory server plugin DLL. /// </param> /// <param name="connect"> /// The connection string for the storage backend. /// </param> public void AddPlugin(string provider, string connect) { m_plugins.AddRange(DataPluginFactory.LoadDataPlugins<IInventoryDataPlugin>(provider, connect)); } #endregion #region IInventoryServices methods public string Host { get { return "default"; } } public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { // m_log.DebugFormat("[AGENT INVENTORY]: Getting inventory skeleton for {0}", userId); InventoryFolderBase rootFolder = RequestRootFolder(userId); // Agent has no inventory structure yet. if (null == rootFolder) { return null; } List<InventoryFolderBase> userFolders = new List<InventoryFolderBase>(); userFolders.Add(rootFolder); foreach (IInventoryDataPlugin plugin in m_plugins) { IList<InventoryFolderBase> folders = plugin.getFolderHierarchy(rootFolder.ID); userFolders.AddRange(folders); } // foreach (InventoryFolderBase folder in userFolders) // { // m_log.DebugFormat("[AGENT INVENTORY]: Got folder {0} {1}", folder.name, folder.folderID); // } return userFolders; } // See IInventoryServices public virtual bool HasInventoryForUser(UUID userID) { return false; } // See IInventoryServices public virtual InventoryFolderBase RequestRootFolder(UUID userID) { // Retrieve the first root folder we get from the list of plugins. foreach (IInventoryDataPlugin plugin in m_plugins) { InventoryFolderBase rootFolder = plugin.getUserRootFolder(userID); if (rootFolder != null) return rootFolder; } // Return nothing if no plugin was able to supply a root folder return null; } // See IInventoryServices public bool CreateNewUserInventory(UUID user) { InventoryFolderBase existingRootFolder = RequestRootFolder(user); if (null != existingRootFolder) { m_log.WarnFormat( "[AGENT INVENTORY]: Did not create a new inventory for user {0} since they already have " + "a root inventory folder with id {1}", user, existingRootFolder.ID); } else { UsersInventory inven = new UsersInventory(); inven.CreateNewInventorySet(user); AddNewInventorySet(inven); return true; } return false; } public List<InventoryItemBase> GetActiveGestures(UUID userId) { List<InventoryItemBase> activeGestures = new List<InventoryItemBase>(); foreach (IInventoryDataPlugin plugin in m_plugins) { activeGestures.AddRange(plugin.fetchActiveGestures(userId)); } return activeGestures; } #endregion #region Methods used by GridInventoryService public List<InventoryFolderBase> RequestSubFolders(UUID parentFolderID) { List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>(); foreach (IInventoryDataPlugin plugin in m_plugins) { inventoryList.AddRange(plugin.getInventoryFolders(parentFolderID)); } return inventoryList; } public List<InventoryItemBase> RequestFolderItems(UUID folderID) { List<InventoryItemBase> itemsList = new List<InventoryItemBase>(); foreach (IInventoryDataPlugin plugin in m_plugins) { itemsList.AddRange(plugin.getInventoryInFolder(folderID)); } return itemsList; } #endregion // See IInventoryServices public virtual bool AddFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[AGENT INVENTORY]: Adding folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.addInventoryFolder(folder); } // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool UpdateFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[AGENT INVENTORY]: Updating folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.updateInventoryFolder(folder); } // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool MoveFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[AGENT INVENTORY]: Moving folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.moveInventoryFolder(folder); } // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool AddItem(InventoryItemBase item) { m_log.DebugFormat( "[AGENT INVENTORY]: Adding item {0} {1} to folder {2}", item.Name, item.ID, item.Folder); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.addInventoryItem(item); } // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool UpdateItem(InventoryItemBase item) { m_log.InfoFormat( "[AGENT INVENTORY]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.updateInventoryItem(item); } // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool DeleteItem(InventoryItemBase item) { m_log.InfoFormat( "[AGENT INVENTORY]: Deleting item {0} {1} from folder {2}", item.Name, item.ID, item.Folder); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.deleteInventoryItem(item.ID); } // FIXME: Should return false on failure return true; } public virtual InventoryItemBase QueryItem(InventoryItemBase item) { foreach (IInventoryDataPlugin plugin in m_plugins) { InventoryItemBase result = plugin.queryInventoryItem(item.ID); if (result != null) return result; } return null; } public virtual InventoryFolderBase QueryFolder(InventoryFolderBase item) { foreach (IInventoryDataPlugin plugin in m_plugins) { InventoryFolderBase result = plugin.queryInventoryFolder(item.ID); if (result != null) return result; } return null; } /// <summary> /// Purge a folder of all items items and subfolders. /// /// FIXME: Really nasty in a sense, because we have to query the database to get information we may /// already know... Needs heavy refactoring. /// </summary> /// <param name="folder"></param> public virtual bool PurgeFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[AGENT INVENTORY]: Purging folder {0} {1} of its contents", folder.Name, folder.ID); List<InventoryFolderBase> subFolders = RequestSubFolders(folder.ID); foreach (InventoryFolderBase subFolder in subFolders) { // m_log.DebugFormat("[AGENT INVENTORY]: Deleting folder {0} {1}", subFolder.Name, subFolder.ID); foreach (IInventoryDataPlugin plugin in m_plugins) { plugin.deleteInventoryFolder(subFolder.ID); } } List<InventoryItemBase> items = RequestFolderItems(folder.ID); foreach (InventoryItemBase item in items) { DeleteItem(item); } // FIXME: Should return false on failure return true; } private void AddNewInventorySet(UsersInventory inventory) { foreach (InventoryFolderBase folder in inventory.Folders.Values) { AddFolder(folder); } } public InventoryItemBase GetInventoryItem(UUID itemID) { foreach (IInventoryDataPlugin plugin in m_plugins) { InventoryItemBase item = plugin.getInventoryItem(itemID); if (item != null) return item; } return null; } /// <summary> /// Used to create a new user inventory. /// </summary> private class UsersInventory { public Dictionary<UUID, InventoryFolderBase> Folders = new Dictionary<UUID, InventoryFolderBase>(); public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>(); public virtual void CreateNewInventorySet(UUID user) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ParentID = UUID.Zero; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "My Inventory"; folder.Type = (short)AssetType.Folder; folder.Version = 1; Folders.Add(folder.ID, folder); UUID rootFolder = folder.ID; folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Animations"; folder.Type = (short)AssetType.Animation; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Body Parts"; folder.Type = (short)AssetType.Bodypart; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Calling Cards"; folder.Type = (short)AssetType.CallingCard; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Clothing"; folder.Type = (short)AssetType.Clothing; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Gestures"; folder.Type = (short)AssetType.Gesture; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Landmarks"; folder.Type = (short)AssetType.Landmark; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Lost And Found"; folder.Type = (short)AssetType.LostAndFoundFolder; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Notecards"; folder.Type = (short)AssetType.Notecard; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Objects"; folder.Type = (short)AssetType.Object; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Photo Album"; folder.Type = (short)AssetType.SnapshotFolder; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Scripts"; folder.Type = (short)AssetType.LSLText; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Sounds"; folder.Type = (short)AssetType.Sound; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Textures"; folder.Type = (short)AssetType.Texture; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Trash"; folder.Type = (short)AssetType.TrashFolder; folder.Version = 1; Folders.Add(folder.ID, folder); } } } }
using System; using LibGD; using NUnit.Framework; [TestFixture] public class GlobalMembersGdCopyBlurred { public const int WIDTH = 300; public const int HEIGHT = 200; public const int LX = (WIDTH/2); // Line X public const int LY = (HEIGHT/2); // Line Y public const int HT = 3; // Half of line-thickness public const int CLOSE_ENOUGH = 0; public const int PIXEL_CLOSE_ENOUGH = 0; public static void save(gdImageStruct im, string filename) { #if false // FILE *out; // // out = fopen(filename, "wb"); // gd.gdImagePng(im, out); // fclose(out); #else //im, filename; #endif } // save /* Test gd.gdImageScale() with bicubic interpolation on a simple * all-white image. */ public static gdImageStruct mkwhite(int x, int y) { gdImageStruct im; im = gd.gdImageCreateTrueColor(x, y); gd.gdImageFilledRectangle(im, 0, 0, x - 1, y - 1, gd.gdImageColorExactAlpha(im, 255, 255, 255, 0)); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (im != null) ? 1 : 0); gd.gdImageSetInterpolationMethod(im, gdInterpolationMethod.GD_BICUBIC); // FP interp'n return im; } // mkwhite /* Fill with almost-black. */ public static void mkblack(gdImageStruct ptr) { gd.gdImageFilledRectangle(ptr, 0, 0, ptr.sx - 1, ptr.sy - 1, gd.gdImageColorExactAlpha(ptr, 2, 2, 2, 0)); } // mkblack public static gdImageStruct mkcross() { gdImageStruct im; int fg; int n; im = mkwhite(WIDTH, HEIGHT); fg = gd.gdImageColorAllocate(im, 0, 0, 0); for (n = -HT; n < HT; n++) { gd.gdImageLine(im, WIDTH / 2 - n, 0, WIDTH / 2 - n, HEIGHT - 1, fg); gd.gdImageLine(im, 0, HEIGHT / 2 - n, WIDTH - 1, HEIGHT / 2 - n, fg); } // for return im; } // mkcross public static void blurblank(gdImageStruct im, int radius, double sigma) { gdImageStruct result; result = gd.gdImageCopyGaussianBlurred(im, radius, sigma); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (result != null) ? 1 : 0); if (result == null) return; GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gdMaxPixelDiff(im, result) <= CLOSE_ENOUGH) ? 1 : 0); gd.gdImageDestroy(result); } // blurblank public static void do_test() { gdImageStruct im; gdImageStruct imref; gdImageStruct tmp; gdImageStruct same; gdImageStruct same2; im = mkwhite(WIDTH, HEIGHT); imref = mkwhite(WIDTH, HEIGHT); /* Blur a plain white image to various radii and ensure they're * still similar enough. */ blurblank(im, 1, 0.0); blurblank(im, 2, 0.0); blurblank(im, 4, 0.0); blurblank(im, 8, 0.0); blurblank(im, 16, 0.0); /* Ditto a black image. */ mkblack(im); //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro: GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gdMaxPixelDiff(im, imref) >= 240) ? 1 : 0); blurblank(im, 1, 0.0); blurblank(im, 2, 0.0); blurblank(im, 4, 0.0); blurblank(im, 8, 0.0); blurblank(im, 16, 0.0); } // do_test /* Ensure that RGB values are equal, then return r (which is therefore * the whiteness.) */ public static int getwhite(gdImageStruct im, int x, int y) { int px; int r; int g; int b; px = gd.gdImageGetPixel(im, x, y); r = ((im).trueColor != 0 ? (((px) & 0xFF0000) >> 16) : (im).red[(px)]); g = ((im).trueColor != 0 ? (((px) & 0x00FF00) >> 8) : (im).green[(px)]); b = ((im).trueColor != 0 ? ((px) & 0x0000FF) : (im).blue[(px)]); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (r == g && r == b) ? 1 : 0); return r; } // getrgb public static int whitecmp(gdImageStruct im1, gdImageStruct im2, int x, int y) { int w1; int w2; w1 = getwhite(im1, x, y); w2 = getwhite(im2, x, y); return Math.Abs(w1 - w2); } // whitediff public static void do_crosstest() { gdImageStruct im = mkcross(); gdImageStruct blurred; const int RADIUS = 16; GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (im != null) ? 1 : 0); save(im, "cross.png"); blurred = gd.gdImageCopyGaussianBlurred(im, RADIUS, 0.0); save(blurred, "blurredcross.png"); /* These spots shouldn't be affected. */ GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, 5, 5) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, WIDTH - 5, 5) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, 5, HEIGHT - 5) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, WIDTH - 5, HEIGHT - 5) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); // printf("%d %d %d %d\n", whitecmp(im, blurred, 0, 0), whitecmp(im, blurred, WIDTH-1, 0), // whitecmp(im, blurred, 0, HEIGHT-1), whitecmp(im, blurred, WIDTH-1, HEIGHT-1)); /* Ditto these, right in the corners */ GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, 0, 0) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, WIDTH - 1, 0) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, 0, HEIGHT - 1) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (whitecmp(im, blurred, WIDTH - 1, HEIGHT - 1) <= PIXEL_CLOSE_ENOUGH) ? 1 : 0); /* Now, poking let's poke around the blurred lines. */ /* Vertical line gets darker when approached from the left. */ GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, 1, 1) > getwhite(blurred, WIDTH / 2 - (HT - 1), 1) ? 1 : 0)); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, WIDTH / 2 - 2, 1) > getwhite(blurred, WIDTH / 2 - 1, 1) ? 1 : 0)); /* ...and lighter when moving away to the right. */ GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, WIDTH / 2 + 2, 1) >= getwhite(blurred, WIDTH / 2 + 1, 1) ? 1 : 0)); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, WIDTH / 2 + 3, 1) >= getwhite(blurred, WIDTH / 2 + 2, 1) ? 1 : 0)); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, WIDTH - 1, 1) > getwhite(blurred, WIDTH / 2 + 1, 1) ? 1 : 0)); /* And the same way, vertically */ GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, 1, 1) > getwhite(blurred, 1, HEIGHT / 2 - (HT - 1))) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, 1, HEIGHT / 2 - (HT - 1)) > getwhite(blurred, 1, HEIGHT / 2 - (HT - 2))) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, 1, HEIGHT / 2) <= getwhite(blurred, 1, HEIGHT / 2 + 1)) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, 1, HEIGHT / 2 + 1) < getwhite(blurred, 1, HEIGHT / 2 + 3)) ? 1 : 0); GlobalMembersGdtest.gdTestAssert(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, "assert failed in <%s:%i>\n", (getwhite(blurred, 1, HEIGHT / 2 + 3) < getwhite(blurred, 1, HEIGHT - 1)) ? 1 : 0); } // do_crosstest [Test] public void TestGdCopyBlurred() { do_test(); do_crosstest(); Assert.AreEqual(0, GlobalMembersGdtest.gdNumFailures()); } }
//#define debug using System; using System.Collections.Generic; using System.Text; namespace ICSimulator { /** * @brief This is an implementation of buffered ring network interface proposed in * Ravindran et al. "A Performance Comparison of Hierarchical Ring- and Mesh-Connected Multiprocessor Networks", * HPCA 1997. * * << NIC >> * Although it's supposed to be using a wormhole flow control, it's actually more like a cut-through * flow control since its ring buffer size is exactly 1 packet in the paper. * * Injection policy: * 1. if the ring buffer is empty and no packet is being transmitted, injection of a new packet can * bypass the ring buffer to the next node. Priority is given over to response packets over * request packets. * 2. Ring buffer is not empty, injection is not allowed. One exception is that once the header flit * of the inject packet is started. Priority is given over to injection until it's done. * * Ring buffer: * Header flit allocated it and a tail flit deallocates it. * * Arbitration: * As mentioned above, arbitration to the next node is always given to in-flight flit (ones in the buffer), * except for the case that a local injection has already started for a packet. * Arbitration always need to check the downstream buffer and see if it's available. * * Caveat: No bypassing. * * TODO: prioritization at the injection queue pool * **/ public class WormholeBuffer { Queue<Flit> buf; // Due to pipelining, we need to increment the buffer count ahead of // time. Sort of like credit. int bufSize, lookAheadSize; bool bWorm; public WormholeBuffer(int size) { bufSize = size; lookAheadSize = 0; if (size < 1) throw new Exception("The buffer size must be at least 1-flit big."); buf = new Queue<Flit>(); bWorm = false; } public void enqueue(Flit f) { if (buf.Count == bufSize) throw new Exception("Cannot enqueue into the ring buffer due to size limit."); buf.Enqueue(f); Simulator.stats.totalBufferEnqCount.Add(); } public Flit dequeue() { Flit f = buf.Dequeue(); lookAheadSize--; // Take care of the cases when queue becomes empty while there is // still more body flits coming in. This is needed because the // arbitration simply looks at the queue and see if it's empty. It // assumes the worm is gone if queue is empty. TODO: this doesn't // fix the deadlock case when buffer size is less than 2. if (f.isHeadFlit && f.packet.nrOfFlits != 1) bWorm = true; if (f.isTailFlit && f.packet.nrOfFlits != 1) bWorm = false; return f; } public bool IsWorm {get { return bWorm;} } public Flit peek() { Flit f = null; if (buf.Count > 0) f = buf.Peek(); return f; } public bool canEnqNewFlit(Flit f) { #if debug Console.WriteLine("cyc {0} flit asking for enq pkt ID {1} flitNr {2}", Simulator.CurrentRound, f.packet.ID, f.flitNr); #endif if (lookAheadSize < bufSize) { lookAheadSize++; return true; } return false; } } public class Router_Node_Buffer : Router { Flit m_injectSlot_CW; Flit m_injectSlot_CCW; Queue<Flit>[] ejectBuffer; WormholeBuffer[] m_ringBuf; int starveCounter; int Local = 0;// defined in router_bridge public Router_Node_Buffer(Coord myCoord) : base(myCoord) { // the node Router is just a Ring node. A Flit gets ejected or moves straight forward linkOut = new Link[2]; linkIn = new Link[2]; m_injectSlot_CW = null; m_injectSlot_CCW = null; throttle[ID] = false; starved[ID] = false; starveCounter = 0; m_ringBuf = new WormholeBuffer[2]; for (int i = 0; i < 2; i++) m_ringBuf[i] = new WormholeBuffer(Config.ringBufferSize); } public Router_Node_Buffer(RC_Coord RC_c, Coord c) : base(c) { linkOut = new Link[2]; linkIn = new Link[2]; m_injectSlot_CW = null; m_injectSlot_CCW = null; ejectBuffer = new Queue<Flit> [2]; for (int i = 0; i < 2; i++) ejectBuffer[i] = new Queue<Flit>(); throttle[ID] = false; starved[ID] = false; starveCounter = 0; m_ringBuf = new WormholeBuffer[2]; for (int i = 0; i < 2; i++) m_ringBuf[i] = new WormholeBuffer(Config.ringBufferSize); } // TODO: later on need to check ejection fifo public override bool creditAvailable(Flit f) { return m_ringBuf[f.packet.pktParity].canEnqNewFlit(f); } protected void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit ejectLocal() { // eject locally-destined flit (highest-ranked, if multiple) Flit ret = null; int flitsTryToEject = 0; int bestDir = -1; // Check both directions for (int dir = 0; dir < 2; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.state != Flit.State.Placeholder && linkIn[dir].Out.dest.ID == ID) { ret = linkIn[dir].Out; bestDir = dir; flitsTryToEject ++; } } if (bestDir != -1) linkIn[bestDir].Out = null; Simulator.stats.flitsTryToEject[flitsTryToEject].Add(); #if debug if (ret != null) Console.WriteLine("ejecting flit {0} flitnr {1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound); #endif return ret; } // TODO: Caveat: THIS MIGHT NOT BE NECESSARY. Can put this in // do step. Imagine injeciton slow as part of fifo. // Injection into the ring: // TODO: need to check downstream buffer occupancy: // 1) If eject next node check next node's ejeciton buffer // 2) If some other nodes, check next node's ring buffer // TODO: How do I take care of the case that the next cycle the ring buffer becomes occupied and it also wants // to eject at the same node? // Ans: Since I already send the head, I have to continue sending. // public override bool canInjectFlit(Flit f) { if (throttle[ID]) return false; bool can; // Body flits and tail flits have to follow the head flit // direction since we are using wormhole flow control if (!f.isHeadFlit) { f.parity = f.packet.pktParity; } if (f.parity == 0) { if (m_injectSlot_CW != null) f.timeWaitToInject ++; can = m_injectSlot_CW == null; } else if (f.parity == 1) { if (m_injectSlot_CCW != null) f.timeWaitToInject ++; can = m_injectSlot_CCW == null; } else if (f.parity == -1) { if (m_injectSlot_CW != null && m_injectSlot_CCW != null) f.timeWaitToInject ++; can = (m_injectSlot_CW == null || m_injectSlot_CCW == null); } else throw new Exception("Unkown parity value!"); // Being blocked in the injection queue // TODO: this starvation count seems incorrect here! Because there // is no guarantee on injection of m_injectSlot_CW and // m_injectSlow_CCW since these can just be imagined as a 1-flit // buffer. if (!can) { starveCounter ++; Simulator.stats.injStarvation.Add(); } // TODO: this is for guaranteeing delievery? if (starveCounter == Config.starveThreshold) starved[ID] = true; return can; } public override void InjectFlit(Flit f) { //if (Config.topology != Topology.Mesh && Config.topology != Topology.MeshOfRings && f.parity != -1) // throw new Exception("In Ring based topologies, the parity must be -1"); starveCounter = 0; starved[ID] = false; if (f.parity == 0) { if (m_injectSlot_CW == null) m_injectSlot_CW = f; else throw new Exception("InjectFlit fault: The slot is empty!"); } else if (f.parity == 1) { if (m_injectSlot_CCW == null) m_injectSlot_CCW = f; else throw new Exception("InjectFlit fault: The slot is empty!"); } else { // Preference on which ring to route to. As long as there is // one ring open for injection, there's no correctness issue. int preference = -1; int dest = f.packet.dest.ID; int src = f.packet.src.ID; if (Config.topology == Topology.SingleRing) { if ((dest - src + Config.N) % Config.N < Config.N / 2) preference = 0; else preference = 1; } else if (dest / 4 == src / 4) { if ((dest - src + 4) % 4 < 2) preference = 0; else if ((dest - src + 4) % 4 > 2) preference = 1; } else if (Config.topology == Topology.HR_4drop) { if (ID == 1 || ID == 2 || ID == 5 || ID == 6 || ID == 8 || ID == 11 || ID == 12 || ID == 15 ) preference = 0; else preference = 1; } else if (Config.topology == Topology.HR_8drop || Config.topology == Topology.HR_8_8drop) { if (ID % 2 == 0) preference = 0; else preference = 1; } else if (Config.topology == Topology.HR_8_16drop) { if (dest / 8 == src / 8) { if ((dest - src + 8) % 8 < 4) preference = 0; else preference = 1; } else { if (ID % 2 == 0) preference = 1; else preference = 0; } } if (Config.NoPreference) preference = -1; if (preference == -1) preference = Simulator.rand.Next(2); if (preference == 0) { if (m_injectSlot_CW == null) m_injectSlot_CW = f; else if (m_injectSlot_CCW == null) m_injectSlot_CCW = f; } else if (preference == 1) { if (m_injectSlot_CCW == null) m_injectSlot_CCW = f; else if (m_injectSlot_CW == null) m_injectSlot_CW = f; } else throw new Exception("Unknown preference!"); // Set the direction for the entire packet since we are doing // wormhole flow control in buffered ring if (f.isHeadFlit) { if (m_injectSlot_CW == f) f.packet.pktParity = 0; else if (m_injectSlot_CCW == f) f.packet.pktParity = 1; } } #if debug if (f != null) { if (m_injectSlot_CW == f) Console.WriteLine("Router Inject flit cyc {0} node coord {3} id {4} -> flit id {5} flitNr {1} :: CW pktParity {2}", Simulator.CurrentRound, f.flitNr, f.packet.pktParity, coord, ID, f.packet.ID); else if (m_injectSlot_CCW == f) Console.WriteLine("Router Inject flit cyc {0} node coord {3} id {4} -> flit id {5} flitNr {1} :: CCW pktParity {2}", Simulator.CurrentRound, f.flitNr, f.packet.pktParity, coord, ID, f.packet.ID); } #endif } protected override void _doStep() { // Record timing for (int i = 0; i < 2; i++) { if (linkIn[i].Out != null && Config.N == 16) { Flit f = linkIn[i].Out; if (f.packet.src.ID / 4 == ID / 4) f.timeInTheSourceRing+=1; else if (f.packet.dest.ID / 4 == ID / 4) f.timeInTheDestRing +=1; else f.timeInTheTransitionRing += 1; } } // Ejection to the local node Flit f1 = null, f2 = null; // This is using two ejection buffers, BUT there's only ejection // port to the local PE. if (Config.EjectBufferSize != -1 && Config.RingEjectTrial == -1) { for (int dir =0; dir < 2; dir ++) { if (linkIn[dir].Out != null && linkIn[dir].Out.packet.dest.ID == ID && ejectBuffer[dir].Count < Config.EjectBufferSize) { ejectBuffer[dir].Enqueue(linkIn[dir].Out); linkIn[dir].Out = null; } } int bestdir = -1; for (int dir = 0; dir < 2; dir ++) { // if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Peek().injectionTime < ejectBuffer[bestdir].Peek().injectionTime)) if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Count > ejectBuffer[bestdir].Count)) // if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || Simulator.rand.Next(2) == 1)) bestdir = dir; } if (bestdir != -1) acceptFlit(ejectBuffer[bestdir].Dequeue()); } else { for (int i = 0; i < Config.RingEjectTrial; i++) { Flit eject = ejectLocal(); if (i == 0) f1 = eject; else if (i == 1) f2 = eject; if (eject != null) acceptFlit(eject); } if (f1 != null && f2 != null && f1.packet == f2.packet) Simulator.stats.ejectsFromSamePacket.Add(1); else if (f1 != null && f2 != null) Simulator.stats.ejectsFromSamePacket.Add(0); } // Arbitration and flow control for (int dir = 0; dir < 2; dir++) { // Enqueue into the buffer if (linkIn[dir].Out != null) { #if debug Console.WriteLine("cyc {0} dir {2} node {4} id {5}:: enq {1} flitNr {3}", Simulator.CurrentRound, linkIn[dir].Out.packet.ID, dir, linkIn[dir].Out.flitNr, coord, ID); #endif m_ringBuf[dir].enqueue(linkIn[dir].Out); linkIn[dir].Out = null; Simulator.stats.flitsPassBy.Add(1); } // Arbitrate betwen local flit and buffered flit Flit winner = null; Flit _injSlot = (dir == 0) ? m_injectSlot_CW : m_injectSlot_CCW; Flit _bufHead = m_ringBuf[dir].peek(); #if debug Console.WriteLine("cyc {0} arb: buf_null {1} injslot_null {2}", Simulator.CurrentRound, _bufHead == null, _injSlot == null); #endif if (_injSlot != null && _bufHead == null && m_ringBuf[dir].IsWorm == false) winner = _injSlot; else if (_injSlot == null && _bufHead != null) winner = _bufHead; else if (_injSlot != null && _bufHead != null) { // Priority is always given to flit in the ring buffer, // execpt if the header flit of the local injection // buffer has already been sent downstream. This is to // ensure wormhole flow control if (_injSlot.isHeadFlit && _bufHead.isHeadFlit) winner = _bufHead; else if (_injSlot.isHeadFlit && !_bufHead.isHeadFlit) winner = _bufHead; else if (!_injSlot.isHeadFlit && _bufHead.isHeadFlit) winner = _injSlot; else throw new Exception("Impossible for both flits in ring buffer and injection slot in active state."); } // Check downstream credit, if ring/ejection buffer is available then send it. if (winner != null) { #if debug Console.Write("cyc {0} :: dir {2} node_ID {4} arb winner {1} ishead {3} dest {5}-> ", Simulator.CurrentRound, winner.packet.ID, dir, winner.isHeadFlit, ID, winner.dest.ID); if (winner == m_ringBuf[dir].peek()) Console.WriteLine("winner In ring buffer"); else if (winner == m_injectSlot_CW) Console.WriteLine("winner In inj cw"); else if (winner == m_injectSlot_CCW) Console.WriteLine("winner In inj ccw"); #endif // TODO: not sure why we need to check whether linkOut.in // is empty or not. Double check on this. // Need to check downstream buffer occupancy: // 1) If eject next node check next node's ejeciton buffer // 2) If some other nodes, check next node's ring buffer if (checkDownStreamCredit(winner) && linkOut[dir].In == null) { if (winner == m_ringBuf[dir].peek()) m_ringBuf[dir].dequeue(); else if (winner == m_injectSlot_CW) m_injectSlot_CW = null; else if (winner == m_injectSlot_CCW) m_injectSlot_CCW = null; linkOut[dir].In = winner; Console.WriteLine("inject"); statsInjectFlit(winner); } else { // Being blocked } } } } /* * In order to check downstream ID, we need to know the topology and * whether we should check local ring's or global ring's buffer and * ejection buffer. * * TODO: currently we do not check ejection fifos since we do not have * them. * */ bool checkDownStreamCredit(Flit f) { if (f == null) throw new Exception("Null flit checking credit."); if (Config.topology == Topology.SingleRing) { int _nextNodeID; if (f.packet.pktParity == 0) _nextNodeID = (ID + 1) % Config.N; else _nextNodeID = (ID == 0) ? Config.N-1 : (ID - 1) % Config.N; #if debug Console.WriteLine("cyc {0} flit asking for credit ID {1} flitNr {2} dir {3} nextNodeID {4}", Simulator.CurrentRound, f.packet.ID, f.flitNr, f.packet.pktParity, _nextNodeID); #endif // TODO: assume always successful ejection if (f.dest.ID == _nextNodeID) return true; return Simulator.network.nodeRouters[_nextNodeID].creditAvailable(f); } else if (Config.topology == Topology.HR_4drop) { int subNodeID = ID % 4; int localRingID = ID / 4; int _nextNodeID, _nextBridgeID; // Determining if there's a bridge router between current // node and the next node if (f.packet.pktParity == 0) { _nextNodeID = (subNodeID + 1) % 4 + localRingID * 4; _nextBridgeID = Array.IndexOf(Simulator.network.GetCWnext, _nextNodeID); #if debug2 Console.WriteLine("Bridge search cyc {0} CW : bridge index {1}", Simulator.CurrentRound, _nextBridgeID); #endif } else { _nextNodeID = (subNodeID == 0) ? 3 : subNodeID - 1; _nextNodeID += localRingID * 4; _nextBridgeID = Array.IndexOf(Simulator.network.GetCCWnext, _nextNodeID); #if debug2 Console.WriteLine("Bridge search cyc {0} CW : bridge index {1}", Simulator.CurrentRound, _nextBridgeID); #endif } #if debug Console.WriteLine("cyc {0} flit asking for credit ID {1} flitNr {2} dir {3} nextNodeID {4} nextBridge {5}", Simulator.CurrentRound, f.packet.ID, f.flitNr, f.packet.pktParity, _nextNodeID, _nextBridgeID); #endif // If bridge is there, check if we are ejecting to bridge if (_nextBridgeID != -1) { if (Simulator.network.bridgeRouters[_nextBridgeID].productive(f, Local) == true) { return Simulator.network.bridgeRouters[_nextBridgeID].creditAvailable(f); } } if (f.dest.ID == _nextNodeID) return true; return Simulator.network.nodeRouters[_nextNodeID].creditAvailable(f); } else throw new Exception("Not Supported"); } } public class Router_Switch_Buffer : Router { int bufferDepth = 1; public static int[,] bufferCurD = new int[Config.N,4]; Flit[,] buffers;// = new Flit[4,32]; public Router_Switch_Buffer(int ID) : base() { coord.ID = ID; enable = true; m_n = null; buffers = new Flit[4,32]; // actual buffer depth is decided by bufferDepth for (int i = 0; i < 4; i++) for (int n = 0; n < bufferDepth; n++) buffers[i, n] = null; } int Local_CW = 0; int Local_CCW = 1; int GL_CW = 2; int GL_CCW = 3; // different routing algorithms can be implemented by changing this function private bool productiveRouter(Flit f, int port) { // Console.WriteLine("Net/RouterRing.cs"); int RingID = ID / 4; if (Config.HR_NoBias) { if ((port == Local_CW || port == Local_CCW) && RingID == f.packet.dest.ID / 4) return false; else if ((port == Local_CW || port == Local_CCW) && RingID != f.packet.dest.ID / 4) return true; else if ((port == GL_CW || port == GL_CCW) && RingID == f.packet.dest.ID / 4) return true; else if ((port == GL_CW || port == GL_CCW) && RingID != f.packet.dest.ID / 4) return false; else throw new Exception("Unknown port of switchRouter"); } else if (Config.HR_SimpleBias) { if ((port == Local_CW || port == Local_CCW) && RingID == f.packet.dest.ID / 4) return false; else if ((port == Local_CW || port == Local_CCW) && RingID != f.packet.dest.ID / 4) // if (RingID + f.packet.dest.ID / 4 == 3) //diagonal. can always inject return true; /* else if (RingID == 0 && destID == 1) return ID == 2 || ID == 1; else if (RingID == 0 && destID == 2) return ID == 3 || ID == 0; else if (RingID == 1 && destID == 0) return ID == 4 || ID == 5; else if (RingID == 1 && destID == 3) return ID == 6 || ID == 7; else if (RingID == 2 && destID == 0) return ID == 8 || ID == 9; else if (RingID == 2 && destID == 3) return ID == 10 || ID == 11; else if (RingID == 3 && destID == 1) return ID == 13 || ID == 14; else if (RingID == 3 && destID == 2) return ID == 12 || ID == 15; else throw new Exception("Unknown src and dest in Hierarchical Ring");*/ else if ((port == GL_CW || port == GL_CCW) && RingID == f.packet.dest.ID / 4) return true; else if ((port == GL_CW || port == GL_CCW) && RingID != f.packet.dest.ID / 4) return false; else throw new Exception("Unknown port of switchRouter"); } else throw new Exception("Unknow Routing Algorithm for Hierarchical Ring"); } protected override void _doStep() { switchRouterStats(); // consider 4 input ports seperately. If not productive, keep circling if (!enable) return; /* if (ID == 3) { if (linkIn[0].Out != null && linkIn[0].Out.packet.dest.ID == 11) Console.WriteLine("parity : {0}, src:{1}", linkIn[0].Out.parity, linkIn[0].Out.packet.src.ID); }*/ for (int dir = 0; dir < 4; dir ++) { int i; for (i = 0; i < bufferDepth; i++) if (buffers[dir, i] == null) break; //Console.WriteLine("linkIn[dir] == null:{0},ID:{1}, dir:{2}", linkIn[dir] == null, ID, dir); bool productive = (linkIn[dir].Out != null)? productiveRouter(linkIn[dir].Out, dir) : false; //Console.WriteLine("productive: {0}", productive); if (linkIn[dir].Out != null && (!productive || i == bufferDepth)) // nonproductive or the buffer is full : bypass the router { linkOut[dir].In = linkIn[dir].Out; Console.WriteLine("transit"); linkIn[dir].Out = null; } else if (linkIn[dir].Out != null) //productive direction and the buffer has empty space, add into buffer { int k; for (k = 0; k < bufferDepth; k++) { if (buffers[dir, k] == null) { buffers[dir, k] = linkIn[dir].Out; linkIn[dir].Out = null; break; } //Console.WriteLine("{0}", k); } if (k == bufferDepth) throw new Exception("The buffer is full!!"); } } // if there're extra slots in the same direction network, inject from the buffer for (int dir = 0; dir < 4; dir ++) { if (linkOut[dir].In == null) // extra slot available { int posdir = (dir+2) % 4; if (buffers[posdir, 0] != null) { linkOut[dir].In = buffers[posdir, 0]; buffers[posdir, 0] = null; } } } // if the productive direction with the same parity is not available. The direction with the other parity is also fine for (int dir = 0; dir < 4; dir ++) { int crossdir = 3 - dir; if (linkOut[dir].In == null) // extra slot available { if (buffers[crossdir, 0] != null) { // for HR_SimpleBias is the dir is not a local ring, can't change rotating direction if (Config.HR_SimpleBias && (dir == GL_CW || dir == GL_CCW)) continue; linkOut[dir].In = buffers[crossdir, 0]; Console.WriteLine("transit"); buffers[crossdir, 0] = null; } } } if (Config.HR_NoBuffer) { for (int dir = 0; dir < 4; dir ++) { if (buffers[dir, 0] != null) { if (linkOut[dir].In != null) throw new Exception("The outlet of the buffer is blocked"); linkOut[dir].In = buffers[dir, 0]; buffers[dir, 0] = null; } } } // move all the flits in the buffer if the head flit is null for (int dir = 0; dir < 4; dir ++) { if (buffers[dir, 0] == null) { for (int i = 0; i < bufferDepth - 1; i++) buffers[dir, i] = buffers[dir, i + 1]; buffers[dir, bufferDepth-1] = null; } } for (int dir = 0; dir < 4; dir ++) { int i; for (i = 0; i < bufferDepth; i++) if (buffers[dir, i] == null) break; bufferCurD[ID,dir] = i; } } void switchRouterStats() { for (int dir = 0; dir < 4; dir ++) { Flit f = linkIn[dir].Out; if (f != null && (dir == Local_CW || dir == Local_CCW)) { if (f.packet.src.ID / 4 == ID / 4) f.timeInTheSourceRing ++; else if (f.packet.dest.ID / 4 == ID / 4) f.timeInTheDestRing ++; } else if (f != null && (dir == GL_CW || dir == GL_CCW)) f.timeInGR += 2; } return; } public override bool canInjectFlit(Flit f) { return false; } public override void InjectFlit(Flit f) { return; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Build.BackEnd; using System.IO; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Tests for the NodePacketTranslators /// </summary> public class BinaryTranslator_Tests { /// <summary> /// Tests the SerializationMode property /// </summary> [Fact] public void TestSerializationMode() { MemoryStream stream = new MemoryStream(); ITranslator translator = BinaryTranslator.GetReadTranslator(stream, null); Assert.Equal(TranslationDirection.ReadFromStream, translator.Mode); translator = BinaryTranslator.GetWriteTranslator(stream); Assert.Equal(TranslationDirection.WriteToStream, translator.Mode); } /// <summary> /// Tests serializing bools. /// </summary> [Fact] public void TestSerializeBool() { HelperTestSimpleType(false, true); HelperTestSimpleType(true, false); } /// <summary> /// Tests serializing bytes. /// </summary> [Fact] public void TestSerializeByte() { byte val = 0x55; HelperTestSimpleType((byte)0, val); HelperTestSimpleType(val, (byte)0); } /// <summary> /// Tests serializing shorts. /// </summary> [Fact] public void TestSerializeShort() { short val = 0x55AA; HelperTestSimpleType((short)0, val); HelperTestSimpleType(val, (short)0); } /// <summary> /// Tests serializing longs. /// </summary> [Fact] public void TestSerializeLong() { long val = 0x55AABBCCDDEE; HelperTestSimpleType((long)0, val); HelperTestSimpleType(val, (long)0); } /// <summary> /// Tests serializing doubles. /// </summary> [Fact] public void TestSerializeDouble() { double val = 3.1416; HelperTestSimpleType((double)0, val); HelperTestSimpleType(val, (double)0); } /// <summary> /// Tests serializing TimeSpan. /// </summary> [Fact] public void TestSerializeTimeSpan() { TimeSpan val = TimeSpan.FromMilliseconds(123); HelperTestSimpleType(TimeSpan.Zero, val); HelperTestSimpleType(val, TimeSpan.Zero); } /// <summary> /// Tests serializing ints. /// </summary> [Fact] public void TestSerializeInt() { int val = 0x55AA55AA; HelperTestSimpleType((int)0, val); HelperTestSimpleType(val, (int)0); } /// <summary> /// Tests serializing strings. /// </summary> [Fact] public void TestSerializeString() { HelperTestSimpleType("foo", null); HelperTestSimpleType("", null); HelperTestSimpleType(null, null); } /// <summary> /// Tests serializing string arrays. /// </summary> [Fact] public void TestSerializeStringArray() { HelperTestArray(new string[] { }, StringComparer.Ordinal); HelperTestArray(new string[] { "foo", "bar" }, StringComparer.Ordinal); HelperTestArray(null, StringComparer.Ordinal); } /// <summary> /// Tests serializing string arrays. /// </summary> [Fact] public void TestSerializeStringList() { HelperTestList(new List<string>(), StringComparer.Ordinal); List<string> twoItems = new List<string>(2); twoItems.Add("foo"); twoItems.Add("bar"); HelperTestList(twoItems, StringComparer.Ordinal); HelperTestList(null, StringComparer.Ordinal); } /// <summary> /// Tests serializing DateTimes. /// </summary> [Fact] public void TestSerializeDateTime() { HelperTestSimpleType(new DateTime(), DateTime.Now); HelperTestSimpleType(DateTime.Now, new DateTime()); } /// <summary> /// Tests serializing enums. /// </summary> [Fact] public void TestSerializeEnum() { TranslationDirection value = TranslationDirection.ReadFromStream; TranslationHelpers.GetWriteTranslator().TranslateEnum(ref value, (int)value); TranslationDirection deserializedValue = TranslationDirection.WriteToStream; TranslationHelpers.GetReadTranslator().TranslateEnum(ref deserializedValue, (int)deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing using the DotNet serializer. /// </summary> [Fact] public void TestSerializeDotNet() { ArgumentNullException value = new ArgumentNullException("The argument was null", new InsufficientMemoryException()); TranslationHelpers.GetWriteTranslator().TranslateDotNet(ref value); ArgumentNullException deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDotNet(ref deserializedValue); Assert.True(TranslationHelpers.CompareExceptions(value, deserializedValue)); } /// <summary> /// Tests serializing using the DotNet serializer passing in null. /// </summary> [Fact] public void TestSerializeDotNetNull() { ArgumentNullException value = null; TranslationHelpers.GetWriteTranslator().TranslateDotNet(ref value); ArgumentNullException deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDotNet(ref deserializedValue); Assert.True(TranslationHelpers.CompareExceptions(value, deserializedValue)); } /// <summary> /// Tests serializing an object with a default constructor. /// </summary> [Fact] public void TestSerializeINodePacketSerializable() { DerivedClass value = new DerivedClass(1, 2); TranslationHelpers.GetWriteTranslator().Translate(ref value); DerivedClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value.BaseValue, deserializedValue.BaseValue); Assert.Equal(value.DerivedValue, deserializedValue.DerivedValue); } /// <summary> /// Tests serializing an object with a default constructor passed as null. /// </summary> [Fact] public void TestSerializeINodePacketSerializableNull() { DerivedClass value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value); DerivedClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing an object requiring a factory to construct. /// </summary> [Fact] public void TestSerializeWithFactory() { BaseClass value = new BaseClass(1); TranslationHelpers.GetWriteTranslator().Translate(ref value, BaseClass.FactoryForDeserialization); BaseClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value.BaseValue, deserializedValue.BaseValue); } /// <summary> /// Tests serializing an object requiring a factory to construct, passing null for the value. /// </summary> [Fact] public void TestSerializeWithFactoryNull() { BaseClass value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value, BaseClass.FactoryForDeserialization); BaseClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing an array of objects with default constructors. /// </summary> [Fact] public void TestSerializeArray() { DerivedClass[] value = new DerivedClass[] { new DerivedClass(1, 2), new DerivedClass(3, 4) }; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value); DerivedClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, DerivedClass.Comparer)); } /// <summary> /// Tests serializing an array of objects with default constructors, passing null for the array. /// </summary> [Fact] public void TestSerializeArrayNull() { DerivedClass[] value = null; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value); DerivedClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, DerivedClass.Comparer)); } /// <summary> /// Tests serializing an array of objects requiring factories to construct. /// </summary> [Fact] public void TestSerializeArrayWithFactory() { BaseClass[] value = new BaseClass[] { new BaseClass(1), new BaseClass(2) }; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value, BaseClass.FactoryForDeserialization); BaseClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, BaseClass.Comparer)); } /// <summary> /// Tests serializing an array of objects requiring factories to construct, passing null for the array. /// </summary> [Fact] public void TestSerializeArrayWithFactoryNull() { BaseClass[] value = null; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value, BaseClass.FactoryForDeserialization); BaseClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, BaseClass.Comparer)); } /// <summary> /// Tests serializing a dictionary of { string, string } /// </summary> [Fact] public void TestSerializeDictionaryStringString() { Dictionary<string, string> value = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); value["foo"] = "bar"; value["alpha"] = "omega"; TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase); Dictionary<string, string> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase); Assert.Equal(value.Count, deserializedValue.Count); Assert.Equal(value["foo"], deserializedValue["foo"]); Assert.Equal(value["alpha"], deserializedValue["alpha"]); Assert.Equal(value["FOO"], deserializedValue["FOO"]); } /// <summary> /// Tests serializing a dictionary of { string, string }, passing null. /// </summary> [Fact] public void TestSerializeDictionaryStringStringNull() { Dictionary<string, string> value = null; TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase); Dictionary<string, string> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// requires a KeyComparer initializer. /// </summary> [Fact] public void TestSerializeDictionaryStringT() { Dictionary<string, BaseClass> value = new Dictionary<string, BaseClass>(StringComparer.OrdinalIgnoreCase); value["foo"] = new BaseClass(1); value["alpha"] = new BaseClass(2); TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Assert.Equal(value.Count, deserializedValue.Count); Assert.Equal(0, BaseClass.Comparer.Compare(value["foo"], deserializedValue["foo"])); Assert.Equal(0, BaseClass.Comparer.Compare(value["alpha"], deserializedValue["alpha"])); Assert.Equal(0, BaseClass.Comparer.Compare(value["FOO"], deserializedValue["FOO"])); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// requires a KeyComparer initializer, passing null for the dictionary. /// </summary> [Fact] public void TestSerializeDictionaryStringTNull() { Dictionary<string, BaseClass> value = null; TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// has a default constructor. /// </summary> [Fact] public void TestSerializeDictionaryStringTNoComparer() { Dictionary<string, BaseClass> value = new Dictionary<string, BaseClass>(); value["foo"] = new BaseClass(1); value["alpha"] = new BaseClass(2); TranslationHelpers.GetWriteTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref value, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value.Count, deserializedValue.Count); Assert.Equal(0, BaseClass.Comparer.Compare(value["foo"], deserializedValue["foo"])); Assert.Equal(0, BaseClass.Comparer.Compare(value["alpha"], deserializedValue["alpha"])); Assert.False(deserializedValue.ContainsKey("FOO")); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// has a default constructor, passing null for the dictionary. /// </summary> [Fact] public void TestSerializeDictionaryStringTNoComparerNull() { Dictionary<string, BaseClass> value = null; TranslationHelpers.GetWriteTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref value, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for bool serialization. /// </summary> private void HelperTestSimpleType(bool initialValue, bool deserializedInitialValue) { bool value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); bool deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for long serialization. /// </summary> private void HelperTestSimpleType(long initialValue, long deserializedInitialValue) { long value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); long deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for double serialization. /// </summary> private void HelperTestSimpleType(double initialValue, double deserializedInitialValue) { double value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); double deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for TimeSpan serialization. /// </summary> private void HelperTestSimpleType(TimeSpan initialValue, TimeSpan deserializedInitialValue) { TimeSpan value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); TimeSpan deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for byte serialization. /// </summary> private void HelperTestSimpleType(byte initialValue, byte deserializedInitialValue) { byte value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); byte deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for short serialization. /// </summary> private void HelperTestSimpleType(short initialValue, short deserializedInitialValue) { short value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); short deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for int serialization. /// </summary> private void HelperTestSimpleType(int initialValue, int deserializedInitialValue) { int value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); int deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for string serialization. /// </summary> private void HelperTestSimpleType(string initialValue, string deserializedInitialValue) { string value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); string deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for DateTime serialization. /// </summary> private void HelperTestSimpleType(DateTime initialValue, DateTime deserializedInitialValue) { DateTime value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); DateTime deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for array serialization. /// </summary> private void HelperTestArray(string[] initialValue, IComparer<string> comparer) { string[] value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); string[] deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, comparer)); } /// <summary> /// Helper for list serialization. /// </summary> private void HelperTestList(List<string> initialValue, IComparer<string> comparer) { List<string> value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); List<string> deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, comparer)); } /// <summary> /// Base class for testing /// </summary> private class BaseClass : ITranslatable { /// <summary> /// A field. /// </summary> private int _baseValue; /// <summary> /// Constructor with value. /// </summary> public BaseClass(int val) { _baseValue = val; } /// <summary> /// Constructor /// </summary> protected BaseClass() { } /// <summary> /// Gets a comparer. /// </summary> static public IComparer<BaseClass> Comparer { get { return new BaseClassComparer(); } } /// <summary> /// Gets the value. /// </summary> public int BaseValue { get { return _baseValue; } } #region INodePacketTranslatable Members /// <summary> /// Factory for serialization. /// </summary> public static BaseClass FactoryForDeserialization(ITranslator translator) { BaseClass packet = new BaseClass(); packet.Translate(translator); return packet; } /// <summary> /// Serializes the class. /// </summary> public virtual void Translate(ITranslator translator) { translator.Translate(ref _baseValue); } #endregion /// <summary> /// Comparer for BaseClass. /// </summary> private class BaseClassComparer : IComparer<BaseClass> { /// <summary> /// Constructor. /// </summary> public BaseClassComparer() { } #region IComparer<BaseClass> Members /// <summary> /// Compare two BaseClass objects. /// </summary> public int Compare(BaseClass x, BaseClass y) { if (x._baseValue == y._baseValue) { return 0; } return -1; } #endregion } } /// <summary> /// Derived class for testing. /// </summary> private class DerivedClass : BaseClass { /// <summary> /// A field. /// </summary> private int _derivedValue; /// <summary> /// Default constructor. /// </summary> public DerivedClass() { } /// <summary> /// Constructor taking two values. /// </summary> public DerivedClass(int derivedValue, int baseValue) : base(baseValue) { _derivedValue = derivedValue; } /// <summary> /// Gets a comparer. /// </summary> static new public IComparer<DerivedClass> Comparer { get { return new DerivedClassComparer(); } } /// <summary> /// Returns the value. /// </summary> public int DerivedValue { get { return _derivedValue; } } #region INodePacketTranslatable Members /// <summary> /// Serializes the class. /// </summary> public override void Translate(ITranslator translator) { base.Translate(translator); translator.Translate(ref _derivedValue); } #endregion /// <summary> /// Comparer for DerivedClass. /// </summary> private class DerivedClassComparer : IComparer<DerivedClass> { /// <summary> /// Constructor /// </summary> public DerivedClassComparer() { } #region IComparer<DerivedClass> Members /// <summary> /// Compares two DerivedClass objects. /// </summary> public int Compare(DerivedClass x, DerivedClass y) { if (x._derivedValue == y._derivedValue) { return BaseClass.Comparer.Compare(x, y); } return -1; } #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. /*============================================================ ** ** ** ** Implementation details of CLR Contracts. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool _assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { if (_assertingMustUseRewriter) System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); _assertingMustUseRewriter = true; // For better diagnostics, report which assembly is at fault. Walk up stack and // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); Assembly probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; if (caller != thisAssembly) { probablyNotRewritten = caller; break; } } if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; String simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); _assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endregion FailureBehavior } public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS #endif public void SetUnwind() { _unwind = true; } } [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { private readonly ContractFailureKind _Kind; private readonly string _UserMessage; private readonly string _Condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _Kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _UserMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _Condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; _Kind = kind; _UserMessage = userMessage; _Condition = condition; } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent; private static readonly Object lockObject = new Object(); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); lock (lockObject) { contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS #endif remove { lock (lockObject) { contractFailedEvent -= value; } } } /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeners deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... ContractFailedEventArgs eventArgs = null; // In case of OOM. #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent; if (contractFailedEventLocal != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } } finally { if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } // May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. // Optional info like string for collapsed text vs. expanded text. String windowTitle = SR.GetResourceString(GetResourceNameForFailure(kind)); const int numStackFramesToSkip = 2; // To make stack traces easier to read System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetResourceNameForFailure(ContractFailureKind failureKind) { String resourceName = null; switch (failureKind) { case ContractFailureKind.Assert: resourceName = "AssertionFailed"; break; case ContractFailureKind.Assume: resourceName = "AssumptionFailed"; break; case ContractFailureKind.Precondition: resourceName = "PreconditionFailed"; break; case ContractFailureKind.Postcondition: resourceName = "PostconditionFailed"; break; case ContractFailureKind.Invariant: resourceName = "InvariantFailed"; break; case ContractFailureKind.PostconditionOnException: resourceName = "PostconditionOnExceptionFailed"; break; default: Contract.Assume(false, "Unreachable code"); resourceName = "AssumptionFailed"; break; } return resourceName; } #if FEATURE_RELIABILITY_CONTRACTS #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { String resourceName = GetResourceNameForFailure(failureKind); // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage; if (!String.IsNullOrEmpty(conditionText)) { resourceName += "_Cnd"; failureMessage = SR.Format(SR.GetResourceString(resourceName), conditionText); } else { failureMessage = SR.GetResourceString(resourceName); } // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } } } // namespace System.Runtime.CompilerServices
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.ObjectModel; using System.Management.Automation.Language; using System.Diagnostics; using System.Management.Automation.Host; using System.Management.Automation.Internal.Host; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Runspaces; namespace System.Management.Automation.Internal { /// <summary> /// Defines members used by Cmdlets. /// All Cmdlets must derive from /// <see cref="System.Management.Automation.Cmdlet"/>. /// </summary> /// <remarks> /// Only use <see cref="System.Management.Automation.Internal.InternalCommand"/> /// as a subclass of /// <see cref="System.Management.Automation.Cmdlet"/>. /// Do not attempt to create instances of /// <see cref="System.Management.Automation.Internal.InternalCommand"/> /// independently, or to derive other classes than /// <see cref="System.Management.Automation.Cmdlet"/> from /// <see cref="System.Management.Automation.Internal.InternalCommand"/>. /// </remarks> /// <seealso cref="System.Management.Automation.Cmdlet"/> /// <!-- /// These are the Cmdlet members which are also used by other /// non-public command types. /// /// Ideally this would be an internal class, but C# does not support /// public classes deriving from internal classes. /// --> [DebuggerDisplay("Command = {_commandInfo}")] public abstract class InternalCommand { #region private_members internal ICommandRuntime commandRuntime; #endregion private_members #region ctor /// <summary> /// Initializes the new instance of Cmdlet class. /// </summary> /// <remarks> /// The only constructor is internal, so outside users cannot create /// an instance of this class. /// </remarks> internal InternalCommand() { this.CommandInfo = null; } #endregion ctor #region internal_members /// <summary> /// Allows you to access the calling token for this command invocation... /// </summary> /// <value></value> internal IScriptExtent InvocationExtent { get; set; } private InvocationInfo _myInvocation = null; /// <summary> /// Return the invocation data object for this command. /// </summary> /// <value>The invocation object for this command.</value> internal InvocationInfo MyInvocation { get { return _myInvocation ?? (_myInvocation = new InvocationInfo(this)); } } /// <summary> /// Represents the current pipeline object under consideration. /// </summary> internal PSObject currentObjectInPipeline = AutomationNull.Value; /// <summary> /// Gets or sets the current pipeline object under consideration. /// </summary> internal PSObject CurrentPipelineObject { get { return currentObjectInPipeline; } set { currentObjectInPipeline = value; } } /// <summary> /// Internal helper. Interface that should be used for interaction with host. /// </summary> internal PSHost PSHostInternal { get { return _CBhost; } } private PSHost _CBhost; /// <summary> /// Internal helper to get to SessionState. /// </summary> internal SessionState InternalState { get { return _state; } } private SessionState _state; /// <summary> /// Internal helper. Indicates whether stop has been requested on this command. /// </summary> internal bool IsStopping { get { MshCommandRuntime mcr = this.commandRuntime as MshCommandRuntime; return (mcr != null && mcr.IsStopping); } } /// <summary> /// The information about the command. /// </summary> private CommandInfo _commandInfo; /// <summary> /// Gets or sets the command information for the command. /// </summary> internal CommandInfo CommandInfo { get { return _commandInfo; } set { _commandInfo = value; } } #endregion internal_members #region public_properties /// <summary> /// Gets or sets the execution context. /// </summary> /// <exception cref="System.ArgumentNullException"> /// may not be set to null /// </exception> internal ExecutionContext Context { get { return _context; } set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Context"); } _context = value; Diagnostics.Assert(_context.EngineHostInterface is InternalHost, "context.EngineHostInterface is not an InternalHost"); _CBhost = (InternalHost)_context.EngineHostInterface; // Construct the session state API set from the new context _state = new SessionState(_context.EngineSessionState); } } private ExecutionContext _context; /// <summary> /// This property tells you if you were being invoked inside the runspace or /// if it was an external request. /// </summary> public CommandOrigin CommandOrigin { get { return CommandOriginInternal; } } internal CommandOrigin CommandOriginInternal = CommandOrigin.Internal; #endregion public_properties #region Override /// <summary> /// When overridden in the derived class, performs initialization /// of command execution. /// Default implementation in the base class just returns. /// </summary> internal virtual void DoBeginProcessing() { } /// <summary> /// When overridden in the derived class, performs execution /// of the command. /// </summary> internal virtual void DoProcessRecord() { } /// <summary> /// When overridden in the derived class, performs clean-up /// after the command execution. /// Default implementation in the base class just returns. /// </summary> internal virtual void DoEndProcessing() { } /// <summary> /// When overridden in the derived class, interrupts currently /// running code within the command. It should interrupt BeginProcessing, /// ProcessRecord, and EndProcessing. /// Default implementation in the base class just returns. /// </summary> internal virtual void DoStopProcessing() { } #endregion Override /// <summary> /// Throws if the pipeline is stopping. /// </summary> /// <exception cref="System.Management.Automation.PipelineStoppedException"></exception> internal void ThrowIfStopping() { if (IsStopping) throw new PipelineStoppedException(); } #region Dispose /// <summary> /// IDisposable implementation /// When the command is complete, release the associated members. /// </summary> /// <remarks> /// Using InternalDispose instead of Dispose pattern because this /// interface was shipped in PowerShell V1 and 3rd cmdlets indirectly /// derive from this interface. If we depend on Dispose() and 3rd /// party cmdlets do not call base.Dispose (which is the case), we /// will still end up having this leak. /// </remarks> internal void InternalDispose(bool isDisposing) { _myInvocation = null; _state = null; _commandInfo = null; _context = null; } #endregion } } namespace System.Management.Automation { #region ActionPreference /// <summary> /// Defines the Action Preference options. These options determine /// what will happen when a particular type of event occurs. /// For example, setting shell variable ErrorActionPreference to "Stop" /// will cause the command to stop when an otherwise non-terminating /// error occurs. /// </summary> public enum ActionPreference { /// <summary>Ignore this event and continue</summary> SilentlyContinue, /// <summary>Stop the command</summary> Stop, /// <summary>Handle this event as normal and continue</summary> Continue, /// <summary>Ask whether to stop or continue</summary> Inquire, /// <summary>Ignore the event completely (not even logging it to the target stream)</summary> Ignore, /// <summary>Suspend the command for further diagnosis. Supported only for workflows.</summary> Suspend, } #endregion ActionPreference #region ConfirmImpact /// <summary> /// Defines the ConfirmImpact levels. These levels describe /// the "destructiveness" of an action, and thus the degree of /// important that the user confirm the action. /// For example, setting the read-only flag on a file might be Low, /// and reformatting a disk might be High. /// These levels are also used in $ConfirmPreference to describe /// which operations should be confirmed. Operations with ConfirmImpact /// equal to or greater than $ConfirmPreference are confirmed. /// Operations with ConfirmImpact.None are never confirmed, and /// no operations are confirmed when $ConfirmPreference is ConfirmImpact.None /// (except when explicitly requested with -Confirm). /// </summary> public enum ConfirmImpact { /// <summary>There is never any need to confirm this action.</summary> None, /// <summary> /// This action only needs to be confirmed when the /// user has requested that low-impact changes must be confirmed. /// </summary> Low, /// <summary> /// This action should be confirmed in most scenarios where /// confirmation is requested. /// </summary> Medium, /// <summary> /// This action is potentially highly "destructive" and should be /// confirmed by default unless otherwise specified. /// </summary> High, } #endregion ConfirmImpact /// <summary> /// Defines members and overrides used by Cmdlets. /// All Cmdlets must derive from <see cref="System.Management.Automation.Cmdlet"/>. /// </summary> /// <remarks> /// There are two ways to create a Cmdlet: by deriving from the Cmdlet base class, and by /// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by /// which users create their own Cmdlets. Extending this class provides support for the most /// common functionality, including object output and record processing. /// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, /// access to the host, or information about the current Cmdlet Providers,) then you should instead /// derive from the PSCmdlet base class. /// The public members defined by the PSCmdlet class are not designed to be overridden; instead, they /// provided access to different aspects of the MSH runtime. /// In both cases, users should first develop and implement an object model to accomplish their /// task, extending the Cmdlet or PSCmdlet classes only as a thin management layer. /// </remarks> /// <seealso cref="System.Management.Automation.Internal.InternalCommand"/> public abstract partial class PSCmdlet : Cmdlet { #region private_members private ProviderIntrinsics _invokeProvider = null; #endregion private_members #region public_properties /// <summary> /// Gets the host interaction APIs. /// </summary> public PSHost Host { get { using (PSTransactionManager.GetEngineProtectionScope()) { return PSHostInternal; } } } /// <summary> /// Gets the instance of session state for the current runspace. /// </summary> public SessionState SessionState { get { using (PSTransactionManager.GetEngineProtectionScope()) { return this.InternalState; } } } /// <summary> /// Gets the event manager for the current runspace. /// </summary> public PSEventManager Events { get { using (PSTransactionManager.GetEngineProtectionScope()) { return this.Context.Events; } } } /// <summary> /// Repository for jobs. /// </summary> public JobRepository JobRepository { get { using (PSTransactionManager.GetEngineProtectionScope()) { return ((LocalRunspace)this.Context.CurrentRunspace).JobRepository; } } } /// <summary> /// Manager for JobSourceAdapters registered. /// </summary> public JobManager JobManager { get { using (PSTransactionManager.GetEngineProtectionScope()) { return ((LocalRunspace)this.Context.CurrentRunspace).JobManager; } } } /// <summary> /// Repository for runspaces. /// </summary> internal RunspaceRepository RunspaceRepository { get { return ((LocalRunspace)this.Context.CurrentRunspace).RunspaceRepository; } } /// <summary> /// Gets the instance of the provider interface APIs for the current runspace. /// </summary> public ProviderIntrinsics InvokeProvider { get { using (PSTransactionManager.GetEngineProtectionScope()) { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } } } #region Provider wrappers /// <Content contentref="System.Management.Automation.PathIntrinsics.CurrentProviderLocation" /> public PathInfo CurrentProviderLocation(string providerId) { using (PSTransactionManager.GetEngineProtectionScope()) { if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); } PathInfo result = SessionState.Path.CurrentProviderLocation(providerId); Diagnostics.Assert(result != null, "DataStoreAdapterCollection.GetNamespaceCurrentLocation() should " + "throw an exception, not return null"); return result; } } /// <Content contentref="System.Management.Automation.PathIntrinsics.GetUnresolvedProviderPathFromPSPath" /> public string GetUnresolvedProviderPathFromPSPath(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); } } /// <Content contentref="System.Management.Automation.PathIntrinsics.GetResolvedProviderPathFromPSPath" /> public Collection<string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider) { using (PSTransactionManager.GetEngineProtectionScope()) { return SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); } } #endregion Provider wrappers #endregion internal_members #region ctor /// <summary> /// Initializes the new instance of PSCmdlet class. /// </summary> /// <remarks> /// Only subclasses of <see cref="System.Management.Automation.Cmdlet"/> /// can be created. /// </remarks> protected PSCmdlet() { } #endregion ctor #region public_methods #region PSVariable APIs /// <Content contentref="System.Management.Automation.VariableIntrinsics.GetValue" /> public object GetVariableValue(string name) { using (PSTransactionManager.GetEngineProtectionScope()) { return this.SessionState.PSVariable.GetValue(name); } } /// <Content contentref="System.Management.Automation.VariableIntrinsics.GetValue" /> public object GetVariableValue(string name, object defaultValue) { using (PSTransactionManager.GetEngineProtectionScope()) { return this.SessionState.PSVariable.GetValue(name, defaultValue); } } #endregion PSVariable APIs #region Parameter methods #endregion Parameter methods #endregion public_methods } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Collections; using System.Reflection; using System.ComponentModel; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using System.Globalization; using System.Linq; using Newtonsoft.Json.Linq; using System.Collections.ObjectModel; namespace Newtonsoft.Json { /// <summary> /// Serializes and deserializes objects into and from the Json format. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into Json. /// </summary> public class JsonSerializer { #region Properties private ReferenceLoopHandling _referenceLoopHandling; private MissingMemberHandling _missingMemberHandling; private ObjectCreationHandling _objectCreationHandling; private NullValueHandling _nullValueHandling; private DefaultValueHandling _defaultValueHandling; private int _level; private JsonConverterCollection _converters; private IMappingResolver _mappingResolver; /// <summary> /// Get or set how reference loops (e.g. a class referencing itself) is handled. /// </summary> public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) throw new ArgumentOutOfRangeException("value"); _referenceLoopHandling = value; } } /// <summary> /// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. /// </summary> public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) throw new ArgumentOutOfRangeException("value"); _missingMemberHandling = value; } } /// <summary> /// Get or set how null values are handled during serialization and deserialization. /// </summary> public NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) throw new ArgumentOutOfRangeException("value"); _nullValueHandling = value; } } /// <summary> /// Get or set how null default are handled during serialization and deserialization. /// </summary> public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.Ignore) throw new ArgumentOutOfRangeException("value"); _defaultValueHandling = value; } } /// <summary> /// Gets or sets how objects are created during deserialization. /// </summary> /// <value>The object creation handling.</value> public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) throw new ArgumentOutOfRangeException("value"); _objectCreationHandling = value; } } /// <summary> /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization. /// </summary> /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value> public JsonConverterCollection Converters { get { if (_converters == null) _converters = new JsonConverterCollection(); return _converters; } } public IMappingResolver MappingResolver { get { return _mappingResolver; } set { _mappingResolver = value; } } #endregion /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/> objects. /// </summary> /// <param name="settings">The settings.</param> /// <returns></returns> public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer jsonSerializer = new JsonSerializer(); if (settings != null) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) jsonSerializer.Converters.AddRange(settings.Converters); jsonSerializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; jsonSerializer.MissingMemberHandling = settings.MissingMemberHandling; jsonSerializer.ObjectCreationHandling = settings.ObjectCreationHandling; jsonSerializer.NullValueHandling = settings.NullValueHandling; jsonSerializer.DefaultValueHandling = settings.DefaultValueHandling; jsonSerializer.MappingResolver = settings.MappingResolver; } return jsonSerializer; } #region Deserialize /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the Json structure to deserialize.</param> /// <returns>The <see cref="Object"/> being deserialized.</returns> public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(JsonReader reader, Type objectType) { if (reader == null) throw new ArgumentNullException("reader"); if (!reader.Read()) return null; if (objectType != null) return CreateObject(reader, objectType, null, null); else return CreateJToken(reader); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="StringReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="TextReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } private JToken CreateJToken(JsonReader reader) { JToken token; using (JsonTokenWriter writer = new JsonTokenWriter()) { writer.WriteToken(reader); token = writer.Token; } return token; } private bool HasClassConverter(Type objectType, out JsonConverter converter) { if (objectType == null) throw new ArgumentNullException("objectType"); converter = JsonTypeReflector.GetConverter(objectType, objectType); return (converter != null); } private object CreateObject(JsonReader reader, Type objectType, object existingValue, JsonConverter memberConverter) { _level++; object value; JsonConverter converter; if (memberConverter != null) { return memberConverter.ReadJson(reader, objectType); } else if (objectType != null && HasClassConverter(objectType, out converter)) { return converter.ReadJson(reader, objectType); } else if (objectType != null && HasMatchingConverter(objectType, out converter)) { return converter.ReadJson(reader, objectType); } else if (objectType == typeof(JsonRaw)) { return JsonRaw.Create(reader); } else { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: if (objectType == null) { value = CreateJToken(reader); } else if (CollectionUtils.IsDictionaryType(objectType)) { if (existingValue == null) value = CreateAndPopulateDictionary(reader, objectType); else value = PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(existingValue), reader); } else { if (existingValue == null) value = CreateAndPopulateObject(reader, objectType); else value = PopulateObject(existingValue, reader, objectType); } break; case JsonToken.StartArray: if (objectType != null) { if (existingValue == null) value = CreateAndPopulateList(reader, objectType); else value = PopulateList(CollectionUtils.CreateCollectionWrapper(existingValue), ReflectionUtils.GetCollectionItemType(objectType), reader); } else { value = CreateJToken(reader); } break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: value = EnsureType(reader.Value, objectType); break; case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); value = constructorName; break; case JsonToken.Null: case JsonToken.Undefined: if (objectType == typeof(DBNull)) value = DBNull.Value; else value = null; break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } _level--; return value; } private object EnsureType(object value, Type targetType) { // do something about null value when the targetType is a valuetype? if (value == null) return null; if (targetType == null) return value; Type valueType = value.GetType(); // type of value and type of target don't match // attempt to convert value's type to target's type if (valueType != targetType) { return ConvertUtils.ConvertOrCast(value, CultureInfo.InvariantCulture, targetType); } else { return value; } } private JsonMemberMappingCollection GetMemberMappings(Type objectType) { ValidationUtils.ArgumentNotNull(objectType, "objectType"); if (_mappingResolver != null) return _mappingResolver.ResolveMappings(objectType); return DefaultMappingResolver.Instance.ResolveMappings(objectType); } private void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName) { JsonMemberMappingCollection memberMappings = GetMemberMappings(targetType); JsonMemberMapping memberMapping; // attempt exact case match first // then try match ignoring case if (memberMappings.TryGetClosestMatchMapping(memberName, out memberMapping)) { SetMappingValue(memberMapping, reader, target); } else { if (_missingMemberHandling == MissingMemberHandling.Error) throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, targetType.Name)); reader.Skip(); } } private void SetMappingValue(JsonMemberMapping memberMapping, JsonReader reader, object target) { if (memberMapping.Ignored) { reader.Skip(); return; } // get the member's underlying type Type memberType = ReflectionUtils.GetMemberUnderlyingType(memberMapping.Member); object currentValue = null; bool useExistingValue = false; if ((_objectCreationHandling == ObjectCreationHandling.Auto || _objectCreationHandling == ObjectCreationHandling.Reuse) && (reader.TokenType == JsonToken.StartArray || reader.TokenType == JsonToken.StartObject)) { currentValue = ReflectionUtils.GetMemberValue(memberMapping.Member, target); useExistingValue = (currentValue != null && !memberType.IsArray && !ReflectionUtils.InheritsGenericDefinition(memberType, typeof(ReadOnlyCollection<>))); } if (!memberMapping.Writable && !useExistingValue) { reader.Skip(); return; } object value = CreateObject(reader, memberType, (useExistingValue) ? currentValue : null, JsonTypeReflector.GetConverter(memberMapping.Member, memberType)); if (!useExistingValue && ShouldSetMappingValue(memberMapping, value)) ReflectionUtils.SetMemberValue(memberMapping.Member, target, value); } private bool ShouldSetMappingValue(JsonMemberMapping memberMapping, object value) { if (_nullValueHandling == NullValueHandling.Ignore && value == null) return false; if (_defaultValueHandling == DefaultValueHandling.Ignore && Equals(value, memberMapping.DefaultValue)) return false; if (!memberMapping.Writable) return false; return true; } private object CreateAndPopulateDictionary(JsonReader reader, Type objectType) { if (IsTypeGenericDictionaryInterface(objectType)) { Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(objectType, out keyType, out valueType); objectType = ReflectionUtils.MakeGenericType(typeof(Dictionary<,>), keyType, valueType); } IWrappedDictionary dictionary = CollectionUtils.CreateDictionaryWrapper(Activator.CreateInstance(objectType)); PopulateDictionary(dictionary, reader); return dictionary.UnderlyingDictionary; } private IDictionary PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader) { Type dictionaryType = dictionary.UnderlyingDictionary.GetType(); Type dictionaryKeyType = ReflectionUtils.GetDictionaryKeyType(dictionaryType); Type dictionaryValueType = ReflectionUtils.GetDictionaryValueType(dictionaryType); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: object keyValue = EnsureType(reader.Value, dictionaryKeyType); reader.Read(); dictionary.Add(keyValue, CreateObject(reader, dictionaryValueType, null, null)); break; case JsonToken.EndObject: return dictionary; default: throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); } } throw new JsonSerializationException("Unexpected end when deserializing object."); } private object CreateAndPopulateList(JsonReader reader, Type objectType) { if (IsTypeGenericCollectionInterface(objectType)) { Type itemType = ReflectionUtils.GetCollectionItemType(objectType); objectType = ReflectionUtils.MakeGenericType(typeof(List<>), itemType); } return CollectionUtils.CreateAndPopulateList(objectType, l => PopulateList(l, ReflectionUtils.GetCollectionItemType(objectType), reader)); } private IList PopulateList(IList list, Type listItemType, JsonReader reader) { while (reader.Read()) { switch (reader.TokenType) { case JsonToken.EndArray: return list; case JsonToken.Comment: break; default: object value = CreateObject(reader, listItemType, null, null); list.Add(value); break; } } throw new JsonSerializationException("Unexpected end when deserializing array."); } private bool IsTypeGenericDictionaryInterface(Type type) { if (!type.IsGenericType) return false; Type genericDefinition = type.GetGenericTypeDefinition(); return (genericDefinition == typeof (IDictionary<,>)); } private bool IsTypeGenericCollectionInterface(Type type) { if (!type.IsGenericType) return false; Type genericDefinition = type.GetGenericTypeDefinition(); return (genericDefinition == typeof (IList<>) || genericDefinition == typeof (ICollection<>) || genericDefinition == typeof (IEnumerable<>)); } private object CreateAndPopulateObject(JsonReader reader, Type objectType) { object newObject; if (objectType.IsInterface || objectType.IsAbstract) throw new JsonSerializationException("Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, objectType)); if (ReflectionUtils.HasDefaultConstructor(objectType)) { newObject = Activator.CreateInstance(objectType); PopulateObject(newObject, reader, objectType); return newObject; } return CreateObjectFromNonDefaultConstructor(objectType, reader); } private object CreateObjectFromNonDefaultConstructor(Type objectType, JsonReader reader) { // object should have a single constructor ConstructorInfo c = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).SingleOrDefault(); if (c == null) throw new JsonSerializationException("Could not find a public constructor for type {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); // create a dictionary to put retrieved values into JsonMemberMappingCollection memberMappings = GetMemberMappings(objectType); IDictionary<JsonMemberMapping, object> mappingValues = memberMappings.ToDictionary(kv => kv, kv => (object)null); bool exit = false; while (!exit && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); if (!reader.Read()) throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); JsonMemberMapping memberMapping; // attempt exact case match first // then try match ignoring case if (memberMappings.TryGetClosestMatchMapping(memberName, out memberMapping)) { if (!memberMapping.Ignored) { Type memberType = ReflectionUtils.GetMemberUnderlyingType(memberMapping.Member); mappingValues[memberMapping] = CreateObject(reader, memberType, null, memberMapping.MemberConverter); } } else { if (_missingMemberHandling == MissingMemberHandling.Error) throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); reader.Skip(); } break; case JsonToken.EndObject: exit = true; break; default: throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); } } IDictionary<ParameterInfo, object> constructorParameters = c.GetParameters().ToDictionary(p => p, p => (object)null); IDictionary<JsonMemberMapping, object> remainingMappingValues = new Dictionary<JsonMemberMapping, object>(); foreach (KeyValuePair<JsonMemberMapping, object> mappingValue in mappingValues) { ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, mappingValue.Key.MappingName).Key; if (matchingConstructorParameter != null) constructorParameters[matchingConstructorParameter] = mappingValue.Value; else remainingMappingValues.Add(mappingValue); } object createdObject = ReflectionUtils.CreateInstance(objectType, constructorParameters.Values.ToArray()); // go through unused values and set the newly created object's properties foreach (KeyValuePair<JsonMemberMapping, object> remainingMappingValue in remainingMappingValues) { if (ShouldSetMappingValue(remainingMappingValue.Key, remainingMappingValue.Value)) ReflectionUtils.SetMemberValue(remainingMappingValue.Key.Member, createdObject, remainingMappingValue.Value); } return createdObject; } private object PopulateObject(object newObject, JsonReader reader, Type objectType) { JsonMemberMappingCollection memberMappings = GetMemberMappings(objectType); Dictionary<string, bool> requiredMappings = memberMappings.Where(m => m.Required).ToDictionary(m => m.MappingName, m => false); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); if (!reader.Read()) throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (reader.TokenType != JsonToken.Null) SetRequiredMapping(memberName, requiredMappings); SetObjectMember(reader, newObject, objectType, memberName); break; case JsonToken.EndObject: foreach (KeyValuePair<string, bool> requiredMapping in requiredMappings) { if (!requiredMapping.Value) throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, requiredMapping.Key)); } return newObject; default: throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); } } throw new JsonSerializationException("Unexpected end when deserializing object."); } private void SetRequiredMapping(string memberName, Dictionary<string, bool> requiredMappings) { // first attempt to find exact case match // then attempt case insensitive match if (requiredMappings.ContainsKey(memberName)) { requiredMappings[memberName] = true; } else { foreach (KeyValuePair<string, bool> requiredMapping in requiredMappings) { if (string.Compare(requiredMapping.Key, requiredMapping.Key, StringComparison.OrdinalIgnoreCase) == 0) { requiredMappings[requiredMapping.Key] = true; break; } } } } #endregion #region Serialize /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(JsonWriter jsonWriter, object value) { if (jsonWriter == null) throw new ArgumentNullException("jsonWriter"); if (value is JToken) ((JToken)value).WriteTo(jsonWriter, (_converters != null) ? _converters.ToArray() : null); else SerializeValue(jsonWriter, value, null); } private void SerializeValue(JsonWriter writer, object value, JsonConverter memberConverter) { JsonConverter converter; if (value == null) { writer.WriteNull(); } else if (memberConverter != null) { memberConverter.WriteJson(writer, value); } else if (HasClassConverter(value.GetType(), out converter)) { converter.WriteJson(writer, value); } else if (HasMatchingConverter(value.GetType(), out converter)) { converter.WriteJson(writer, value); } else if (JsonConvert.IsJsonPrimitive(value)) { writer.WriteValue(value); } else if (value is IList) { SerializeList(writer, (IList)value); } else if (value is IDictionary) { SerializeDictionary(writer, (IDictionary)value); } else if (value is ICollection) { SerializeCollection(writer, (ICollection)value); } else if (value is IEnumerable) { SerializeEnumerable(writer, (IEnumerable)value); } else if (value is JsonRaw) { writer.WriteRawValue(((JsonRaw)value).Content); } else { SerializeObject(writer, value); } } private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter) { return HasMatchingConverter(_converters, type, out matchingConverter); } internal static bool HasMatchingConverter(IList<JsonConverter> converters, Type objectType, out JsonConverter matchingConverter) { if (objectType == null) throw new ArgumentNullException("objectType"); if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) { matchingConverter = converter; return true; } } } matchingConverter = null; return false; } private void WriteMemberInfoProperty(JsonWriter writer, object value, JsonMemberMapping memberMapping) { MemberInfo member = memberMapping.Member; string propertyName = memberMapping.MappingName; JsonConverter memberConverter = memberMapping.MemberConverter; object defaultValue = memberMapping.DefaultValue; if (!ReflectionUtils.IsIndexedProperty(member)) { object memberValue = ReflectionUtils.GetMemberValue(member, value); if (_nullValueHandling == NullValueHandling.Ignore && memberValue == null) return; if (_defaultValueHandling == DefaultValueHandling.Ignore && object.Equals(memberValue, defaultValue)) return; if (writer.SerializeStack.IndexOf(memberValue) != -1) { switch (_referenceLoopHandling) { case ReferenceLoopHandling.Error: throw new JsonSerializationException("Self referencing loop"); case ReferenceLoopHandling.Ignore: // return from method return; case ReferenceLoopHandling.Serialize: // continue break; default: throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(CultureInfo.InvariantCulture, _referenceLoopHandling)); } } writer.WritePropertyName(propertyName ?? member.Name); SerializeValue(writer, memberValue, memberConverter); } } private void SerializeObject(JsonWriter writer, object value) { Type objectType = value.GetType(); #if !SILVERLIGHT && !PocketPC TypeConverter converter = TypeDescriptor.GetConverter(objectType); // use the objectType's TypeConverter if it has one and can convert to a string if (converter != null && !(converter is ComponentConverter) && (converter.GetType() != typeof(TypeConverter) || value is Type)) { if (converter.CanConvertTo(typeof(string))) { writer.WriteValue(converter.ConvertToInvariantString(value)); return; } } #else if (value is Guid || value is Type) { writer.WriteValue(value.ToString()); return; } #endif writer.SerializeStack.Add(value); writer.WriteStartObject(); JsonMemberMappingCollection memberMappings = GetMemberMappings(objectType); foreach (JsonMemberMapping memberMapping in memberMappings) { if (!memberMapping.Ignored && memberMapping.Readable) WriteMemberInfoProperty(writer, value, memberMapping); } writer.WriteEndObject(); writer.SerializeStack.RemoveAt(writer.SerializeStack.Count - 1); } private void SerializeEnumerable(JsonWriter writer, IEnumerable values) { SerializeList(writer, values.Cast<object>().ToList()); } private void SerializeCollection(JsonWriter writer, ICollection values) { SerializeList(writer, values.Cast<object>().ToList()); } private void SerializeList(JsonWriter writer, IList values) { writer.WriteStartArray(); for (int i = 0; i < values.Count; i++) { SerializeValue(writer, values[i], null); } writer.WriteEndArray(); } private void SerializeDictionary(JsonWriter writer, IDictionary values) { writer.WriteStartObject(); foreach (DictionaryEntry entry in values) { writer.WritePropertyName(entry.Key.ToString()); SerializeValue(writer, entry.Value, null); } writer.WriteEndObject(); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent { using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Definition; using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update; using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.Definition; using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.Update; using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.UpdateDefinition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update; using System.Collections.Generic; internal partial class VirtualMachineScaleSetExtensionImpl { /// <summary> /// Gets true if this extension is configured to upgrade automatically when a new minor version of /// the extension image that this extension based on is published. /// </summary> bool Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.AutoUpgradeMinorVersionEnabled { get { return this.AutoUpgradeMinorVersionEnabled(); } } /// <summary> /// Gets the name of the resource. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name { get { return this.Name(); } } /// <summary> /// Gets the provisioning state of this virtual machine scale set extension. /// </summary> string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.ProvisioningState { get { return this.ProvisioningState(); } } /// <summary> /// Gets the public settings of the virtual machine scale set extension as key value pairs. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, object> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.PublicSettings { get { return this.PublicSettings(); } } /// <summary> /// Gets the public settings of the virtual machine extension as a JSON string. /// </summary> string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.PublicSettingsAsJsonString { get { return this.PublicSettingsAsJsonString(); } } /// <summary> /// Gets the publisher name of the virtual machine scale set extension image this extension is created from. /// </summary> string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.PublisherName { get { return this.PublisherName(); } } /// <summary> /// Gets the type name of the virtual machine scale set extension image this extension is created from. /// </summary> string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.TypeName { get { return this.TypeName(); } } /// <summary> /// Gets the version name of the virtual machine scale set extension image this extension is created from. /// </summary> string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension.VersionName { get { return this.VersionName(); } } /// <summary> /// Attaches the child definition to the parent resource update. /// </summary> /// <return>The next stage of the parent definition.</return> VirtualMachineScaleSet.Update.IWithApply Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<VirtualMachineScaleSet.Update.IWithApply>.Attach() { return this.Attach(); } /// <summary> /// Attaches the child definition to the parent resource definiton. /// </summary> /// <return>The next stage of the parent definition.</return> VirtualMachineScaleSet.Definition.IWithCreate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<VirtualMachineScaleSet.Definition.IWithCreate>.Attach() { return this.Attach(); } /// <summary> /// Specifies the virtual machine scale set extension image to use. /// </summary> /// <param name="image">An extension image.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithImageOrPublisher<VirtualMachineScaleSet.Definition.IWithCreate>.WithImage(IVirtualMachineExtensionImage image) { return this.WithImage(image); } /// <summary> /// Specifies the virtual machine scale set extension image to use. /// </summary> /// <param name="image">An extension image.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithImageOrPublisher<VirtualMachineScaleSet.Update.IWithApply>.WithImage(IVirtualMachineExtensionImage image) { return this.WithImage(image); } /// <summary> /// Enables auto-upgrading of the extension with minor versions. /// </summary> /// <return>The next stage of the update.</return> VirtualMachineScaleSetExtension.Update.IUpdate VirtualMachineScaleSetExtension.Update.IWithAutoUpgradeMinorVersion.WithMinorVersionAutoUpgrade() { return this.WithMinorVersionAutoUpgrade(); } /// <summary> /// Enables auto upgrading of the extension with minor versions. /// </summary> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithAutoUpgradeMinorVersion<VirtualMachineScaleSet.Definition.IWithCreate>.WithMinorVersionAutoUpgrade() { return this.WithMinorVersionAutoUpgrade(); } /// <summary> /// Enables auto upgrading of the extension with minor versions. /// </summary> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAutoUpgradeMinorVersion<VirtualMachineScaleSet.Update.IWithApply>.WithMinorVersionAutoUpgrade() { return this.WithMinorVersionAutoUpgrade(); } /// <summary> /// Disables auto upgrading of the extension with minor versions. /// </summary> /// <return>The next stage of the update.</return> VirtualMachineScaleSetExtension.Update.IUpdate VirtualMachineScaleSetExtension.Update.IWithAutoUpgradeMinorVersion.WithoutMinorVersionAutoUpgrade() { return this.WithoutMinorVersionAutoUpgrade(); } /// <summary> /// Disables auto upgrading the extension with minor versions. /// </summary> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithAutoUpgradeMinorVersion<VirtualMachineScaleSet.Definition.IWithCreate>.WithoutMinorVersionAutoUpgrade() { return this.WithoutMinorVersionAutoUpgrade(); } /// <summary> /// Disables auto upgrade of the extension with minor versions. /// </summary> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAutoUpgradeMinorVersion<VirtualMachineScaleSet.Update.IWithApply>.WithoutMinorVersionAutoUpgrade() { return this.WithoutMinorVersionAutoUpgrade(); } /// <summary> /// Specifies a private settings entry. /// </summary> /// <param name="key">The key of a private settings entry.</param> /// <param name="value">The value of the private settings entry.</param> /// <return>The next stage of the update.</return> VirtualMachineScaleSetExtension.Update.IUpdate VirtualMachineScaleSetExtension.Update.IWithSettings.WithProtectedSetting(string key, object value) { return this.WithProtectedSetting(key, value); } /// <summary> /// Specifies a private settings entry. /// </summary> /// <param name="key">The key of a private settings entry.</param> /// <param name="value">The value of the private settings entry.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithSettings<VirtualMachineScaleSet.Definition.IWithCreate>.WithProtectedSetting(string key, object value) { return this.WithProtectedSetting(key, value); } /// <summary> /// Specifies a private settings entry. /// </summary> /// <param name="key">The key of a private settings entry.</param> /// <param name="value">The value of the private settings entry.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithSettings<VirtualMachineScaleSet.Update.IWithApply>.WithProtectedSetting(string key, object value) { return this.WithProtectedSetting(key, value); } /// <summary> /// Specifies private settings. /// </summary> /// <param name="settings">The private settings.</param> /// <return>The next stage of the update.</return> VirtualMachineScaleSetExtension.Update.IUpdate VirtualMachineScaleSetExtension.Update.IWithSettings.WithProtectedSettings(IDictionary<string, object> settings) { return this.WithProtectedSettings(settings); } /// <summary> /// Specifies private settings. /// </summary> /// <param name="settings">The private settings.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithSettings<VirtualMachineScaleSet.Definition.IWithCreate>.WithProtectedSettings(IDictionary<string, object> settings) { return this.WithProtectedSettings(settings); } /// <summary> /// Specifies private settings. /// </summary> /// <param name="settings">The private settings.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithSettings<VirtualMachineScaleSet.Update.IWithApply>.WithProtectedSettings(IDictionary<string, object> settings) { return this.WithProtectedSettings(settings); } /// <summary> /// Specifies a public settings entry. /// </summary> /// <param name="key">The key of a public settings entry.</param> /// <param name="value">The value of the public settings entry.</param> /// <return>The next stage of the update.</return> VirtualMachineScaleSetExtension.Update.IUpdate VirtualMachineScaleSetExtension.Update.IWithSettings.WithPublicSetting(string key, object value) { return this.WithPublicSetting(key, value); } /// <summary> /// Specifies a public settings entry. /// </summary> /// <param name="key">The key of a public settings entry.</param> /// <param name="value">The value of the public settings entry.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithSettings<VirtualMachineScaleSet.Definition.IWithCreate>.WithPublicSetting(string key, object value) { return this.WithPublicSetting(key, value); } /// <summary> /// Specifies a public settings entry. /// </summary> /// <param name="key">The key of a public settings entry.</param> /// <param name="value">The value of the public settings entry.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithSettings<VirtualMachineScaleSet.Update.IWithApply>.WithPublicSetting(string key, object value) { return this.WithPublicSetting(key, value); } /// <summary> /// Specifies public settings. /// </summary> /// <param name="settings">The public settings.</param> /// <return>The next stage of the update.</return> VirtualMachineScaleSetExtension.Update.IUpdate VirtualMachineScaleSetExtension.Update.IWithSettings.WithPublicSettings(IDictionary<string, object> settings) { return this.WithPublicSettings(settings); } /// <summary> /// Specifies public settings. /// </summary> /// <param name="settings">The public settings.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithSettings<VirtualMachineScaleSet.Definition.IWithCreate>.WithPublicSettings(IDictionary<string, object> settings) { return this.WithPublicSettings(settings); } /// <summary> /// Specifies public settings. /// </summary> /// <param name="settings">The public settings.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithSettings<VirtualMachineScaleSet.Update.IWithApply>.WithPublicSettings(IDictionary<string, object> settings) { return this.WithPublicSettings(settings); } /// <summary> /// Specifies the name of the publisher of the virtual machine scale set extension image. /// </summary> /// <param name="extensionImagePublisherName">A publisher name.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithType<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithPublisher<VirtualMachineScaleSet.Definition.IWithCreate>.WithPublisher(string extensionImagePublisherName) { return this.WithPublisher(extensionImagePublisherName); } /// <summary> /// Specifies the name of the virtual machine scale set extension image publisher. /// </summary> /// <param name="extensionImagePublisherName">The publisher name.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithType<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithPublisher<VirtualMachineScaleSet.Update.IWithApply>.WithPublisher(string extensionImagePublisherName) { return this.WithPublisher(extensionImagePublisherName); } /// <summary> /// Specifies the type of the virtual machine scale set extension image. /// </summary> /// <param name="extensionImageTypeName">The image type name.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithVersion<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithType<VirtualMachineScaleSet.Definition.IWithCreate>.WithType(string extensionImageTypeName) { return this.WithType(extensionImageTypeName); } /// <summary> /// Specifies the type of the virtual machine scale set extension image. /// </summary> /// <param name="extensionImageTypeName">An image type name.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithVersion<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithType<VirtualMachineScaleSet.Update.IWithApply>.WithType(string extensionImageTypeName) { return this.WithType(extensionImageTypeName); } /// <summary> /// Specifies the version of the virtual machine scale set image extension. /// </summary> /// <param name="extensionImageVersionName">The version name.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.Definition.IWithAttach<VirtualMachineScaleSet.Definition.IWithCreate> VirtualMachineScaleSetExtension.Definition.IWithVersion<VirtualMachineScaleSet.Definition.IWithCreate>.WithVersion(string extensionImageVersionName) { return this.WithVersion(extensionImageVersionName); } /// <summary> /// Specifies the version of the virtual machine scale set image extension. /// </summary> /// <param name="extensionImageVersionName">A version name.</param> /// <return>The next stage of the definition.</return> VirtualMachineScaleSetExtension.UpdateDefinition.IWithAttach<VirtualMachineScaleSet.Update.IWithApply> VirtualMachineScaleSetExtension.UpdateDefinition.IWithVersion<VirtualMachineScaleSet.Update.IWithApply>.WithVersion(string extensionImageVersionName) { return this.WithVersion(extensionImageVersionName); } } }
using Tibia.Addresses; namespace Tibia { public partial class Version { public static void SetVersion857() { BattleList.Start = 0x63FEF0; BattleList.StepCreatures = 0xA8; BattleList.MaxCreatures = 250; BattleList.End = BattleList.Start + (BattleList.StepCreatures * BattleList.MaxCreatures); Client.StartTime = 0x7E0788; Client.XTeaKey = 0x7998B4; Client.SocketStruct = 0x799888; Client.RecvPointer = 0x5B85E4; Client.SendPointer = 0x5B8610; Client.FrameRatePointer = 0x79DA6C; Client.FrameRateCurrentOffset = 0x60; Client.FrameRateLimitOffset = 0x58; Client.MultiClient = 0x50BB24; Client.Status = 0x79CF20; Client.SafeMode = 0x799CDC; Client.FollowMode = Client.SafeMode + 4; Client.AttackMode = Client.FollowMode + 4; Client.ActionState = 0x79CF80; Client.ActionStateFreezer = 0x51D074; Client.LastMSGText = 0x7E094F8; Client.LastMSGAuthor = Client.LastMSGText - 0x28; Client.StatusbarText = 0x7E07A8; Client.StatusbarTime = Client.StatusbarText - 4; Client.ClickId = 0x79CFC0; Client.ClickCount = Client.ClickId + 4; Client.ClickZ = Client.ClickId - 0x68; Client.SeeId = Client.ClickId + 12; Client.SeeCount = Client.SeeId + 4; Client.SeeZ = Client.SeeId - 0x68; Client.ClickContextMenuItemId = 0x79CFCC; Client.ClickContextMenuCreatureId = 0x79CFD0; Client.LoginServerStart = 0x7947F0; Client.StepLoginServer = 112; Client.DistancePort = 100; Client.MaxLoginServers = 10; Client.RSA = 0x5B8980; Client.LoginCharList = 0x79CED4; Client.LoginCharListLength = 0x79CED8; Client.LoginSelectedChar = 0x79CED0; Client.GameWindowRectPointer = 0x64C254; Client.GameWindowBar = 0x7E079C; Client.DatPointer = 0x7998D4; Client.EventTriggerPointer = 0x51F4D0; Client.DialogPointer = 0x64F5BC; Client.DialogLeft = 0x14; Client.DialogTop = 0x18; Client.DialogWidth = 0x1C; Client.DialogHeight = 0x20; Client.DialogCaption = 0x50; Client.LastRcvPacket = 0x795068; Client.DecryptCall = 0x45C345; Client.LoginAccountNum = 0; Client.LoginPassword = 0x79CEDC; Client.LoginAccount = Client.LoginPassword + 32; Client.LoginPatch = 0; Client.LoginPatch2 = 0; Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 }; Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 }; Client.ParserFunc = 0x45C310; Client.GetNextPacketCall = 0x45C345; Client.RecvStream = 0x7998A4; Container.Start = 0x64CD08; Container.StepContainer = 492; Container.StepSlot = 12; Container.MaxContainers = 16; Container.MaxStack = 100; Container.DistanceIsOpen = 0; Container.DistanceId = 4; Container.DistanceName = 16; Container.DistanceVolume = 48; Container.DistanceAmount = 56; Container.DistanceItemId = 60; Container.DistanceItemCount = 64; Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer); ContextMenus.AddContextMenuPtr = 0x4522E0; ContextMenus.OnClickContextMenuPtr = 0x44E910; ContextMenus.OnClickContextMenuVf = 0x5BD9C0; ContextMenus.AddSetOutfitContextMenu = 0x453243; ContextMenus.AddPartyActionContextMenu = 0x45366C; ContextMenus.AddCopyNameContextMenu = 0x453750; ContextMenus.AddTradeWithContextMenu = 0x452E89; ContextMenus.AddLookContextMenu = 0x452D3F; Creature.DistanceId = 0; Creature.DistanceType = 3; Creature.DistanceName = 4; Creature.DistanceX = 36; Creature.DistanceY = 40; Creature.DistanceZ = 44; Creature.DistanceScreenOffsetHoriz = 48; Creature.DistanceScreenOffsetVert = 52; Creature.DistanceIsWalking = 76; Creature.DistanceWalkSpeed = 140; Creature.DistanceDirection = 80; Creature.DistanceIsVisible = 144; Creature.DistanceBlackSquare = 132; Creature.DistanceLight = 120; Creature.DistanceLightColor = 124; Creature.DistanceHPBar = 136; Creature.DistanceSkull = 148; Creature.DistanceParty = 152; Creature.DistanceWarIcon = 160; Creature.DistanceIsBlocking = 164; Creature.DistanceOutfit = 96; Creature.DistanceColorHead = 100; Creature.DistanceColorBody = 104; Creature.DistanceColorLegs = 108; Creature.DistanceColorFeet = 112; Creature.DistanceAddon = 116; DatItem.StepItems = 0x50; DatItem.Width = 0; DatItem.Height = 4; DatItem.MaxSizeInPixels = 8; DatItem.Layers = 12; DatItem.PatternX = 16; DatItem.PatternY = 20; DatItem.PatternDepth = 24; DatItem.Phase = 28; DatItem.Sprite = 32; DatItem.Flags = 36; DatItem.CanLookAt = 40; DatItem.WalkSpeed = 44; DatItem.TextLimit = 48; DatItem.LightRadius = 52; DatItem.LightColor = 56; DatItem.ShiftX = 60; DatItem.ShiftY = 64; DatItem.WalkHeight = 68; DatItem.Automap = 72; DatItem.LensHelp = 76; DrawItem.DrawItemFunc = 0x4B5770; DrawSkin.DrawSkinFunc = 0x4B9560; Hotkey.SendAutomaticallyStart = 0x799ED8; Hotkey.SendAutomaticallyStep = 0x01; Hotkey.TextStart = 0x799F00; Hotkey.TextStep = 0x100; Hotkey.ObjectStart = 0x799E48; Hotkey.ObjectStep = 0x04; Hotkey.ObjectUseTypeStart = 0x799D28; Hotkey.ObjectUseTypeStep = 0x04; Hotkey.MaxHotkeys = 36; Map.MapPointer = 0x654110; Map.StepTile = 168; Map.StepTileObject = 12; Map.DistanceTileObjectCount = 0; Map.DistanceTileObjects = 4; Map.DistanceObjectId = 0; Map.DistanceObjectData = 4; Map.DistanceObjectDataEx = 8; Map.MaxTileObjects = 10; Map.MaxX = 18; Map.MaxY = 14; Map.MaxZ = 8; Map.MaxTiles = 2016; Map.ZAxisDefault = 7; Map.NameSpy1 = 0x4F2689; Map.NameSpy2 = 0x4F2693; Map.NameSpy1Default = 19061; Map.NameSpy2Default = 16501; Map.LevelSpy1 = 0x4F453A; Map.LevelSpy2 = 0x4F463F; Map.LevelSpy3 = 0x4F46C0; Map.LevelSpyPtr = 0x64C254; Map.LevelSpyAdd1 = 28; Map.LevelSpyAdd2 = 0x2A88; Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0x88, 0x2A, 0x00, 0x00 }; Map.FullLightNop = 0x4EAE29; Map.FullLightAdr = 0x4EAE2C; Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 }; Map.FullLightNopEdited = new byte[] { 0x90, 0x90 }; Map.FullLightAdrDefault = 0x80; Map.FullLightAdrEdited = 0xFF; Player.Experience = 0x63FE84; Player.Flags = Player.Experience - 108; Player.Id = Player.Experience + 12; Player.Health = Player.Experience + 8; Player.HealthMax = Player.Experience + 4; Player.Level = Player.Experience - 4; Player.MagicLevel = Player.Experience - 8; Player.LevelPercent = Player.Experience - 12; Player.MagicLevelPercent = Player.Experience - 16; Player.Mana = Player.Experience - 20; Player.ManaMax = Player.Experience - 24; Player.Soul = Player.Experience - 28; Player.Stamina = Player.Experience - 32; Player.Capacity = Player.Experience - 36; Player.FistPercent = 0x63FE1C; Player.ClubPercent = Player.FistPercent + 4; Player.SwordPercent = Player.FistPercent + 8; Player.AxePercent = Player.FistPercent + 12; Player.DistancePercent = Player.FistPercent + 16; Player.ShieldingPercent = Player.FistPercent + 20; Player.FishingPercent = Player.FistPercent + 24; Player.Fist = Player.FistPercent + 28; Player.Club = Player.FistPercent + 32; Player.Sword = Player.FistPercent + 36; Player.Axe = Player.FistPercent + 40; Player.Distance = Player.FistPercent + 44; Player.Shielding = Player.FistPercent + 48; Player.Fishing = Player.FistPercent + 52; Player.SlotHead = 0x64CC90; Player.SlotNeck = Player.SlotHead + 12; Player.SlotBackpack = Player.SlotHead + 24; Player.SlotArmor = Player.SlotHead + 36; Player.SlotRight = Player.SlotHead + 48; Player.SlotLeft = Player.SlotHead + 60; Player.SlotLegs = Player.SlotHead + 72; Player.SlotFeet = Player.SlotHead + 84; Player.SlotRing = Player.SlotHead + 96; Player.SlotAmmo = Player.SlotHead + 108; Player.MaxSlots = 10; Player.DistanceSlotCount = 4; Player.CurrentTileToGo = 0x63FE98; Player.TilesToGo = 0x63FE9C; Player.GoToX = Player.Experience + 80; Player.GoToY = Player.GoToX - 4; Player.GoToZ = Player.GoToX - 8; Player.RedSquare = 0x63FE5C; Player.GreenSquare = Player.RedSquare - 4; Player.WhiteSquare = Player.GreenSquare - 8; Player.AccessN = 0; Player.AccessS = 0; Player.TargetId = Player.RedSquare; Player.TargetBattlelistId = Player.TargetId - 8; Player.TargetBattlelistType = Player.TargetId - 5; Player.TargetType = Player.TargetId + 3; Player.Z = 0x64F5F8; TextDisplay.PrintName = 0x4F56A3; TextDisplay.PrintFPS = 0x45A1F8; TextDisplay.ShowFPS = 0x63DB34; TextDisplay.PrintTextFunc = 0x4B4BB0; TextDisplay.NopFPS = 0x45A134; Vip.Start = 0x63DBB0; Vip.StepPlayers = 0x2C; Vip.MaxPlayers = 200; Vip.DistanceId = 0; Vip.DistanceName = 4; Vip.DistanceStatus = 34; Vip.DistanceIcon = 40; Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers); } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Creating { public sealed class CreateResourceWithToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>> { private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext; private readonly ReadWriteFakers _fakers = new(); public CreateResourceWithToOneRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext) { _testContext = testContext; testContext.UseController<WorkItemGroupsController>(); testContext.UseController<WorkItemsController>(); testContext.UseController<RgbColorsController>(); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.AllowClientGeneratedIds = true; } [Fact] public async Task Can_create_OneToOne_relationship_from_principal_side() { // Arrange WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate(); existingGroup.Color = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Groups.Add(existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItemGroups", relationships = new { color = new { data = new { type = "rgbColors", id = existingGroup.Color.StringId } } } } }; const string route = "/workItemGroups"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes.Should().NotBeEmpty(); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); string newGroupId = responseDocument.Data.SingleValue.Id; newGroupId.Should().NotBeNullOrEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<WorkItemGroup> groupsInDatabase = await dbContext.Groups.Include(group => group.Color).ToListAsync(); WorkItemGroup newGroupInDatabase = groupsInDatabase.Single(group => group.StringId == newGroupId); newGroupInDatabase.Color.Should().NotBeNull(); newGroupInDatabase.Color.Id.Should().Be(existingGroup.Color.Id); WorkItemGroup existingGroupInDatabase = groupsInDatabase.Single(group => group.Id == existingGroup.Id); existingGroupInDatabase.Color.Should().BeNull(); }); } [Fact] public async Task Can_create_OneToOne_relationship_from_dependent_side() { // Arrange RgbColor existingColor = _fakers.RgbColor.Generate(); existingColor.Group = _fakers.WorkItemGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.RgbColors.Add(existingColor); await dbContext.SaveChangesAsync(); }); const string colorId = "0A0B0C"; var requestBody = new { data = new { type = "rgbColors", id = colorId, relationships = new { group = new { data = new { type = "workItemGroups", id = existingColor.Group.StringId } } } } }; const string route = "/rgbColors"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(rgbColor => rgbColor.Group).ToListAsync(); RgbColor newColorInDatabase = colorsInDatabase.Single(color => color.Id == colorId); newColorInDatabase.Group.Should().NotBeNull(); newColorInDatabase.Group.Id.Should().Be(existingColor.Group.Id); RgbColor existingColorInDatabase = colorsInDatabase.SingleOrDefault(color => color.Id == existingColor.Id); existingColorInDatabase.Should().NotBeNull(); existingColorInDatabase!.Group.Should().BeNull(); }); } [Fact] public async Task Can_create_relationship_with_include() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } } } } }; const string route = "/workItems?include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes.Should().NotBeEmpty(); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId); responseDocument.Included[0].Attributes["firstName"].Should().Be(existingUserAccount.FirstName); responseDocument.Included[0].Attributes["lastName"].Should().Be(existingUserAccount.LastName); responseDocument.Included[0].Relationships.Should().NotBeEmpty(); int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(newWorkItemId); workItemInDatabase.Assignee.Should().NotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccount.Id); }); } [Fact] public async Task Can_create_relationship_with_include_and_primary_fieldset() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); WorkItem newWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", attributes = new { description = newWorkItem.Description, priority = newWorkItem.Priority }, relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } } } } }; const string route = "/workItems?fields[workItems]=description,assignee&include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes.Should().HaveCount(1); responseDocument.Data.SingleValue.Attributes["description"].Should().Be(newWorkItem.Description); responseDocument.Data.SingleValue.Relationships.Should().HaveCount(1); responseDocument.Data.SingleValue.Relationships["assignee"].Data.SingleValue.Id.Should().Be(existingUserAccount.StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId); responseDocument.Included[0].Attributes["firstName"].Should().Be(existingUserAccount.FirstName); responseDocument.Included[0].Attributes["lastName"].Should().Be(existingUserAccount.LastName); responseDocument.Included[0].Relationships.Should().NotBeEmpty(); int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(newWorkItemId); workItemInDatabase.Description.Should().Be(newWorkItem.Description); workItemInDatabase.Priority.Should().Be(newWorkItem.Priority); workItemInDatabase.Assignee.Should().NotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccount.Id); }); } [Fact] public async Task Cannot_create_for_missing_relationship_type() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { id = Unknown.StringId.For<UserAccount, long>() } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element."); error.Detail.Should().StartWith("Expected 'type' element in 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Cannot_create_for_unknown_relationship_type() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = Unknown.ResourceType, id = Unknown.StringId.For<UserAccount, long>() } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type."); error.Detail.Should().StartWith($"Resource type '{Unknown.ResourceType}' does not exist. - Request body: <<"); } [Fact] public async Task Cannot_create_for_missing_relationship_ID() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts" } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' element."); error.Detail.Should().StartWith("Expected 'id' element in 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Cannot_create_with_unknown_relationship_ID() { // Arrange string userAccountId = Unknown.StringId.For<UserAccount, long>(); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts", id = userAccountId } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId}' in relationship 'assignee' does not exist."); } [Fact] public async Task Cannot_create_on_relationship_type_mismatch() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "rgbColors", id = "0A0B0C" } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Relationship contains incompatible resource type."); error.Detail.Should().StartWith("Relationship 'assignee' contains incompatible resource type 'rgbColors'. - Request body: <<"); } [Fact] public async Task Can_create_resource_with_duplicate_relationship() { // Arrange List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.AddRange(existingUserAccounts); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccounts[0].StringId } }, assignee_duplicate = new { data = new { type = "userAccounts", id = existingUserAccounts[1].StringId } } } } }; string requestBodyText = JsonSerializer.Serialize(requestBody).Replace("assignee_duplicate", "assignee"); const string route = "/workItems?include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBodyText); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes.Should().NotBeEmpty(); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccounts[1].StringId); responseDocument.Included[0].Attributes["firstName"].Should().Be(existingUserAccounts[1].FirstName); responseDocument.Included[0].Attributes["lastName"].Should().Be(existingUserAccounts[1].LastName); responseDocument.Included[0].Relationships.Should().NotBeEmpty(); int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(newWorkItemId); workItemInDatabase.Assignee.Should().NotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccounts[1].Id); }); } [Fact] public async Task Cannot_create_with_data_array_in_relationship() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new[] { new { type = "userAccounts", id = existingUserAccount.StringId } } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected single data element for to-one relationship."); error.Detail.Should().StartWith("Expected single data element for 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Cannot_create_resource_with_local_ID() { // Arrange const string workItemLocalId = "wo-1"; var requestBody = new { data = new { type = "workItems", lid = workItemLocalId, relationships = new { parent = new { data = new { type = "workItems", lid = workItemLocalId } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().StartWith("Local IDs cannot be used at this endpoint. - Request body: <<"); } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; using System.Windows.Threading; using Fluent.Extensions; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents panel for Gallery and InRibbonGallery with grouping and filtering capabilities /// </summary> public class GalleryPanel : StackPanel { // todo: localization private const string Undefined = "Undefined"; #region Fields // Currently used group containers private readonly List<GalleryGroupContainer> galleryGroupContainers = new List<GalleryGroupContainer>(); // Designate that gallery panel must be refreshed its groups private bool needsRefresh; #endregion #region Properties #region IsGrouped /// <summary> /// Gets or sets whether gallery panel shows groups /// (Filter property still works as usual) /// </summary> public bool IsGrouped { get { return (bool)this.GetValue(IsGroupedProperty); } set { this.SetValue(IsGroupedProperty, value); } } /// <summary>Identifies the <see cref="IsGrouped"/> dependency property.</summary> public static readonly DependencyProperty IsGroupedProperty = DependencyProperty.Register(nameof(IsGrouped), typeof(bool), typeof(GalleryPanel), new PropertyMetadata(BooleanBoxes.FalseBox, OnIsGroupedChanged)); private static void OnIsGroupedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var galleryPanel = (GalleryPanel)d; galleryPanel.RefreshAsync(); } #endregion #region GroupBy /// <summary> /// Gets or sets property name to group items /// </summary> public string GroupBy { get { return (string)this.GetValue(GroupByProperty); } set { this.SetValue(GroupByProperty, value); } } /// <summary>Identifies the <see cref="GroupBy"/> dependency property.</summary> public static readonly DependencyProperty GroupByProperty = DependencyProperty.Register(nameof(GroupBy), typeof(string), typeof(GalleryPanel), new PropertyMetadata(OnGroupByChanged)); private static void OnGroupByChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var galleryPanel = (GalleryPanel)d; galleryPanel.RefreshAsync(); } #endregion #region GroupByAdvanced /// <summary> /// Gets or sets name of property which /// will use to group items in the Gallery. /// </summary> public Func<object, string> GroupByAdvanced { get { return (Func<object, string>)this.GetValue(GroupByAdvancedProperty); } set { this.SetValue(GroupByAdvancedProperty, value); } } /// <summary>Identifies the <see cref="GroupByAdvanced"/> dependency property.</summary> public static readonly DependencyProperty GroupByAdvancedProperty = DependencyProperty.Register(nameof(GroupByAdvanced), typeof(Func<object, string>), typeof(GalleryPanel), new PropertyMetadata(OnGroupByAdvancedChanged)); private static void OnGroupByAdvancedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var galleryPanel = (GalleryPanel)d; galleryPanel.RefreshAsync(); } #endregion #region ItemContainerGenerator /// <summary> /// Gets or sets ItemContainerGenerator which generates the /// user interface (UI) on behalf of its host, such as an ItemsControl. /// </summary> public ItemContainerGenerator ItemContainerGenerator { get { return (ItemContainerGenerator)this.GetValue(ItemContainerGeneratorProperty); } set { this.SetValue(ItemContainerGeneratorProperty, value); } } /// <summary>Identifies the <see cref="ItemContainerGenerator"/> dependency property.</summary> public static readonly DependencyProperty ItemContainerGeneratorProperty = DependencyProperty.Register(nameof(ItemContainerGenerator), typeof(ItemContainerGenerator), typeof(GalleryPanel), new PropertyMetadata(OnItemContainerGeneratorChanged)); private static void OnItemContainerGeneratorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var galleryPanel = (GalleryPanel)d; galleryPanel.RefreshAsync(); } #endregion #region ItemWidth /// <summary> /// Gets or sets a value that specifies the width of /// all items that are contained within /// </summary> public double ItemWidth { get { return (double)this.GetValue(ItemWidthProperty); } set { this.SetValue(ItemWidthProperty, value); } } /// <summary>Identifies the <see cref="ItemWidth"/> dependency property.</summary> public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register(nameof(ItemWidth), typeof(double), typeof(GalleryPanel), new PropertyMetadata(DoubleBoxes.NaN)); #endregion #region ItemHeight /// <summary> /// Gets or sets a value that specifies the height of /// all items that are contained within /// </summary> public double ItemHeight { get { return (double)this.GetValue(ItemHeightProperty); } set { this.SetValue(ItemHeightProperty, value); } } /// <summary>Identifies the <see cref="ItemHeight"/> dependency property.</summary> public static readonly DependencyProperty ItemHeightProperty = DependencyProperty.Register(nameof(ItemHeight), typeof(double), typeof(GalleryPanel), new PropertyMetadata(DoubleBoxes.NaN)); #endregion #region Filter /// <summary> /// Gets or sets groups names separated by comma which must be shown /// </summary> public string Filter { get { return (string)this.GetValue(FilterProperty); } set { this.SetValue(FilterProperty, value); } } /// <summary>Identifies the <see cref="Filter"/> dependency property.</summary> public static readonly DependencyProperty FilterProperty = DependencyProperty.Register(nameof(Filter), typeof(string), typeof(GalleryPanel), new PropertyMetadata(OnFilterChanged)); private static void OnFilterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var galleryPanel = (GalleryPanel)d; galleryPanel.RefreshAsync(); } #endregion #region MinItemsInRow /// <summary> /// Gets or sets maximum items quantity in row /// </summary> public int MinItemsInRow { get { return (int)this.GetValue(MinItemsInRowProperty); } set { this.SetValue(MinItemsInRowProperty, value); } } /// <summary>Identifies the <see cref="MinItemsInRow"/> dependency property.</summary> public static readonly DependencyProperty MinItemsInRowProperty = DependencyProperty.Register(nameof(MinItemsInRow), typeof(int), typeof(GalleryPanel), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion #region MaxItemsInRow /// <summary> /// Gets or sets maximum items quantity in row /// </summary> public int MaxItemsInRow { get { return (int)this.GetValue(MaxItemsInRowProperty); } set { this.SetValue(MaxItemsInRowProperty, value); } } /// <summary>Identifies the <see cref="MaxItemsInRow"/> dependency property.</summary> public static readonly DependencyProperty MaxItemsInRowProperty = DependencyProperty.Register(nameof(MaxItemsInRow), typeof(int), typeof(GalleryPanel), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion #endregion #region Initialization /// <summary> /// Default constructor /// </summary> public GalleryPanel() { this.visualCollection = new VisualCollection(this); this.Loaded += this.HandleGalleryPanel_Loaded; } private void HandleGalleryPanel_Loaded(object sender, RoutedEventArgs e) { this.Loaded -= this.HandleGalleryPanel_Loaded; this.Refresh(); } #endregion #region Visual Tree private readonly VisualCollection visualCollection; /// <inheritdoc /> protected override int VisualChildrenCount => base.VisualChildrenCount + this.visualCollection.Count; /// <inheritdoc /> protected override Visual GetVisualChild(int index) { if (index < base.VisualChildrenCount) { return base.GetVisualChild(index); } return this.visualCollection[index - base.VisualChildrenCount]; } #endregion #region Refresh private bool areUpdatesSuspsended; /// <summary> /// Suspends updates. /// </summary> public void SuspendUpdates() { this.areUpdatesSuspsended = true; } /// <summary> /// Resumes updates. /// </summary> public void ResumeUpdates() { this.areUpdatesSuspsended = false; } /// <summary> /// Resumes updates and calls <see cref="Refresh"/>. /// </summary> public void ResumeUpdatesRefresh() { this.ResumeUpdates(); this.Refresh(); } private void RefreshAsync() { if (this.needsRefresh || this.areUpdatesSuspsended) { return; } this.needsRefresh = true; this.RunInDispatcherAsync(() => { if (this.needsRefresh == false) { return; } this.Refresh(); this.needsRefresh = false; }, DispatcherPriority.Send); } private void Refresh() { if (this.areUpdatesSuspsended) { return; } // Clear currently used group containers // and supply with new generated ones foreach (var galleryGroupContainer in this.galleryGroupContainers) { BindingOperations.ClearAllBindings(galleryGroupContainer); this.visualCollection.Remove(galleryGroupContainer); } this.galleryGroupContainers.Clear(); // Gets filters var filter = this.Filter?.Split(','); var dictionary = new Dictionary<string, GalleryGroupContainer>(); foreach (UIElement item in this.InternalChildren) { if (item is null) { continue; } // Resolve group name string propertyValue = null; if (this.GroupByAdvanced != null) { propertyValue = this.ItemContainerGenerator is null ? this.GroupByAdvanced(item) : this.GroupByAdvanced(this.ItemContainerGenerator.ItemFromContainerOrContainerContent(item)); } else if (string.IsNullOrEmpty(this.GroupBy) == false) { propertyValue = this.ItemContainerGenerator is null ? this.GetPropertyValueAsString(item) : this.GetPropertyValueAsString(this.ItemContainerGenerator.ItemFromContainerOrContainerContent(item)); } if (propertyValue is null) { propertyValue = Undefined; } // Make invisible if it is not in filter (or is not grouped) if (this.IsGrouped == false || (filter != null && filter.Contains(propertyValue) == false)) { item.Measure(new Size(0, 0)); item.Arrange(new Rect(0, 0, 0, 0)); } // Skip if it is not in filter if (filter != null && filter.Contains(propertyValue) == false) { continue; } // To put all items in one group in case of IsGrouped = False if (this.IsGrouped == false) { propertyValue = Undefined; } if (dictionary.ContainsKey(propertyValue) == false) { var galleryGroupContainer = new GalleryGroupContainer { Header = propertyValue }; RibbonControl.Bind(this, galleryGroupContainer, nameof(this.Orientation), GalleryGroupContainer.OrientationProperty, BindingMode.OneWay); RibbonControl.Bind(this, galleryGroupContainer, nameof(this.ItemWidth), GalleryGroupContainer.ItemWidthProperty, BindingMode.OneWay); RibbonControl.Bind(this, galleryGroupContainer, nameof(this.ItemHeight), GalleryGroupContainer.ItemHeightProperty, BindingMode.OneWay); RibbonControl.Bind(this, galleryGroupContainer, nameof(this.MaxItemsInRow), GalleryGroupContainer.MaxItemsInRowProperty, BindingMode.OneWay); RibbonControl.Bind(this, galleryGroupContainer, nameof(this.MinItemsInRow), GalleryGroupContainer.MinItemsInRowProperty, BindingMode.OneWay); dictionary.Add(propertyValue, galleryGroupContainer); this.galleryGroupContainers.Add(galleryGroupContainer); this.visualCollection.Add(galleryGroupContainer); } var galleryItemPlaceholder = new GalleryItemPlaceholder(item); dictionary[propertyValue].Items.Add(galleryItemPlaceholder); } if ((this.IsGrouped == false || (this.GroupBy is null && this.GroupByAdvanced is null)) && this.galleryGroupContainers.Count != 0) { // Make it without headers if there is only one group or if we are not supposed to group this.galleryGroupContainers[0].IsHeadered = false; } this.InvalidateMeasure(); } /// <inheritdoc /> protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved) { base.OnVisualChildrenChanged(visualAdded, visualRemoved); if (visualRemoved is GalleryGroupContainer) { return; } if (visualAdded is GalleryGroupContainer) { return; } this.RefreshAsync(); } #endregion #region Layout Overrides /// <inheritdoc /> protected override Size MeasureOverride(Size availableSize) { double width = 0; double height = 0; foreach (var child in this.galleryGroupContainers) { child.Measure(availableSize); height += child.DesiredSize.Height; width = Math.Max(width, child.DesiredSize.Width); } var size = new Size(width, height); return size; } /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) { var finalRect = new Rect(finalSize); foreach (var item in this.galleryGroupContainers) { finalRect.Height = item.DesiredSize.Height; finalRect.Width = Math.Max(finalSize.Width, item.DesiredSize.Width); // Arrange a container to arrange placeholders item.Arrange(finalRect); finalRect.Y += item.DesiredSize.Height; // Now arrange our actual items using arranged size of placeholders foreach (GalleryItemPlaceholder placeholder in item.Items) { var leftTop = placeholder.TranslatePoint(default, this); placeholder.Target.Arrange(new Rect(leftTop.X, leftTop.Y, placeholder.ArrangedSize.Width, placeholder.ArrangedSize.Height)); } } return finalSize; } #endregion #region Private Methods private string GetPropertyValueAsString(object item) { if (item is null || this.GroupBy is null) { return Undefined; } var property = item.GetType().GetProperty(this.GroupBy, BindingFlags.Public | BindingFlags.Instance); var result = property?.GetValue(item, null); if (result is null) { return Undefined; } return result.ToString(); } #endregion /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var count = this.VisualChildrenCount; for (var i = 0; i < count; i++) { yield return this.GetVisualChild(i); } } } } }
using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Support; using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ByteBlockPool = Lucene.Net.Util.ByteBlockPool; using BytesRef = Lucene.Net.Util.BytesRef; using OffsetAttribute = Lucene.Net.Analysis.TokenAttributes.OffsetAttribute; using PayloadAttribute = Lucene.Net.Analysis.TokenAttributes.PayloadAttribute; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using TermVectorsWriter = Lucene.Net.Codecs.TermVectorsWriter; internal sealed class TermVectorsConsumerPerField : TermsHashConsumerPerField { internal readonly TermsHashPerField termsHashPerField; internal readonly TermVectorsConsumer termsWriter; internal readonly FieldInfo fieldInfo; internal readonly DocumentsWriterPerThread.DocState docState; internal readonly FieldInvertState fieldState; internal bool doVectors; internal bool doVectorPositions; internal bool doVectorOffsets; internal bool doVectorPayloads; internal int maxNumPostings; internal IOffsetAttribute offsetAttribute; internal IPayloadAttribute payloadAttribute; internal bool hasPayloads; // if enabled, and we actually saw any for this field public TermVectorsConsumerPerField(TermsHashPerField termsHashPerField, TermVectorsConsumer termsWriter, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.termsWriter = termsWriter; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; } internal override int StreamCount { get { return 2; } } internal override bool Start(IIndexableField[] fields, int count) { doVectors = false; doVectorPositions = false; doVectorOffsets = false; doVectorPayloads = false; hasPayloads = false; for (int i = 0; i < count; i++) { IIndexableField field = fields[i]; if (field.IndexableFieldType.IsIndexed) { if (field.IndexableFieldType.StoreTermVectors) { doVectors = true; doVectorPositions |= field.IndexableFieldType.StoreTermVectorPositions; doVectorOffsets |= field.IndexableFieldType.StoreTermVectorOffsets; if (doVectorPositions) { doVectorPayloads |= field.IndexableFieldType.StoreTermVectorPayloads; } else if (field.IndexableFieldType.StoreTermVectorPayloads) { // TODO: move this check somewhere else, and impl the other missing ones throw new System.ArgumentException("cannot index term vector payloads without term vector positions (field=\"" + field.Name + "\")"); } } else { if (field.IndexableFieldType.StoreTermVectorOffsets) { throw new System.ArgumentException("cannot index term vector offsets when term vectors are not indexed (field=\"" + field.Name + "\")"); } if (field.IndexableFieldType.StoreTermVectorPositions) { throw new System.ArgumentException("cannot index term vector positions when term vectors are not indexed (field=\"" + field.Name + "\")"); } if (field.IndexableFieldType.StoreTermVectorPayloads) { throw new System.ArgumentException("cannot index term vector payloads when term vectors are not indexed (field=\"" + field.Name + "\")"); } } } else { if (field.IndexableFieldType.StoreTermVectors) { throw new System.ArgumentException("cannot index term vectors when field is not indexed (field=\"" + field.Name + "\")"); } if (field.IndexableFieldType.StoreTermVectorOffsets) { throw new System.ArgumentException("cannot index term vector offsets when field is not indexed (field=\"" + field.Name + "\")"); } if (field.IndexableFieldType.StoreTermVectorPositions) { throw new System.ArgumentException("cannot index term vector positions when field is not indexed (field=\"" + field.Name + "\")"); } if (field.IndexableFieldType.StoreTermVectorPayloads) { throw new System.ArgumentException("cannot index term vector payloads when field is not indexed (field=\"" + field.Name + "\")"); } } } if (doVectors) { termsWriter.hasVectors = true; if (termsHashPerField.bytesHash.Count != 0) { // Only necessary if previous doc hit a // non-aborting exception while writing vectors in // this field: termsHashPerField.Reset(); } } // TODO: only if needed for performance //perThread.postingsCount = 0; return doVectors; } [MethodImpl(MethodImplOptions.NoInlining)] public void Abort() { } /// <summary> /// Called once per field per document if term vectors /// are enabled, to write the vectors to /// RAMOutputStream, which is then quickly flushed to /// the real term vectors files in the Directory. /// </summary> internal override void Finish() { if (!doVectors || termsHashPerField.bytesHash.Count == 0) { return; } termsWriter.AddFieldToFlush(this); } [MethodImpl(MethodImplOptions.NoInlining)] internal void FinishDocument() { Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.finish start")); int numPostings = termsHashPerField.bytesHash.Count; BytesRef flushTerm = termsWriter.flushTerm; Debug.Assert(numPostings >= 0); if (numPostings > maxNumPostings) { maxNumPostings = numPostings; } // this is called once, after inverting all occurrences // of a given field in the doc. At this point we flush // our hash into the DocWriter. Debug.Assert(termsWriter.VectorFieldsInOrder(fieldInfo)); TermVectorsPostingsArray postings = (TermVectorsPostingsArray)termsHashPerField.postingsArray; TermVectorsWriter tv = termsWriter.writer; int[] termIDs = termsHashPerField.SortPostings(tv.Comparer); tv.StartField(fieldInfo, numPostings, doVectorPositions, doVectorOffsets, hasPayloads); ByteSliceReader posReader = doVectorPositions ? termsWriter.vectorSliceReaderPos : null; ByteSliceReader offReader = doVectorOffsets ? termsWriter.vectorSliceReaderOff : null; ByteBlockPool termBytePool = termsHashPerField.termBytePool; for (int j = 0; j < numPostings; j++) { int termID = termIDs[j]; int freq = postings.freqs[termID]; // Get BytesRef termBytePool.SetBytesRef(flushTerm, postings.textStarts[termID]); tv.StartTerm(flushTerm, freq); if (doVectorPositions || doVectorOffsets) { if (posReader != null) { termsHashPerField.InitReader(posReader, termID, 0); } if (offReader != null) { termsHashPerField.InitReader(offReader, termID, 1); } tv.AddProx(freq, posReader, offReader); } tv.FinishTerm(); } tv.FinishField(); termsHashPerField.Reset(); fieldInfo.SetStoreTermVectors(); } internal void ShrinkHash() { termsHashPerField.ShrinkHash(maxNumPostings); maxNumPostings = 0; } internal override void Start(IIndexableField f) { if (doVectorOffsets) { offsetAttribute = fieldState.AttributeSource.AddAttribute<IOffsetAttribute>(); } else { offsetAttribute = null; } if (doVectorPayloads && fieldState.AttributeSource.HasAttribute<IPayloadAttribute>()) { payloadAttribute = fieldState.AttributeSource.GetAttribute<IPayloadAttribute>(); } else { payloadAttribute = null; } } internal void WriteProx(TermVectorsPostingsArray postings, int termID) { if (doVectorOffsets) { int startOffset = fieldState.Offset + offsetAttribute.StartOffset; int endOffset = fieldState.Offset + offsetAttribute.EndOffset; termsHashPerField.WriteVInt32(1, startOffset - postings.lastOffsets[termID]); termsHashPerField.WriteVInt32(1, endOffset - startOffset); postings.lastOffsets[termID] = endOffset; } if (doVectorPositions) { BytesRef payload; if (payloadAttribute == null) { payload = null; } else { payload = payloadAttribute.Payload; } int pos = fieldState.Position - postings.lastPositions[termID]; if (payload != null && payload.Length > 0) { termsHashPerField.WriteVInt32(0, (pos << 1) | 1); termsHashPerField.WriteVInt32(0, payload.Length); termsHashPerField.WriteBytes(0, payload.Bytes, payload.Offset, payload.Length); hasPayloads = true; } else { termsHashPerField.WriteVInt32(0, pos << 1); } postings.lastPositions[termID] = fieldState.Position; } } internal override void NewTerm(int termID) { Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.newTerm start")); TermVectorsPostingsArray postings = (TermVectorsPostingsArray)termsHashPerField.postingsArray; postings.freqs[termID] = 1; postings.lastOffsets[termID] = 0; postings.lastPositions[termID] = 0; WriteProx(postings, termID); } internal override void AddTerm(int termID) { Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.addTerm start")); TermVectorsPostingsArray postings = (TermVectorsPostingsArray)termsHashPerField.postingsArray; postings.freqs[termID]++; WriteProx(postings, termID); } [ExceptionToNetNumericConvention] internal override void SkippingLongTerm() { } internal override ParallelPostingsArray CreatePostingsArray(int size) { return new TermVectorsPostingsArray(size); } internal sealed class TermVectorsPostingsArray : ParallelPostingsArray { public TermVectorsPostingsArray(int size) : base(size) { freqs = new int[size]; lastOffsets = new int[size]; lastPositions = new int[size]; } internal int[] freqs; // How many times this term occurred in the current doc internal int[] lastOffsets; // Last offset we saw internal int[] lastPositions; // Last position where this term occurred internal override ParallelPostingsArray NewInstance(int size) { return new TermVectorsPostingsArray(size); } internal override void CopyTo(ParallelPostingsArray toArray, int numToCopy) { Debug.Assert(toArray is TermVectorsPostingsArray); TermVectorsPostingsArray to = (TermVectorsPostingsArray)toArray; base.CopyTo(toArray, numToCopy); Array.Copy(freqs, 0, to.freqs, 0, size); Array.Copy(lastOffsets, 0, to.lastOffsets, 0, size); Array.Copy(lastPositions, 0, to.lastPositions, 0, size); } internal override int BytesPerPosting() { return base.BytesPerPosting() + 3 * RamUsageEstimator.NUM_BYTES_INT32; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.GkeHub.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedGkeHubClientTest { [xunit::FactAttribute] public void GetMembershipRequestObject() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMembershipRequest request = new GetMembershipRequest { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), }; Membership expectedResponse = new Membership { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", Endpoint = new MembershipEndpoint(), State = new MembershipState(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), ExternalId = "external_id9442680e", LastConnectionTime = new wkt::Timestamp(), UniqueId = "unique_idee0c0869", Authority = new Authority(), }; mockGrpcClient.Setup(x => x.GetMembership(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Membership response = client.GetMembership(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMembershipRequestObjectAsync() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMembershipRequest request = new GetMembershipRequest { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), }; Membership expectedResponse = new Membership { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", Endpoint = new MembershipEndpoint(), State = new MembershipState(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), ExternalId = "external_id9442680e", LastConnectionTime = new wkt::Timestamp(), UniqueId = "unique_idee0c0869", Authority = new Authority(), }; mockGrpcClient.Setup(x => x.GetMembershipAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Membership>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Membership responseCallSettings = await client.GetMembershipAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Membership responseCancellationToken = await client.GetMembershipAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMembership() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMembershipRequest request = new GetMembershipRequest { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), }; Membership expectedResponse = new Membership { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", Endpoint = new MembershipEndpoint(), State = new MembershipState(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), ExternalId = "external_id9442680e", LastConnectionTime = new wkt::Timestamp(), UniqueId = "unique_idee0c0869", Authority = new Authority(), }; mockGrpcClient.Setup(x => x.GetMembership(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Membership response = client.GetMembership(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMembershipAsync() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMembershipRequest request = new GetMembershipRequest { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), }; Membership expectedResponse = new Membership { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", Endpoint = new MembershipEndpoint(), State = new MembershipState(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), ExternalId = "external_id9442680e", LastConnectionTime = new wkt::Timestamp(), UniqueId = "unique_idee0c0869", Authority = new Authority(), }; mockGrpcClient.Setup(x => x.GetMembershipAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Membership>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Membership responseCallSettings = await client.GetMembershipAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Membership responseCancellationToken = await client.GetMembershipAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMembershipResourceNames() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMembershipRequest request = new GetMembershipRequest { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), }; Membership expectedResponse = new Membership { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", Endpoint = new MembershipEndpoint(), State = new MembershipState(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), ExternalId = "external_id9442680e", LastConnectionTime = new wkt::Timestamp(), UniqueId = "unique_idee0c0869", Authority = new Authority(), }; mockGrpcClient.Setup(x => x.GetMembership(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Membership response = client.GetMembership(request.MembershipName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMembershipResourceNamesAsync() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMembershipRequest request = new GetMembershipRequest { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), }; Membership expectedResponse = new Membership { MembershipName = MembershipName.FromProjectLocationMembership("[PROJECT]", "[LOCATION]", "[MEMBERSHIP]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", Endpoint = new MembershipEndpoint(), State = new MembershipState(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), ExternalId = "external_id9442680e", LastConnectionTime = new wkt::Timestamp(), UniqueId = "unique_idee0c0869", Authority = new Authority(), }; mockGrpcClient.Setup(x => x.GetMembershipAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Membership>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Membership responseCallSettings = await client.GetMembershipAsync(request.MembershipName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Membership responseCancellationToken = await client.GetMembershipAsync(request.MembershipName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFeatureRequestObject() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFeatureRequest request = new GetFeatureRequest { Name = "name1c9368b0", }; Feature expectedResponse = new Feature { FeatureName = FeatureName.FromProjectLocationFeature("[PROJECT]", "[LOCATION]", "[FEATURE]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ResourceState = new FeatureResourceState(), Spec = new CommonFeatureSpec(), MembershipSpecs = { { "key8a0b6e3c", new MembershipFeatureSpec() }, }, State = new CommonFeatureState(), MembershipStates = { { "key8a0b6e3c", new MembershipFeatureState() }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Feature response = client.GetFeature(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFeatureRequestObjectAsync() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFeatureRequest request = new GetFeatureRequest { Name = "name1c9368b0", }; Feature expectedResponse = new Feature { FeatureName = FeatureName.FromProjectLocationFeature("[PROJECT]", "[LOCATION]", "[FEATURE]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ResourceState = new FeatureResourceState(), Spec = new CommonFeatureSpec(), MembershipSpecs = { { "key8a0b6e3c", new MembershipFeatureSpec() }, }, State = new CommonFeatureState(), MembershipStates = { { "key8a0b6e3c", new MembershipFeatureState() }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Feature responseCallSettings = await client.GetFeatureAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Feature responseCancellationToken = await client.GetFeatureAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFeature() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFeatureRequest request = new GetFeatureRequest { Name = "name1c9368b0", }; Feature expectedResponse = new Feature { FeatureName = FeatureName.FromProjectLocationFeature("[PROJECT]", "[LOCATION]", "[FEATURE]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ResourceState = new FeatureResourceState(), Spec = new CommonFeatureSpec(), MembershipSpecs = { { "key8a0b6e3c", new MembershipFeatureSpec() }, }, State = new CommonFeatureState(), MembershipStates = { { "key8a0b6e3c", new MembershipFeatureState() }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Feature response = client.GetFeature(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFeatureAsync() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFeatureRequest request = new GetFeatureRequest { Name = "name1c9368b0", }; Feature expectedResponse = new Feature { FeatureName = FeatureName.FromProjectLocationFeature("[PROJECT]", "[LOCATION]", "[FEATURE]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ResourceState = new FeatureResourceState(), Spec = new CommonFeatureSpec(), MembershipSpecs = { { "key8a0b6e3c", new MembershipFeatureSpec() }, }, State = new CommonFeatureState(), MembershipStates = { { "key8a0b6e3c", new MembershipFeatureState() }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DeleteTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); Feature responseCallSettings = await client.GetFeatureAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Feature responseCancellationToken = await client.GetFeatureAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GenerateConnectManifestRequestObject() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GenerateConnectManifestRequest request = new GenerateConnectManifestRequest { Name = "name1c9368b0", Namespace = "namespace9e1e8089", Proxy = proto::ByteString.CopyFromUtf8("proxyeb871343"), Version = "version102ff72a", IsUpgrade = false, Registry = "registrycf5d20a9", ImagePullSecretContent = proto::ByteString.CopyFromUtf8("image_pull_secret_content89fc8e49"), }; GenerateConnectManifestResponse expectedResponse = new GenerateConnectManifestResponse { Manifest = { new ConnectAgentResource(), }, }; mockGrpcClient.Setup(x => x.GenerateConnectManifest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); GenerateConnectManifestResponse response = client.GenerateConnectManifest(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GenerateConnectManifestRequestObjectAsync() { moq::Mock<GkeHub.GkeHubClient> mockGrpcClient = new moq::Mock<GkeHub.GkeHubClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GenerateConnectManifestRequest request = new GenerateConnectManifestRequest { Name = "name1c9368b0", Namespace = "namespace9e1e8089", Proxy = proto::ByteString.CopyFromUtf8("proxyeb871343"), Version = "version102ff72a", IsUpgrade = false, Registry = "registrycf5d20a9", ImagePullSecretContent = proto::ByteString.CopyFromUtf8("image_pull_secret_content89fc8e49"), }; GenerateConnectManifestResponse expectedResponse = new GenerateConnectManifestResponse { Manifest = { new ConnectAgentResource(), }, }; mockGrpcClient.Setup(x => x.GenerateConnectManifestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateConnectManifestResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GkeHubClient client = new GkeHubClientImpl(mockGrpcClient.Object, null); GenerateConnectManifestResponse responseCallSettings = await client.GenerateConnectManifestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GenerateConnectManifestResponse responseCancellationToken = await client.GenerateConnectManifestAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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 Cake.Common.Tests.Fixtures.Tools.WiX; using Cake.Common.Tools.WiX.Heat; using Cake.Core; using Cake.Testing; using Cake.Testing.Xunit; using Xunit; namespace Cake.Common.Tests.Unit.Tools.WiX { public sealed class HeatRunnerTests { public sealed class TheConstructor { [Fact] public void Should_Throw_If_Environment_Is_Null() { // Given var fixture = new HeatFixture(); fixture.Environment = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "environment"); } } public sealed class TheRunMethod { [Fact] public void Should_Throw_If_Directory_Path_Empty() { // Given var fixture = new HeatFixture(); fixture.DirectoryPath = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<ArgumentNullException>(result); Assert.Equal("directoryPath", ((ArgumentException)result)?.ParamName); } [Fact] public void Should_Throw_If_Output_File_Empty() { // Given var fixture = new HeatFixture(); fixture.OutputFile = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<ArgumentNullException>(result); Assert.Equal("outputFile", ((ArgumentException)result)?.ParamName); } [Fact] public void Should_Set_Working_Directory() { // Given var fixture = new HeatFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working", result.Process.WorkingDirectory.FullPath); } // Not a Valid Test case based on the fixture setup public void Should_Throw_If_Settings_Is_Null() { // Given var fixture = new HeatFixture(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_Heat_Runner_Was_Not_Found() { // Given var fixture = new HeatFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Heat: Could not locate executable.", result?.Message); } [Theory] [InlineData("/bin/tools/WiX/heat.exe", "/bin/tools/WiX/heat.exe")] [InlineData("./tools/WiX/heat.exe", "/Working/tools/WiX/heat.exe")] public void Should_Use_Heat_Runner_From_Tool_Path_If_Provided(string toolPath, string excepted) { // Given var fixture = new HeatFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(excepted, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/WiX/heat.exe", "C:/WiX/heat.exe")] public void Should_Use_Heat_Runner_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected) { // Given var fixture = new HeatFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Fact] public void Should_Find_Heat_Runner_If_Tool_Path_Not_Provided() { // Given var fixture = new HeatFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/heat.exe", result.Path.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new HeatFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Heat: Process was not started.", result?.Message); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new HeatFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Heat: Process returned an error (exit code 1).", result?.Message); } [Fact] public void Should_Add_File_Harvest_Type_If_Provided() { // Given var fixture = new HeatFixture(); fixture.HarvestType = WiXHarvestType.File; // When var result = fixture.Run(); // Then Assert.Equal("file \"/Working/Cake.dll\" -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Website_Harvest_Type_If_Provided() { // Given var fixture = new HeatFixture(); fixture.HarvestType = WiXHarvestType.Website; // When var result = fixture.Run(); // Then Assert.Equal("website \"Default Web Site\" -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Performance_Harvest_Type_If_Provided() { // Given var fixture = new HeatFixture(); fixture.HarvestType = WiXHarvestType.Perf; fixture.HarvestTarget = "Cake Category"; // When var result = fixture.Run(); // Then Assert.Equal("perf \"Cake Category\" -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Extension_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Extensions = new[] { "WiXSecurityExtensions" }; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -ext WiXSecurityExtensions -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_NoLogo_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.NoLogo = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -nologo -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Suppress_Specific_Warnings_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressSpecificWarnings = new[] { "0001", "0002" }; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -sw0001 -sw0002 -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Treat_Specific_Warnings_As_Errors_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.TreatSpecificWarningsAsErrors = new[] { "1101", "1102" }; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -wx1101 -wx1102 -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Auto_Generate_Guid_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.AutogeneratedGuid = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -ag -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Component_Group_Name_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.ComponentGroupName = "CakeComponentGroup"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -cg CakeComponentGroup -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Configuration_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Configuration = "Release"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -configuration Release -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Directory_Id_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.DirectoryId = "CakeDirectoryId"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -directoryid CakeDirectoryId -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Directory_Reference_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.DirectoryReferenceId = "CakeAppDirectoryReference"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -dr CakeAppDirectoryReference -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Generate_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Generate = WiXGenerateType.Container; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -generate container -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Not_Add_Generate_To_Arguments_If_Default_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Generate = WiXGenerateType.Components; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Generate_Guid_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.GenerateGuid = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -gg -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Generate_Guid_Without_Braces_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.GenerateGuidWithoutBraces = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -g1 -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Keep_Empty_Directories_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.KeepEmptyDirectories = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -ke -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Platform_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Platform = "osx"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -platform osx -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Binaries_Output_Group_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.OutputGroup = WiXOutputGroupType.Binaries; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -pog Binaries -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Symbols_Output_Group_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.OutputGroup = WiXOutputGroupType.Symbols; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -pog Symbols -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Documents_Output_Group_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.OutputGroup = WiXOutputGroupType.Documents; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -pog Documents -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Satellites_Output_Group_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.OutputGroup = WiXOutputGroupType.Satellites; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -pog Satellites -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Sources_Output_Group_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.OutputGroup = WiXOutputGroupType.Sources; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -pog Sources -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Content_Output_Group_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.OutputGroup = WiXOutputGroupType.Content; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -pog Content -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Project_Name_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.ProjectName = "Cake.Project"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -projectname Cake.Project -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Suppress_Com_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressCom = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -scom -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Suppress_Fragments_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressFragments = true; // When var results = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -sfrag -out \"/Working/cake.wxs\"", results.Args); } [Fact] public void Should_Add_Suppress_Unique_Ids_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressUniqueIds = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -suid -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Suppress_Root_Directory_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressRootDirectory = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -srd -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Suppress_Registry_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressRegistry = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -sreg -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Suppress_Vb6_Com_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.SuppressVb6Com = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -svb6 -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Template_Type_Fragment_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Template = WiXTemplateType.Fragment; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -template fragment -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Template_Type_Module_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Template = WiXTemplateType.Module; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -template module -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Template_Type_Product_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Template = WiXTemplateType.Product; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -template product -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Transform_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Transform = "cake.xslt"; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -t \"cake.xslt\" -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Indent_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Indent = 5; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -indent 5 -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Verbose_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.Verbose = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -v -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Add_Generate_Binder_Variables_To_Arguments_If_Provided() { // Given var fixture = new HeatFixture(); fixture.Settings.GenerateBinderVariables = true; // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -wixvar -out \"/Working/cake.wxs\"", result.Args); } [Fact] public void Should_Default_To_Directory_Harvest_Type() { // Given var fixture = new HeatFixture(); // When var result = fixture.Run(); // Then Assert.Equal("dir \"/Working/src/Cake\" -out \"/Working/cake.wxs\"", result.Args); } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Zeus; using Zeus.Projects; namespace MyGeneration { /// <summary> /// Summary description for AddEditModule. /// </summary> public class FormAddEditModule : System.Windows.Forms.Form { private System.Windows.Forms.Label labelName; private System.Windows.Forms.Label labelDescription; private System.Windows.Forms.TextBox textBoxName; private System.Windows.Forms.TextBox textBoxDescription; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.ErrorProvider errorProviderRequiredFields; private ZeusModule _module; private bool _isActivated = false; private CheckBox checkBox1; private Label labelUserData; private DataGridView dataGridViewUserData; private DataGridViewTextBoxColumn ColumnName; private DataGridViewTextBoxColumn ColumnValue; private TabControl tabControl1; private TabPage tabPageUser; private TabPage tabPageCachedData; private DataGridView dataGridViewCache; private DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private IContainer components; public FormAddEditModule() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.labelName = new System.Windows.Forms.Label(); this.labelDescription = new System.Windows.Forms.Label(); this.textBoxName = new System.Windows.Forms.TextBox(); this.textBoxDescription = new System.Windows.Forms.TextBox(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonOK = new System.Windows.Forms.Button(); this.errorProviderRequiredFields = new System.Windows.Forms.ErrorProvider(this.components); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.labelUserData = new System.Windows.Forms.Label(); this.dataGridViewUserData = new System.Windows.Forms.DataGridView(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnValue = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPageUser = new System.Windows.Forms.TabPage(); this.tabPageCachedData = new System.Windows.Forms.TabPage(); this.dataGridViewCache = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)(this.errorProviderRequiredFields)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewUserData)).BeginInit(); this.tabControl1.SuspendLayout(); this.tabPageUser.SuspendLayout(); this.tabPageCachedData.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewCache)).BeginInit(); this.SuspendLayout(); // // labelName // this.labelName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelName.Location = new System.Drawing.Point(16, 8); this.labelName.Name = "labelName"; this.labelName.Size = new System.Drawing.Size(424, 23); this.labelName.TabIndex = 0; this.labelName.Text = "Name:"; this.labelName.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // labelDescription // this.labelDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelDescription.Location = new System.Drawing.Point(16, 56); this.labelDescription.Name = "labelDescription"; this.labelDescription.Size = new System.Drawing.Size(424, 23); this.labelDescription.TabIndex = 1; this.labelDescription.Text = "Description:"; this.labelDescription.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // textBoxName // this.textBoxName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxName.Location = new System.Drawing.Point(16, 32); this.textBoxName.Name = "textBoxName"; this.textBoxName.Size = new System.Drawing.Size(424, 20); this.textBoxName.TabIndex = 2; this.textBoxName.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxName_Validating); // // textBoxDescription // this.textBoxDescription.AcceptsReturn = true; this.textBoxDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxDescription.Location = new System.Drawing.Point(16, 80); this.textBoxDescription.Multiline = true; this.textBoxDescription.Name = "textBoxDescription"; this.textBoxDescription.Size = new System.Drawing.Size(424, 60); this.textBoxDescription.TabIndex = 3; // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.CausesValidation = false; this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(376, 419); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 4; this.buttonCancel.Text = "Cancel"; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.Location = new System.Drawing.Point(296, 419); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 5; this.buttonOK.Text = "OK"; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // errorProviderRequiredFields // this.errorProviderRequiredFields.ContainerControl = this; // // checkBox1 // this.checkBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.checkBox1.AutoSize = true; this.checkBox1.Location = new System.Drawing.Point(19, 396); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(229, 17); this.checkBox1.TabIndex = 6; this.checkBox1.Text = "Override Saved Data With Default Settings"; this.checkBox1.UseVisualStyleBackColor = true; // // labelUserData // this.labelUserData.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelUserData.Location = new System.Drawing.Point(12, 143); this.labelUserData.Name = "labelUserData"; this.labelUserData.Size = new System.Drawing.Size(424, 23); this.labelUserData.TabIndex = 7; this.labelUserData.Text = "User Override Data:"; this.labelUserData.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // dataGridViewUserData // this.dataGridViewUserData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridViewUserData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewUserData.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnName, this.ColumnValue}); this.dataGridViewUserData.Location = new System.Drawing.Point(6, 6); this.dataGridViewUserData.Name = "dataGridViewUserData"; this.dataGridViewUserData.Size = new System.Drawing.Size(405, 183); this.dataGridViewUserData.TabIndex = 8; // // ColumnName // this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.ColumnName.HeaderText = "Name"; this.ColumnName.Name = "ColumnName"; // // ColumnValue // this.ColumnValue.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.ColumnValue.HeaderText = "Value"; this.ColumnValue.Name = "ColumnValue"; // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPageUser); this.tabControl1.Controls.Add(this.tabPageCachedData); this.tabControl1.Location = new System.Drawing.Point(15, 169); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(425, 221); this.tabControl1.TabIndex = 9; // // tabPageUser // this.tabPageUser.Controls.Add(this.dataGridViewUserData); this.tabPageUser.Location = new System.Drawing.Point(4, 22); this.tabPageUser.Name = "tabPageUser"; this.tabPageUser.Padding = new System.Windows.Forms.Padding(3); this.tabPageUser.Size = new System.Drawing.Size(417, 195); this.tabPageUser.TabIndex = 0; this.tabPageUser.Text = "User Runtime Override Data"; this.tabPageUser.UseVisualStyleBackColor = true; // // tabPageCachedData // this.tabPageCachedData.Controls.Add(this.dataGridViewCache); this.tabPageCachedData.Location = new System.Drawing.Point(4, 22); this.tabPageCachedData.Name = "tabPageCachedData"; this.tabPageCachedData.Padding = new System.Windows.Forms.Padding(3); this.tabPageCachedData.Size = new System.Drawing.Size(417, 195); this.tabPageCachedData.TabIndex = 1; this.tabPageCachedData.Text = "Module Cached Data"; this.tabPageCachedData.UseVisualStyleBackColor = true; // // dataGridViewCache // this.dataGridViewCache.AllowUserToAddRows = false; this.dataGridViewCache.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridViewCache.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewCache.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn1, this.dataGridViewTextBoxColumn2}); this.dataGridViewCache.Location = new System.Drawing.Point(6, 6); this.dataGridViewCache.Name = "dataGridViewCache"; this.dataGridViewCache.ReadOnly = true; this.dataGridViewCache.Size = new System.Drawing.Size(405, 183); this.dataGridViewCache.TabIndex = 9; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn1.HeaderText = "Name"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn2.HeaderText = "Value"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; // // FormAddEditModule // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(460, 449); this.Controls.Add(this.tabControl1); this.Controls.Add(this.labelUserData); this.Controls.Add(this.checkBox1); this.Controls.Add(this.buttonOK); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.textBoxDescription); this.Controls.Add(this.textBoxName); this.Controls.Add(this.labelDescription); this.Controls.Add(this.labelName); this.Name = "FormAddEditModule"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Add/Edit Project Folder"; this.Load += new System.EventHandler(this.FormAddEditModule_Load); this.Activated += new System.EventHandler(this.FormAddEditModule_Activated); ((System.ComponentModel.ISupportInitialize)(this.errorProviderRequiredFields)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewUserData)).EndInit(); this.tabControl1.ResumeLayout(false); this.tabPageUser.ResumeLayout(false); this.tabPageCachedData.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewCache)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public ZeusModule Module { get { return _module; } set { _module = value; if(_module.Name != null) { this.textBoxName.Text = _module.Name; this.Text = "Folder: " + _module.Name; } else { this.textBoxName.Text = string.Empty; this.Text = "Folder: [New] "; } if(_module.Description != null) this.textBoxDescription.Text = _module.Description; else this.textBoxDescription.Text = string.Empty; this.checkBox1.Checked = this.Module.DefaultSettingsOverride; this.dataGridViewUserData.Rows.Clear(); foreach (InputItem item in this._module.UserSavedItems) { int newIndex = this.dataGridViewUserData.Rows.Add(); DataGridViewRow r = this.dataGridViewUserData.Rows[newIndex]; r.Cells[0].Value = item.VariableName; r.Cells[1].Value = item.Data; r.Cells[1].ToolTipText = item.DataTypeName; } this.dataGridViewCache.Rows.Clear(); foreach (InputItem item in this._module.SavedItems) { int newIndex = this.dataGridViewCache.Rows.Add(); DataGridViewRow r = this.dataGridViewCache.Rows[newIndex]; r.Cells[0].Value = item.VariableName; r.Cells[1].Value = item.Data; r.Cells[1].ToolTipText = item.DataTypeName; } this._isActivated = false; } } private void buttonOK_Click(object sender, System.EventArgs e) { CancelEventArgs args = new CancelEventArgs(); this.textBoxName_Validating(this, args); if (!args.Cancel) { this.Module.Name = this.textBoxName.Text; if (this.textBoxDescription.Text.Length > 0) { this.Module.Description = this.textBoxDescription.Text; } this.Module.DefaultSettingsOverride = this.checkBox1.Checked; this.Module.UserSavedItems.Clear(); foreach (DataGridViewRow r in dataGridViewUserData.Rows) { if (r.Cells.Count >= 2) { string key = r.Cells[0].Value as string; string val = r.Cells[1].Value as string; if (!string.IsNullOrEmpty(key)) { InputItem item = new InputItem(); if (string.IsNullOrEmpty(val)) val = string.Empty; item.VariableName = key.Trim(); item.Data = val.Trim(); item.DataType = typeof(String); _module.UserSavedItems[key] = item; } } } ArrayList keys = new ArrayList(); ArrayList keysToDelete = new ArrayList(); foreach (DataGridViewRow r in dataGridViewCache.Rows) { if (r.Cells.Count >= 2) { string key = r.Cells[0].Value as string; if (!string.IsNullOrEmpty(key)) { keys.Add(key); } } } foreach (InputItem item in this._module.SavedItems) { if (!keys.Contains(item.VariableName)) { keysToDelete.Add(item.VariableName); } } foreach (string varname in keysToDelete) { this.Module.SavedItems.Remove(varname); } this.DialogResult = DialogResult.OK; this.Close(); } } private void textBoxName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { if (this.textBoxName.Text.Trim() == string.Empty) { e.Cancel = true; this.errorProviderRequiredFields.SetError(this.textBoxName, "Name is Required!"); } else { this.errorProviderRequiredFields.SetError(this.textBoxName, string.Empty); } } private void buttonCancel_Click(object sender, System.EventArgs e) { this.Close(); } private void FormAddEditModule_Load(object sender, System.EventArgs e) { this.errorProviderRequiredFields.SetError(this.textBoxName, string.Empty); this.errorProviderRequiredFields.SetIconAlignment(this.textBoxName, ErrorIconAlignment.TopRight); } private void FormAddEditModule_Activated(object sender, System.EventArgs e) { if (!this._isActivated) { this.textBoxName.Focus(); this._isActivated = true; } } } }
#region License /* * WebSocketServer.cs * * A C# implementation of the WebSocket protocol server. * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contributors /* * Contributors: * - Juan Manuel Lallana <juan.manuel.lallana@gmail.com> * - Jonas Hovgaard <j@jhovgaard.dk> * - Liryna <liryna.stark@gmail.com> * - Rohan Singh <rohan-singh@hotmail.com> */ #endregion using System; using System.Collections.Generic; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using System.Threading; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Provides a WebSocket protocol server. /// </summary> /// <remarks> /// The WebSocketServer class can provide multiple WebSocket services. /// </remarks> public class WebSocketServer { #region Private Fields private System.Net.IPAddress _address; private AuthenticationSchemes _authSchemes; private Func<IIdentity, NetworkCredential> _credFinder; private bool _dnsStyle; private string _hostname; private TcpListener _listener; private Logger _logger; private int _port; private string _realm; private Thread _receiveThread; private bool _reuseAddress; private bool _secure; private WebSocketServiceManager _services; private ServerSslConfiguration _sslConfig; private volatile ServerState _state; private object _sync; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming connection requests on /// port 80. /// </remarks> public WebSocketServer () { init (null, System.Net.IPAddress.Any, 80, false); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming connection requests /// on <paramref name="port"/>. /// </para> /// <para> /// If <paramref name="port"/> is 443, that instance provides a secure connection. /// </para> /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (int port) : this (port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified WebSocket URL. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming connection requests /// on the host name and port in <paramref name="url"/>. /// </para> /// <para> /// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on /// which to listen. It's determined by the scheme (ws or wss) in <paramref name="url"/>. /// (Port 80 if the scheme is ws.) /// </para> /// </remarks> /// <param name="url"> /// A <see cref="string"/> that represents the WebSocket URL of the server. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="url"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="url"/> is invalid. /// </para> /// </exception> public WebSocketServer (string url) { if (url == null) throw new ArgumentNullException ("url"); if (url.Length == 0) throw new ArgumentException ("An empty string.", "url"); Uri uri; string msg; if (!tryCreateUri (url, out uri, out msg)) throw new ArgumentException (msg, "url"); var host = uri.DnsSafeHost; var addr = host.ToIPAddress (); if (!addr.IsLocal ()) throw new ArgumentException ("The host part isn't a local host name: " + url, "url"); init (host, addr, uri.Port, uri.Scheme == "wss"); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="port"/> and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming connection requests on /// <paramref name="port"/>. /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (int port, bool secure) { if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init (null, System.Net.IPAddress.Any, port, secure); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="address"/> and <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming connection requests /// on <paramref name="address"/> and <paramref name="port"/>. /// </para> /// <para> /// If <paramref name="port"/> is 443, that instance provides a secure connection. /// </para> /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (System.Net.IPAddress address, int port) : this (address, port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class with /// the specified <paramref name="address"/>, <paramref name="port"/>, /// and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming connection requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public WebSocketServer (System.Net.IPAddress address, int port, bool secure) { if (address == null) throw new ArgumentNullException ("address"); if (!address.IsLocal ()) throw new ArgumentException ("Not a local IP address: " + address, "address"); if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init (null, address, port, secure); } #endregion #region Public Properties /// <summary> /// Gets the local IP address of the server. /// </summary> /// <value> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </value> public System.Net.IPAddress Address { get { return _address; } } /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <value> /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values, /// indicates the scheme used to authenticate the clients. The default value is /// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// </value> public AuthenticationSchemes AuthenticationSchemes { get { return _authSchemes; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _authSchemes = value; } } /// <summary> /// Gets a value indicating whether the server has started. /// </summary> /// <value> /// <c>true</c> if the server has started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _state == ServerState.Start; } } /// <summary> /// Gets a value indicating whether the server provides a secure connection. /// </summary> /// <value> /// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>. /// </value> public bool IsSecure { get { return _secure; } } /// <summary> /// Gets or sets a value indicating whether the server cleans up /// the inactive sessions periodically. /// </summary> /// <value> /// <c>true</c> if the server cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. The default value is <c>true</c>. /// </value> public bool KeepClean { get { return _services.KeepClean; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _services.KeepClean = value; } } /// <summary> /// Gets the logging functions. /// </summary> /// <remarks> /// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it, /// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum /// values. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging functions. /// </value> public Logger Log { get { return _logger; } } /// <summary> /// Gets the port on which to listen for incoming connection requests. /// </summary> /// <value> /// An <see cref="int"/> that represents the port number on which to listen. /// </value> public int Port { get { return _port; } } /// <summary> /// Gets or sets the name of the realm associated with the server. /// </summary> /// <value> /// A <see cref="string"/> that represents the name of the realm. The default value is /// <c>"SECRET AREA"</c>. /// </value> public string Realm { get { return _realm ?? (_realm = "SECRET AREA"); } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _realm = value; } } /// <summary> /// Gets or sets a value indicating whether the server is allowed to be bound to /// an address that is already in use. /// </summary> /// <remarks> /// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state, /// you should set this property to <c>true</c>. /// </remarks> /// <value> /// <c>true</c> if the server is allowed to be bound to an address that is already in use; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> public bool ReuseAddress { get { return _reuseAddress; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _reuseAddress = value; } } /// <summary> /// Gets or sets the SSL configuration used to authenticate the server and /// optionally the client for secure connection. /// </summary> /// <value> /// A <see cref="ServerSslConfiguration"/> that represents the configuration used to /// authenticate the server and optionally the client for secure connection. /// </value> public ServerSslConfiguration SslConfiguration { get { return _sslConfig ?? (_sslConfig = new ServerSslConfiguration (null)); } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _sslConfig = value; } } /// <summary> /// Gets or sets the delegate called to find the credentials for an identity used to /// authenticate a client. /// </summary> /// <value> /// A <c>Func&lt;<see cref="IIdentity"/>, <see cref="NetworkCredential"/>&gt;</c> delegate that /// references the method(s) used to find the credentials. The default value is a function that /// only returns <see langword="null"/>. /// </value> public Func<IIdentity, NetworkCredential> UserCredentialsFinder { get { return _credFinder ?? (_credFinder = identity => null); } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _credFinder = value; } } /// <summary> /// Gets or sets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. The default value is /// the same as 1 second. /// </value> public TimeSpan WaitTime { get { return _services.WaitTime; } set { var msg = _state.CheckIfAvailable (true, false, false) ?? value.CheckIfValidWaitTime (); if (msg != null) { _logger.Error (msg); return; } _services.WaitTime = value; } } /// <summary> /// Gets the access to the WebSocket services provided by the server. /// </summary> /// <value> /// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services. /// </value> public WebSocketServiceManager WebSocketServices { get { return _services; } } #endregion #region Private Methods private void abort () { lock (_sync) { if (!IsListening) return; _state = ServerState.ShuttingDown; } _listener.Stop (); _services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false); _state = ServerState.Stop; } private static bool authenticate ( TcpListenerWebSocketContext context, AuthenticationSchemes scheme, string realm, Func<IIdentity, NetworkCredential> credentialsFinder) { var chal = scheme == AuthenticationSchemes.Basic ? AuthenticationChallenge.CreateBasicChallenge (realm).ToBasicString () : scheme == AuthenticationSchemes.Digest ? AuthenticationChallenge.CreateDigestChallenge (realm).ToDigestString () : null; if (chal == null) { context.Close (HttpStatusCode.Forbidden); return false; } var retry = -1; Func<bool> auth = null; auth = () => { retry++; if (retry > 99) { context.Close (HttpStatusCode.Forbidden); return false; } var user = HttpUtility.CreateUser ( context.Headers["Authorization"], scheme, realm, context.HttpMethod, credentialsFinder); if (user != null && user.Identity.IsAuthenticated) { context.SetUser (user); return true; } context.SendAuthenticationChallenge (chal); return auth (); }; return auth (); } private string checkIfCertificateExists () { return _secure && (_sslConfig == null || _sslConfig.ServerCertificate == null) ? "The secure connection requires a server certificate." : null; } private void init (string hostname, System.Net.IPAddress address, int port, bool secure) { _hostname = hostname ?? address.ToString (); _address = address; _port = port; _secure = secure; _authSchemes = AuthenticationSchemes.Anonymous; _dnsStyle = Uri.CheckHostName (hostname) == UriHostNameType.Dns; _listener = new TcpListener (address, port); _logger = new Logger (); _services = new WebSocketServiceManager (_logger); _sync = new object (); } private void processRequest (TcpListenerWebSocketContext context) { var uri = context.RequestUri; if (uri == null || uri.Port != _port) { context.Close (HttpStatusCode.BadRequest); return; } if (_dnsStyle) { var hostname = uri.DnsSafeHost; if (Uri.CheckHostName (hostname) == UriHostNameType.Dns && hostname != _hostname) { context.Close (HttpStatusCode.NotFound); return; } } WebSocketServiceHost host; if (!_services.InternalTryGetServiceHost (uri.AbsolutePath, out host)) { context.Close (HttpStatusCode.NotImplemented); return; } host.StartSession (context); } private void receiveRequest () { while (true) { try { var cl = _listener.AcceptTcpClient (); ThreadPool.QueueUserWorkItem ( state => { try { var ctx = cl.GetWebSocketContext (null, _secure, _sslConfig, _logger); if (_authSchemes != AuthenticationSchemes.Anonymous && !authenticate (ctx, _authSchemes, Realm, UserCredentialsFinder)) return; processRequest (ctx); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); cl.Close (); } }); } catch (SocketException ex) { _logger.Warn ("Receiving has been stopped.\n reason: " + ex.Message); break; } catch (Exception ex) { _logger.Fatal (ex.ToString ()); break; } } if (IsListening) abort (); } private void startReceiving () { if (_reuseAddress) _listener.Server.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _listener.Start (); _receiveThread = new Thread (new ThreadStart (receiveRequest)); _receiveThread.IsBackground = true; _receiveThread.Start (); } private void stopReceiving (int millisecondsTimeout) { _listener.Stop (); _receiveThread.Join (millisecondsTimeout); } private static bool tryCreateUri (string uriString, out Uri result, out string message) { if (!uriString.TryCreateWebSocketUri (out result, out message)) return false; if (result.PathAndQuery != "/") { result = null; message = "Includes the path or query component: " + uriString; return false; } return true; } #endregion #region Public Methods /// <summary> /// Adds a WebSocket service with the specified behavior, <paramref name="path"/>, /// and <paramref name="initializer"/>. /// </summary> /// <remarks> /// <para> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </para> /// <para> /// <paramref name="initializer"/> returns an initialized specified typed /// <see cref="WebSocketBehavior"/> instance. /// </para> /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to add. /// </param> /// <param name="initializer"> /// A <c>Func&lt;T&gt;</c> delegate that references the method used to initialize /// a new specified typed <see cref="WebSocketBehavior"/> instance (a new /// <see cref="IWebSocketSession"/> instance). /// </param> /// <typeparam name="TBehavior"> /// The type of the behavior of the service to add. The TBehavior must inherit /// the <see cref="WebSocketBehavior"/> class. /// </typeparam> public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer) where TBehavior : WebSocketBehavior { var msg = path.CheckIfValidServicePath () ?? (initializer == null ? "'initializer' is null." : null); if (msg != null) { _logger.Error (msg); return; } _services.Add<TBehavior> (path, initializer); } /// <summary> /// Adds a WebSocket service with the specified behavior and <paramref name="path"/>. /// </summary> /// <remarks> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to add. /// </param> /// <typeparam name="TBehaviorWithNew"> /// The type of the behavior of the service to add. The TBehaviorWithNew must inherit /// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless /// constructor. /// </typeparam> public void AddWebSocketService<TBehaviorWithNew> (string path) where TBehaviorWithNew : WebSocketBehavior, new () { AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ()); } /// <summary> /// Removes the WebSocket service with the specified <paramref name="path"/>. /// </summary> /// <remarks> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to find. /// </param> public bool RemoveWebSocketService (string path) { var msg = path.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } return _services.Remove (path); } /// <summary> /// Starts receiving the WebSocket connection requests. /// </summary> public void Start () { lock (_sync) { var msg = _state.CheckIfAvailable (true, false, false) ?? checkIfCertificateExists (); if (msg != null) { _logger.Error (msg); return; } _services.Start (); startReceiving (); _state = ServerState.Start; } } /// <summary> /// Stops receiving the WebSocket connection requests. /// </summary> public void Stop () { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } stopReceiving (5000); _services.Stop (new CloseEventArgs (), true, true); _state = ServerState.Stop; } /// <summary> /// Stops receiving the WebSocket connection requests with /// the specified <see cref="ushort"/> and <see cref="string"/>. /// </summary> /// <param name="code"> /// A <see cref="ushort"/> that represents the status code indicating the reason for the stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the stop. /// </param> public void Stop (ushort code, string reason) { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckCloseParameters (code, reason, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } stopReceiving (5000); if (code == (ushort) CloseStatusCode.NoStatus) { _services.Stop (new CloseEventArgs (), true, true); } else { var send = !code.IsReserved (); _services.Stop (new CloseEventArgs (code, reason), send, send); } _state = ServerState.Stop; } /// <summary> /// Stops receiving the WebSocket connection requests with /// the specified <see cref="CloseStatusCode"/> and <see cref="string"/>. /// </summary> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating /// the reason for the stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the stop. /// </param> public void Stop (CloseStatusCode code, string reason) { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckCloseParameters (code, reason, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } stopReceiving (5000); if (code == CloseStatusCode.NoStatus) { _services.Stop (new CloseEventArgs (), true, true); } else { var send = !code.IsReserved (); _services.Stop (new CloseEventArgs (code, reason), send, send); } _state = ServerState.Stop; } #endregion } }
#define USE_IL_GENERATOR_DEBUG using System; using System.Collections.Generic; using System.Data; using System.Reflection; using System.Reflection.Emit; #if USE_IL_GENERATOR_DEBUG using FdwIlGenerator = fdw.Common.Data.DebugIlGenerator; #else using FdwIlGenerator = System.Reflection.Emit.ILGenerator; #endif namespace fdw.Common.Data { /// <summary> /// Represents the base of all IL code-generation utility classes. /// </summary> /// <typeparam name="TType">The class type utilized by the Populator instance.</typeparam> /// <typeparam name="TDataReader">The IDataReader-derived type utilized by the Populator instance.</typeparam> public abstract class CodeBase<TType, TDataReader> where TType : class where TDataReader : class, IDataReader { private readonly IDictionary<Type, int> _typesToArguments; private readonly IDictionary<Type, int> _typeToLocalOffset; private readonly Populator<TType, TDataReader> _populator; private readonly Stack<Op> _opCodes; protected CodeBase(Populator<TType, TDataReader> populator) : this(populator, new Stack<Op>(), new Dictionary<Type, int> { { typeof(TDataReader), 0 } }, new Dictionary<Type, int>()) { // } protected CodeBase(Populator<TType, TDataReader> populator, Stack<Op> opCodes, IDictionary<Type, int> typesToArguments, IDictionary<Type, int> typesToLocalOffset) { _typesToArguments = typesToArguments; _typeToLocalOffset = typesToLocalOffset; _populator = populator; _opCodes = opCodes; } public IDictionary<Type, int> TypesToArguments { get { return _typesToArguments; } } public IDictionary<Type, int> TypesToLocalOffset { get { return _typeToLocalOffset; } } public Populator<TType, TDataReader> Populator { get { return _populator; } } public FdwIlGenerator Generator { get { return _populator.Generator; } } public Stack<Op> OpCodes { get { return _opCodes; } } public abstract CodeBaseParameter<TType, TDataReader> Call<TArg1, TOut>(MethodInfo mi, int constant); public abstract CodeBaseParameter<TType, TDataReader> Call<TArg1, TOut>(MethodInfo mi); public virtual CodeBase<TType, TDataReader> MarkLabel(Label label) { // Horrible, ugly hack. See the Emit method for details. OpCodes.Push(new Op(System.Reflection.Emit.OpCodes.Nop, label)); return this; } public CodeBase<TType, TDataReader> DeclareTypeOf(Type type) { var mi = typeof(CodeBaseBody<TType, TDataReader>).GetMethod("DeclareTypeOf", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); mi = mi.MakeGenericMethod(type); return (CodeBaseBody<TType, TDataReader>)mi.Invoke(this, null); } public CodeBase<TType, TDataReader> DeclareTypeOf<TVar>() { if (!_typeToLocalOffset.ContainsKey(typeof(TVar))) { var offset = Populator.IntroduceVariableOf(typeof(TVar)); _typeToLocalOffset.Add(typeof(TVar), offset); } return this; } public CodeBase<TType, TDataReader> InitializeValueTypeOf(Type type) { var mi = typeof(CodeBaseBody<TType, TDataReader>).GetMethod("InitializeValueTypeOf", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); mi = mi.MakeGenericMethod(type); return (CodeBaseBody<TType, TDataReader>)mi.Invoke(this, null); } public CodeBase<TType, TDataReader> InitializeValueTypeOf<TTypeToInitialize>() { DeclareTypeOf<TTypeToInitialize>(); OpCodes.Push(new Op(System.Reflection.Emit.OpCodes.Ldloca_S, TypesToLocalOffset[typeof(TTypeToInitialize)])); OpCodes.Push(new Op(System.Reflection.Emit.OpCodes.Initobj, typeof(TTypeToInitialize))); return this; } public CodeBase<TType, TDataReader> New(ConstructorInfo ctor) { OpCodes.Push(new Op(System.Reflection.Emit.OpCodes.Newobj, ctor)); return this; } public CodeBase<TType, TDataReader> New<TTypeToConstruct>(ConstructorInfo ctor) { return DeclareTypeOf<TTypeToConstruct>().New(ctor); } public virtual CodeBaseMethod<TType, TDataReader> Call(MethodInfo mi) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method; } public virtual CodeBaseMethod<TType, TDataReader> Call<TArg>(MethodInfo mi, bool dummy) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); method.In<TArg>(); OpCodes.Push(mi.IsStatic ? new Op(System.Reflection.Emit.OpCodes.Call, mi) : new Op(System.Reflection.Emit.OpCodes.Callvirt, mi)); return method; } public virtual CodeBaseParameter<TType, TDataReader> Call<TArg1>(Type returnType, MethodInfo mi, int constant) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method.In<TArg1>().In(constant).Out(returnType); } public virtual CodeBaseParameter<TType, TDataReader> Call<TOut>(MethodInfo mi, int constant) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method.In(constant).Out<TOut>(); } public virtual CodeBaseParameter<TType, TDataReader> Call<TArg1, TArg2, TOut>(MethodInfo mi, int constant) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method.In<TArg1>().In<TArg2>().In(constant).Out<TOut>(); } public virtual CodeBaseParameter<TType, TDataReader> Call<TArg1, TArg2, TOut>(MethodInfo mi) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method.In<TArg1>().In<TArg2>().Out<TOut>(); } public virtual CodeBaseParameter<TType, TDataReader> Call<TArg1, TArg2, TArg3, TOut>(MethodInfo mi) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method.In<TArg1>().In<TArg2>().In<TArg3>().Out<TOut>(); } public virtual CodeBaseParameter<TType, TDataReader> Call<TOut>(MethodInfo mi) { var method = new CodeBaseMethod<TType, TDataReader>((CodeBaseBody<TType, TDataReader>)this, mi); return method.Out<TOut>(); } public virtual CodeBase<TType, TDataReader> LoadConstant(int constant) { var opcode = IlGeneratorExtensions.GetEmitLdcOpcode(constant); OpCodes.Push(new Op(opcode, opcode == System.Reflection.Emit.OpCodes.Ldc_I4 ? (object)constant : null)); return this; } /// <summary> /// Creates a load instruction. Depending on the arguments or locality of the type, may load the value /// from the function parameter or from the function local variables. /// </summary> /// <example> /// The following example generates a load instruction. /// <code> /// Load&lt;int&gt;() /// </code> /// The generated IL is similar to: /// <code> /// ldloc.0 /// </code> /// ... Or... /// <code> /// ldarg.0 /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// void foo() { /// var i = 0; // or whatever's on the stack /// } /// </code> /// ... Or... /// <code> /// void foo(int arg1) { /// var i = arg1; /// } /// </code> /// </example> /// <typeparam name="TTypeToLoad">The type of variable to load</typeparam> /// <returns>The current CodeBase instance</returns> public virtual CodeBase<TType, TDataReader> Load<TTypeToLoad>() { int offset; OpCode opcode; if (Populator.Arguments.ContainsKey(typeof(TTypeToLoad))) { offset = Populator.Arguments[typeof(TTypeToLoad)]; opcode = IlGeneratorExtensions.GetEmitLdArgOpCode(offset); } else { DeclareTypeOf<TTypeToLoad>(); offset = TypesToLocalOffset[typeof(TTypeToLoad)]; opcode = IlGeneratorExtensions.GetEmitLdlocOpCode(offset); } OpCodes.Push(new Op(opcode, (opcode == System.Reflection.Emit.OpCodes.Ldloc || opcode == System.Reflection.Emit.OpCodes.Ldarg) ? (object)offset : null)); return this; } /// <summary> /// Helper function around <see cref="Load"/> with an argument type of Type. The Type is converted to the generic /// type syntax and invoked. Slightly less efficient than the generic version. Utilize the generic Load method /// whenever possible. /// </summary> /// <param name="type">The type of variable to load</param> /// <returns>The current CodeBase instance</returns> public virtual CodeBase<TType, TDataReader> Load(Type type) { var mi = typeof(CodeBaseBody<TType, TDataReader>).GetMethod("Load", BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null); mi = mi.MakeGenericMethod(type); return (CodeBaseBody<TType, TDataReader>)mi.Invoke(this, null); } /// <summary> /// Creates a store instruction to a class field. /// </summary> /// <example> /// The following example generates a store field instruction. Assume a class with a field <c>f</c>. /// <code> /// var f = instance.GetType().GetProperty(&quot;f&quot;); /// StoreInField(f); /// </code> /// The generated IL is similar to: /// <code> /// stfld /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// instance.f = value; /// </code> /// </example> /// <param name="fi">The <see cref="FieldInfo"/> field which will store the value</param> /// <returns>The current CodeBase instance</returns> public virtual CodeBase<TType, TDataReader> StoreInField(FieldInfo fi) { OpCodes.Push(new Op(System.Reflection.Emit.OpCodes.Stfld, fi)); return this; } /// <summary> /// Creates a store instruction which pops the current value from the top of the stack and stores it in the /// local function location declared by the type provided. This is equivalent to declaring a variable and /// storing a value in the declared location. /// </summary> /// <example> /// The following example generates a store instruction to an integer. /// <code> /// Store&lt;int&gt;() /// </code> /// The generated IL is similar to: /// <code> /// stloc.0 /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// int i = 0: /// </code> /// </example> /// <typeparam name="TTypeToStore">The type to store</typeparam> /// <returns>The current CodeBase instance</returns> public virtual CodeBase<TType, TDataReader> Store<TTypeToStore>() { DeclareTypeOf<TType>(); var offset = TypesToLocalOffset[typeof(TTypeToStore)]; var opcode = IlGeneratorExtensions.GetEmitStLocOpCode(offset); OpCodes.Push(new Op(opcode, opcode == System.Reflection.Emit.OpCodes.Stloc ? (object)offset : null)); return this; } /// <summary> /// Creates an instruction equivalent to a short branch. The jump is handled by the provided delegate. /// </summary> /// <example> /// The following example generates an unconditional jump-to instruction to a label defined by labelLoad. /// <code> /// Jump((c, op) => c.JumpTo(op, labelLoad)) /// </code> /// The generated IL is similar to: /// <code> /// br.s SOME_LABEL /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// goto label; /// // some code /// label: /// </code> /// </example> /// <param name="fn">The delegate to handle the branch</param> /// <returns>Returns the CodeBase instance returned by the delegate</returns> public virtual CodeBase<TType, TDataReader> Jump(Func<CodeBase<TType, TDataReader>, OpCode, CodeBase<TType, TDataReader>> fn) { if (fn != null) { return fn(this, System.Reflection.Emit.OpCodes.Br_S); } throw new NotImplementedException(); } /// <summary> /// Creates an instruction for the specified label, most likely a branching instruction. Primarily utilized by the /// conditional branch commands such as a <c>IfTrue</c>. /// </summary> /// <param name="opcode">The IL Opcode to push onto the stack, most likely a branching instruction</param> /// <param name="label">The label associated with the opcode</param> /// <returns>The current CodeBase instance</returns> public CodeBase<TType, TDataReader> JumpTo(OpCode opcode, Label label) { OpCodes.Push(new Op(opcode, label)); return this; } /// <summary> /// Creates an instruction equivalent to a a short branch True. The jump is handled by the provided delegate. /// </summary> /// <example> /// The following example generates a jump-to instruction to a label defined by labelLoad if the prior stack-state value /// is true, not-null or non-zero. /// <code> /// IfTrue((c, op) => c.JumpTo(op, labelLoad)) /// </code> /// The generated IL is similar to: /// <code> /// brtrue.s SOME_LABEL /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// if(true) { /// // SOME_LABEL /// } /// </code> /// </example> /// <param name="fn">The delegate to handle the true case</param> /// <returns>Returns the CodeBase instance returned by the delegate</returns> public CodeBase<TType, TDataReader> IfTrue(Func<CodeBase<TType, TDataReader>, OpCode, CodeBase<TType, TDataReader>> fn) { if (fn != null) return fn(this, System.Reflection.Emit.OpCodes.Brtrue_S); throw new NotImplementedException(); } /// <summary> /// Creates an instruction equivalent to a short branch if-less-than-or-equal-to the provided constant value. The jump is handled by the provided delegate. /// </summary> /// <example> /// The following example generates a jump-to instruction to a label defined by labelLoad if the prior stack-state value is /// less-than-or-equal to 0 (0 is pushed onto the stack). /// <code>IfLessThanOrEqualTo(0, (c, op) => c.JumpTo(op, labelLoad))</code> /// The generated IL is similar to: /// <code> /// ble.s SOME_LABEL /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// if(x &lt;= 0) { /// // SOME_LABEL /// } /// </code> /// </example> /// <param name="constant"></param> /// <param name="fn">The delegate to handle the true case</param> /// <returns>Returns the CodeBase instance returned by the delegate</returns> public CodeBase<TType, TDataReader> IfLessThanOrEqualTo(int constant, Func<CodeBase<TType, TDataReader>, OpCode, CodeBase<TType, TDataReader>> fn) { return LoadConstant(constant).IfLessThanOrEqual(fn); } /// <summary> /// Creates an instruction equivalent to a short branch if-less-than-or-equal-to. The jump is handled by the provided delegate. /// </summary> /// <example> /// The following example generates a jump-to instruction to a label defined by labelLoad against the two values on top of the /// stack. /// <code>IfLessThanOrEqualTo((c, op) => c.JumpTo(op, labelLoad))</code> /// The generated IL is similar to: /// <code> /// ble.s SOME_LABEL /// </code> /// ... and can be (roughly) expressed imparitively as: /// <code> /// if(x &lt;= y) { /// // SOME_LABEL /// } /// </code> /// </example> /// <param name="fn">The delegate to handle the true case</param> /// <returns>Returns the CodeBase instance returned by the delegate</returns> public CodeBase<TType, TDataReader> IfLessThanOrEqual(Func<CodeBase<TType, TDataReader>, OpCode, CodeBase<TType, TDataReader>> fn) { if (fn != null) return fn(this, System.Reflection.Emit.OpCodes.Ble_S); throw new NotImplementedException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.CompilerServices; using System.IO; using System.Text; using Xunit; public class FileInfo_Create_str { public static String s_strDtTmVer = "2009/02/18"; public static String s_strClassMethod = "FileInfo.Create"; public static String s_strTFName = "Create_str.cs"; public static String s_strTFPath = Directory.GetCurrentDirectory(); [Fact] public static void runTest() { int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { FileInfo file2 = null; Stream fs2; String fileName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName()); try { new FileInfo(fileName).Delete(); } catch (Exception) { } strLoc = "Loc_099u8"; // [] Create a File with '.'. iCountTestcases++; file2 = new FileInfo("."); try { file2.Create(); iCountErrors++; printerr("Error_298dy! Expected exception not thrown, file2==" + file2.FullName); file2.Delete(); } catch (UnauthorizedAccessException) { } catch (Exception exc) { iCountErrors++; printerr("Error_209xj! Incorrect exception thrown, exc==" + exc.ToString()); } // [] Try to create an existing file. strLoc = "Loc_209xc"; //Create a file. String testDir = Path.Combine(TestInfo.CurrentDirectory, "TestDir"); Directory.CreateDirectory(testDir); fileName = Path.Combine(testDir, "foobar.cs"); FileStream fstream = File.Create(fileName); fstream.Dispose(); iCountTestcases++; file2 = new FileInfo(fileName); try { FileStream fs = file2.Create(); fs.Dispose(); } catch (Exception exc) { iCountErrors++; printerr("Error_6566! Incorrect exception thrown, exc==" + exc.ToString()); } file2.Delete(); Directory.Delete(testDir); // [] Pass valid File name strLoc = "Loc_498vy"; iCountTestcases++; fileName = Path.Combine(TestInfo.CurrentDirectory, "UniqueFileName_28829"); file2 = new FileInfo(fileName); try { FileStream fs = file2.Create(); if (file2.Name != Path.GetFileName(fileName)) { iCountErrors++; printerr("Error_0010! Unexpected File name :: " + file2.Name); } fs.Dispose(); file2.Delete(); } catch (Exception exc) { iCountErrors++; printerr("Error_28829! Unexpected exception thrown, exc==" + exc.ToString()); } // [] Try to create the file in the parent directory strLoc = "Loc_09t83"; iCountTestcases++; file2 = new FileInfo(Path.Combine(TestInfo.CurrentDirectory, "abc", "..", "Test.txt")); try { FileStream fs = file2.Create(); fs.Dispose(); } catch (Exception exc) { iCountErrors++; printerr("Error_0980! Incorrect exception thrown, exc==" + exc.ToString()); } file2.Delete(); // [] Create a long filename File strLoc = "Loc_2908y"; StringBuilder sb = new StringBuilder(TestInfo.CurrentDirectory); while (sb.Length < IOInputs.MaxPath + 1) sb.Append("a"); iCountTestcases++; try { file2 = new FileInfo(sb.ToString()); file2.Create(); file2.Delete(); iCountErrors++; printerr("Error_109ty! Expected exception not thrown, file2==" + file2.FullName); } catch (PathTooLongException) { } catch (Exception exc) { iCountErrors++; printerr("Error_109dv! Incorrect exception thrown, exc==" + exc.ToString()); } // [] Do some symbols strLoc = "Loc_87yg7"; fileName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName() + "!@#$%^&"); iCountTestcases++; try { file2 = new FileInfo(fileName); FileStream fs = file2.Create(); if (!file2.FullName.Equals(fileName)) { iCountErrors++; printerr("Error_0109x! Incorrect File name, file2==" + file2.FullName); } fs.Dispose(); file2.Delete(); } catch (Exception e) { iCountErrors++; printerr("Unexpected exception occured... " + e.ToString()); } // [] specifying subfile2ectories should fail unless they exist strLoc = "Loc_209ud"; iCountTestcases++; file2 = new FileInfo(Path.Combine(TestInfo.CurrentDirectory, "Test", "Test", "Test", "test.cs")); try { file2.Create(); if (file2.FullName.IndexOf(Path.Combine("Test", "Test", "Test")) == -1) { iCountErrors++; printerr("Error_0010! Unexpected File name :: " + file2.FullName); } } catch (DirectoryNotFoundException) { } catch (Exception exc) { iCountErrors++; printerr("Error_2019u! Incorrect exception thrown, exc==" + exc.ToString()); } // [] Try incorrect File name strLoc = "Loc_2089x"; iCountTestcases++; try { file2 = new FileInfo("\0"); file2.Create(); iCountErrors++; printerr("Error_19883! Expected exception not thrown, file2==" + file2.FullName); file2.Delete(); } catch (ArgumentException) { } catch (Exception exc) { iCountErrors++; printerr("Error_0198xu! Incorrect exception thrown, exc==" + exc.ToString()); } // network path test moved to RemoteIOTests.cs // [] Pass nested level File structure. strLoc = "Loc_098gt"; iCountTestcases++; file2 = new FileInfo(Path.Combine(TestInfo.CurrentDirectory, "abc", "xyz", "..", "..", "test.txt")); try { FileStream fs = file2.Create(); fs.Dispose(); file2.Delete(); } catch (Exception exc) { iCountErrors++; printerr("Error_9092c! Incorrect exception thrown, exc==" + exc.ToString()); } /* Test disabled because it modifies state outside the current working directory // [] Create a file in root strLoc = "Loc_89ytb"; try { String CurrentDirectory2 = Directory.GetCurrentDirectory(); String tempPath = CurrentDirectory2.Substring(0, CurrentDirectory2.IndexOf("\\") + 1) + Path.GetFileName(fileName); if (!File.Exists(tempPath) && !Directory.Exists(tempPath)) { file2 = new FileInfo(tempPath); FileStream fs = file2.Create(); fs.Dispose(); iCountTestcases++; if (!file2.Exists) { iCountErrors++; printerr("Error_t78g7! File not created, file==" + file2.FullName); } file2.Delete(); } } catch (Exception exc) { iCountErrors++; printerr("Error_h38d9! Unexpected exception, exc==" + exc.ToString()); } */ if (!Interop.IsLinux) // testing case-insensitivity { // [] Create file in current file2 by giving full File check casing as well strLoc = "loc_89tbh"; string fileName2 = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName()); fs2 = File.Create(fileName2); file2 = new FileInfo(Path.Combine(TestInfo.CurrentDirectory.ToLowerInvariant(), Path.GetFileNameWithoutExtension(fileName2).ToLowerInvariant() + Path.GetExtension(fileName2).ToUpperInvariant())); iCountTestcases++; if (!file2.Exists) { iCountErrors++; printerr("Error_t87gy! File not created, file==" + file2.FullName); } fs2.Dispose(); file2.Delete(); } } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics if (iCountErrors != 0) { Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString()); } Assert.Equal(0, iCountErrors); } public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err); } }
using System.Runtime.InteropServices; using System; namespace BeeDevelopment.Brazil { public partial class Z80A { [StructLayout(LayoutKind.Explicit)] [Serializable()] struct RegisterPair { [FieldOffset(0)] public ushort Value16; [FieldOffset(0)] public byte Low8; [FieldOffset(1)] public byte High8; public RegisterPair(ushort value) { this.Value16 = value; this.Low8 = (byte)(this.Value16); this.High8 = (byte)(this.Value16 >> 8); } public static implicit operator ushort(RegisterPair rp) { return rp.Value16; } public static implicit operator RegisterPair(ushort value) { return new RegisterPair(value); } } #region Flags private bool RegFlagC { get { return (RegAF.Low8 & 0x01) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x01) | (value ? 0x01 : 0x00)); } } private bool RegFlagN { get { return (RegAF.Low8 & 0x02) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x02) | (value ? 0x02 : 0x00)); } } private bool RegFlagP { get { return (RegAF.Low8 & 0x04) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x04) | (value ? 0x04 : 0x00)); } } private bool RegFlag3 { get { return (RegAF.Low8 & 0x08) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x08) | (value ? 0x08 : 0x00)); } } private bool RegFlagH { get { return (RegAF.Low8 & 0x10) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x10) | (value ? 0x10 : 0x00)); } } private bool RegFlag5 { get { return (RegAF.Low8 & 0x20) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x20) | (value ? 0x20 : 0x00)); } } private bool RegFlagZ { get { return (RegAF.Low8 & 0x40) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x40) | (value ? 0x40 : 0x00)); } } private bool RegFlagS { get { return (RegAF.Low8 & 0x80) != 0; } set { RegAF.Low8 = (byte)((RegAF.Low8 & ~0x80) | (value ? 0x80 : 0x00)); } } #endregion #region Main Register Set private RegisterPair RegAF; private RegisterPair RegBC; private RegisterPair RegDE; private RegisterPair RegHL; #endregion #region Alternate Register Set private RegisterPair RegAltAF; // Shadow for A and F private RegisterPair RegAltBC; // Shadow for B and C private RegisterPair RegAltDE; // Shadow for D and E private RegisterPair RegAltHL; // Shadow for H and L #endregion #region Special Purpose Registers private byte RegI; // I (interrupt vector) private byte RegR; // R (memory refresh) private RegisterPair RegIX; // IX (index register x) private RegisterPair RegIY; // IY (index register y) private RegisterPair RegSP; // SP (stack pointer) private RegisterPair RegPC; // PC (program counter) #endregion private void ResetRegisters() { // Clear main registers RegAF = 0; RegBC = 0; RegDE = 0; RegHL = 0; // Clear alternate registers RegAltAF = 0; RegAltBC = 0; RegAltDE = 0; RegAltHL = 0; // Clear special purpose registers RegI = 0; RegR = 0; RegIX.Value16 = 0; RegIY.Value16 = 0; RegSP.Value16 = 0; RegPC.Value16 = 0; } #region Public accessors [StateNotSaved()] public byte RegisterA { get { return RegAF.High8; } set { RegAF.High8 = value; } } [StateNotSaved()] public byte RegisterF { get { return RegAF.Low8; } set { RegAF.Low8 = value; } } public ushort RegisterAF { get { return RegAF.Value16; } set { RegAF.Value16 = value; } } [StateNotSaved()] public byte RegisterB { get { return RegBC.High8; } set { RegBC.High8 = value; } } [StateNotSaved()] public byte RegisterC { get { return RegBC.Low8; } set { RegBC.Low8 = value; } } public ushort RegisterBC { get { return RegBC.Value16; } set { RegBC.Value16 = value; } } [StateNotSaved()] public byte RegisterD { get { return RegDE.High8; } set { RegDE.High8 = value; } } [StateNotSaved()] public byte RegisterE { get { return RegDE.Low8; } set { RegDE.Low8 = value; } } public ushort RegisterDE { get { return RegDE.Value16; } set { RegDE.Value16 = value; } } [StateNotSaved()] public byte RegisterH { get { return RegHL.High8; } set { RegHL.High8 = value; } } [StateNotSaved()] public byte RegisterL { get { return RegHL.Low8; } set { RegHL.Low8 = value; } } public ushort RegisterHL { get { return RegHL.Value16; } set { RegHL.Value16 = value; } } public ushort RegisterPC { get { return RegPC.Value16; } set { RegPC.Value16 = value; } } public ushort RegisterSP { get { return RegSP.Value16; } set { RegSP.Value16 = value; } } public ushort RegisterIX { get { return RegIX.Value16; } set { RegIX.Value16 = value; } } public ushort RegisterIY { get { return RegIY.Value16; } set { RegIY.Value16 = value; } } public byte RegisterI { get { return RegI; } set { RegI = value; } } public byte RegisterR { get { return RegR; } set { RegR = value; } } public ushort RegisterShadowAF { get { return RegAltAF.Value16; } set { RegAltAF.Value16 = value; } } public ushort RegisterShadowBC { get { return RegAltBC.Value16; } set { RegAltBC.Value16 = value; } } public ushort RegisterShadowDE { get { return RegAltDE.Value16; } set { RegAltDE.Value16 = value; } } public ushort RegisterShadowHL { get { return RegAltHL.Value16; } set { RegAltHL.Value16 = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime; namespace System.Runtime { public enum RhFailFastReason { Unknown = 0, InternalError = 1, // "Runtime internal error" UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope." UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method." ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object." IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code." PN_UnhandledException = 6, // ProjectN: "unhandled exception" PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition." Max } // Keep this synchronized with the duplicate definition in DebugEventSource.cpp [Flags] internal enum ExceptionEventKind { Thrown = 1, CatchHandlerFound = 2, Unhandled = 4, FirstPassFrameEntered = 8 } internal unsafe static class DebuggerNotify { // We cache the events a debugger is interested on the C# side to avoid p/invokes when the // debugger isn't attached. // // Ideally we would like the managed debugger to start toggling this directly so that // it stays perfectly up-to-date. However as a reasonable approximation we fetch // the value from native code at the beginning of each exception dispatch. If the debugger // attempts to enroll in more events mid-exception handling we aren't going to see it. private static ExceptionEventKind s_cachedEventMask; internal static void BeginFirstPass(Exception e, byte* faultingIP, UIntPtr faultingFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.Thrown) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Thrown, faultingIP, faultingFrameSP); } internal static void FirstPassFrameEntered(Exception e, byte* enteredFrameIP, UIntPtr enteredFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.FirstPassFrameEntered) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.FirstPassFrameEntered, enteredFrameIP, enteredFrameSP); } internal static void EndFirstPass(Exception e, byte* handlerIP, UIntPtr handlingFrameSP) { if (handlerIP == null) { if ((s_cachedEventMask & ExceptionEventKind.Unhandled) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Unhandled, null, UIntPtr.Zero); } else { if ((s_cachedEventMask & ExceptionEventKind.CatchHandlerFound) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.CatchHandlerFound, handlerIP, handlingFrameSP); } } internal static void BeginSecondPass() { //desktop debugging has an unwind begin event, however it appears that is unneeded for now, and possibly // will never be needed? } } internal unsafe static class EH { internal static UIntPtr MaxSP { get { return new UIntPtr(unchecked((void*)(ulong)-1L)); } } private enum RhEHClauseKind { RH_EH_CLAUSE_TYPED = 0, RH_EH_CLAUSE_FAULT = 1, RH_EH_CLAUSE_FILTER = 2, RH_EH_CLAUSE_UNUSED = 3, } private struct RhEHClause { internal RhEHClauseKind _clauseKind; internal uint _tryStartOffset; internal uint _tryEndOffset; internal byte* _filterAddress; internal byte* _handlerAddress; internal void* _pTargetType; ///<summary> /// We expect the stackwalker to adjust return addresses to point at 'return address - 1' so that we /// can use an interval here that is closed at the start and open at the end. When a hardware fault /// occurs, the IP is pointing at the start of the instruction and will not be adjusted by the /// stackwalker. Therefore, it will naturally work with an interval that has a closed start and open /// end. ///</summary> public bool ContainsCodeOffset(uint codeOffset) { return ((codeOffset >= _tryStartOffset) && (codeOffset < _tryEndOffset)); } } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__EHEnum)] private struct EHEnum { [FieldOffset(0)] private IntPtr _dummy; // For alignment } // This is a fail-fast function used by the runtime as a last resort that will terminate the process with // as little effort as possible. No guarantee is made about the semantics of this fail-fast. internal static void FallbackFailFast(RhFailFastReason reason, Exception unhandledException) { InternalCalls.RhpFallbackFailFast(); } // Constants used with RhpGetClasslibFunction, to indicate which classlib function // we are interested in. // Note: make sure you change the def in EHHelpers.cpp if you change this! internal enum ClassLibFunctionId { GetRuntimeException = 0, FailFast = 1, // UnhandledExceptionHandler = 2, // unused AppendExceptionStackFrame = 3, } // Given an address pointing somewhere into a managed module, get the classlib-defined fail-fast // function and invoke it. Any failure to find and invoke the function, or if it returns, results in // Rtm-define fail-fast behavior. internal unsafe static void FailFastViaClasslib(RhFailFastReason reason, Exception unhandledException, IntPtr classlibAddress) { // Find the classlib function that will fail fast. This is a RuntimeExport function from the // classlib module, and is therefore managed-callable. IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunction(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { // The classlib didn't provide a function, so we fail our way... FallbackFailFast(reason, unhandledException); } try { // Invoke the classlib fail fast function. CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, IntPtr.Zero, IntPtr.Zero); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's function should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } #if AMD64 [StructLayout(LayoutKind.Explicit, Size = 0x4d0)] #elif ARM [StructLayout(LayoutKind.Explicit, Size=0x1a0)] #elif X86 [StructLayout(LayoutKind.Explicit, Size=0x2cc)] #else [StructLayout(LayoutKind.Explicit, Size = 0x10)] // this is small enough that it should trip an assert in RhpCopyContextFromExInfo #endif private struct OSCONTEXT { } #if ARM private const int c_IPAdjustForHardwareFault = 2; #else private const int c_IPAdjustForHardwareFault = 1; #endif internal unsafe static void* PointerAlign(void* ptr, int alignmentInBytes) { int alignMask = alignmentInBytes - 1; #if BIT64 return (void*)((((long)ptr) + alignMask) & ~alignMask); #else return (void*)((((int)ptr) + alignMask) & ~alignMask); #endif } [MethodImpl(MethodImplOptions.NoInlining)] internal unsafe static void UnhandledExceptionFailFastViaClasslib( RhFailFastReason reason, Exception unhandledException, IntPtr classlibAddress, ref ExInfo exInfo) { IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunction(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { FailFastViaClasslib( reason, unhandledException, classlibAddress); } // 16-byte align the context. This is overkill on x86 and ARM, but simplifies things slightly. const int contextAlignment = 16; byte* pbBuffer = stackalloc byte[sizeof(OSCONTEXT) + contextAlignment]; void* pContext = PointerAlign(pbBuffer, contextAlignment); // We 'normalized' the faulting IP of hardware faults to behave like return addresses. Undo this // normalization here so that we report the correct thing in the exception context record. if ((exInfo._kind & ExKind.KindMask) == ExKind.HardwareFault) { exInfo._pExContext->IP = (IntPtr)(((byte*)exInfo._pExContext->IP) - c_IPAdjustForHardwareFault); } InternalCalls.RhpCopyContextFromExInfo(pContext, sizeof(OSCONTEXT), exInfo._pExContext); try { CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, exInfo._pExContext->IP, (IntPtr)pContext); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's funciton should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } private enum RhEHFrameType { RH_EH_FIRST_FRAME = 1, RH_EH_FIRST_RETHROW_FRAME = 2, } internal unsafe static void AppendExceptionStackFrameViaClasslib( Exception exception, IntPtr IP, bool isFirstRethrowFrame, bool isFirstFrame) { IntPtr pAppendStackFrame = (IntPtr)InternalCalls.RhpGetClasslibFunction(IP, ClassLibFunctionId.AppendExceptionStackFrame); int flags = (isFirstFrame ? (int)RhEHFrameType.RH_EH_FIRST_FRAME : 0) | (isFirstRethrowFrame ? (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME : 0); if (pAppendStackFrame != IntPtr.Zero) { try { CalliIntrinsics.CallVoid(pAppendStackFrame, exception, IP, flags); } catch { // disallow all exceptions leaking out of callbacks } } } // Given an ExceptionID and an address pointing somewhere into a managed module, get // an exception object of a type that the module containing the given address will understand. // This finds the classlib-defined GetRuntimeException function and asks it for the exception object. internal static Exception GetClasslibException(ExceptionIDs id, IntPtr address) { unsafe { // Find the classlib function that will give us the exception object we want to throw. This // is a RuntimeExport function from the classlib module, and is therefore managed-callable. void* pGetRuntimeExceptionFunction = InternalCalls.RhpGetClasslibFunction(address, ClassLibFunctionId.GetRuntimeException); // Return the exception object we get from the classlib. Exception e = null; try { e = CalliIntrinsics.Call<Exception>((IntPtr)pGetRuntimeExceptionFunction, id); } catch { // disallow all exceptions leaking out of callbacks } // If the helper fails to yield an object, then we fail-fast. if (e == null) { FailFastViaClasslib( RhFailFastReason.ClassLibDidNotTranslateExceptionID, null, address); } return e; } } // RhExceptionHandling_ functions are used to throw exceptions out of our asm helpers. We tail-call from // the asm helpers to these functions, which performs the throw. The tail-call is important: it ensures that // the stack is crawlable from within these functions. [RuntimeExport("RhExceptionHandling_ThrowClasslibOverflowException")] public static void ThrowClasslibOverflowException(IntPtr address) { // Throw the overflow exception defined by the classlib, using the return address of the asm helper // to find the correct classlib. throw GetClasslibException(ExceptionIDs.Overflow, address); } [RuntimeExport("RhExceptionHandling_ThrowClasslibDivideByZeroException")] public static void ThrowClasslibDivideByZeroException(IntPtr address) { // Throw the divide by zero exception defined by the classlib, using the return address of the asm helper // to find the correct classlib. throw GetClasslibException(ExceptionIDs.DivideByZero, address); } [RuntimeExport("RhExceptionHandling_FailedAllocation")] public static void FailedAllocation(EETypePtr pEEType, bool fIsOverflow) { ExceptionIDs exID = fIsOverflow ? ExceptionIDs.Overflow : ExceptionIDs.OutOfMemory; // Throw the out of memory exception defined by the classlib, using the input EEType* // to find the correct classlib. throw pEEType.ToPointer()->GetClasslibException(exID); } #if !INPLACE_RUNTIME private static OutOfMemoryException s_theOOMException = new OutOfMemoryException(); // Rtm exports GetRuntimeException for the few cases where we have a helper that throws an exception // and may be called by either slr100 or other classlibs and that helper needs to throw an exception. // There are only a few cases where this happens now (the fast allocation helpers), so we limit the // exception types that Rtm will return. [RuntimeExport("GetRuntimeException")] public static Exception GetRuntimeException(ExceptionIDs id) { switch (id) { case ExceptionIDs.OutOfMemory: // Throw a preallocated exception to avoid infinite recursion. return s_theOOMException; case ExceptionIDs.Overflow: return new OverflowException(); default: Debug.Assert(false, "unexpected ExceptionID"); FallbackFailFast(RhFailFastReason.InternalError, null); return null; } } #endif private enum HwExceptionCode : uint { STATUS_REDHAWK_NULL_REFERENCE = 0x00000000u, STATUS_DATATYPE_MISALIGNMENT = 0x80000002u, STATUS_ACCESS_VIOLATION = 0xC0000005u, STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094u, } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__PAL_LIMITED_CONTEXT)] public struct PAL_LIMITED_CONTEXT { [FieldOffset(AsmOffsets.OFFSETOF__PAL_LIMITED_CONTEXT__IP)] internal IntPtr IP; // the rest of the struct is left unspecified. } internal struct StackRange { } // N.B. -- These values are burned into the throw helper assembly code and are also known the the // StackFrameIterator code. [Flags] internal enum ExKind : byte { None = 0, Throw = 1, HardwareFault = 2, // unused: 3 KindMask = 3, RethrowFlag = 4, Rethrow = 5, // RethrowFlag | Throw RethrowFault = 6, // RethrowFlag | HardwareFault } [StackOnly] [StructLayout(LayoutKind.Explicit)] public struct ExInfo { internal void Init(Exception exceptionObj) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _kind -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; _notifyDebuggerSP = UIntPtr.Zero; } internal void Init(Exception exceptionObj, ref ExInfo rethrownExInfo) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; _kind = rethrownExInfo._kind | ExKind.RethrowFlag; _notifyDebuggerSP = UIntPtr.Zero; } internal Exception ThrownException { get { return _exception; } } [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pPrevExInfo)] internal void* _pPrevExInfo; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pExContext)] internal PAL_LIMITED_CONTEXT* _pExContext; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_exception)] private Exception _exception; // actual object reference, specially reported by GcScanRootsWorker [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_kind)] internal ExKind _kind; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_passNumber)] internal byte _passNumber; // BEWARE: This field is used by the stackwalker to know if the dispatch code has reached the // point at which a handler is called. In other words, it serves as an "is a handler // active" state where '_idxCurClause == MaxTryRegionIdx' means 'no'. [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_idxCurClause)] internal uint _idxCurClause; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_frameIter)] internal StackFrameIterator _frameIter; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_notifyDebuggerSP)] volatile internal UIntPtr _notifyDebuggerSP; } // // Called by RhpThrowHwEx // [RuntimeExport("RhThrowHwEx")] public static void RhThrowHwEx(uint exceptionCode, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); IntPtr faultingCodeAddress = exInfo._pExContext->IP; ExceptionIDs exceptionId; switch (exceptionCode) { case (uint)HwExceptionCode.STATUS_REDHAWK_NULL_REFERENCE: exceptionId = ExceptionIDs.NullReference; break; case (uint)HwExceptionCode.STATUS_DATATYPE_MISALIGNMENT: exceptionId = ExceptionIDs.DataMisaligned; break; // N.B. -- AVs that have a read/write address lower than 64k are already transformed to // HwExceptionCode.REDHAWK_NULL_REFERENCE prior to calling this routine. case (uint)HwExceptionCode.STATUS_ACCESS_VIOLATION: exceptionId = ExceptionIDs.AccessViolation; break; case (uint)HwExceptionCode.STATUS_INTEGER_DIVIDE_BY_ZERO: exceptionId = ExceptionIDs.DivideByZero; break; default: // We don't wrap SEH exceptions from foreign code like CLR does, so we believe that we // know the complete set of HW faults generated by managed code and do not need to handle // this case. FailFastViaClasslib(RhFailFastReason.InternalError, null, faultingCodeAddress); exceptionId = ExceptionIDs.NullReference; break; } Exception exceptionToThrow = GetClasslibException(exceptionId, faultingCodeAddress); exInfo.Init(exceptionToThrow); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); FallbackFailFast(RhFailFastReason.InternalError, null); } private const uint MaxTryRegionIdx = 0xFFFFFFFFu; [RuntimeExport("RhThrowEx")] public static void RhThrowEx(Exception exceptionObj, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // Transform attempted throws of null to a throw of NullReferenceException. if (exceptionObj == null) { IntPtr faultingCodeAddress = exInfo._pExContext->IP; exceptionObj = GetClasslibException(ExceptionIDs.NullReference, faultingCodeAddress); } exInfo.Init(exceptionObj); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); FallbackFailFast(RhFailFastReason.InternalError, null); } [RuntimeExport("RhRethrow")] public static void RhRethrow(ref ExInfo activeExInfo, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // We need to copy the Exception object to this stack location because collided unwinds will cause // the original stack location to go dead. Exception rethrownException = activeExInfo.ThrownException; exInfo.Init(rethrownException, ref activeExInfo); DispatchEx(ref exInfo._frameIter, ref exInfo, activeExInfo._idxCurClause); FallbackFailFast(RhFailFastReason.InternalError, null); } private static void DispatchEx(ref StackFrameIterator frameIter, ref ExInfo exInfo, uint startIdx) { Debug.Assert(exInfo._passNumber == 1, "expected asm throw routine to set the pass"); Exception exceptionObj = exInfo.ThrownException; // ------------------------------------------------ // // First pass // // ------------------------------------------------ UIntPtr handlingFrameSP = MaxSP; byte* pCatchHandler = null; uint catchingTryRegionIdx = MaxTryRegionIdx; bool isFirstRethrowFrame = (startIdx != MaxTryRegionIdx); bool isFirstFrame = true; byte* prevControlPC = null; UIntPtr prevFramePtr = UIntPtr.Zero; bool unwoundReversePInvoke = false; bool isValid = frameIter.Init(exInfo._pExContext); Debug.Assert(isValid, "RhThrowEx called with an unexpected context"); DebuggerNotify.BeginFirstPass(exceptionObj, frameIter.ControlPC, frameIter.SP); for (; isValid; isValid = frameIter.Next(out startIdx, out unwoundReversePInvoke)) { // For GC stackwalking, we'll happily walk across native code blocks, but for EH dispatch, we // disallow dispatching exceptions across native code. if (unwoundReversePInvoke) break; prevControlPC = frameIter.ControlPC; DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); // A debugger can subscribe to get callbacks at a specific frame of exception dispatch // exInfo._notifyDebuggerSP can be populated by the debugger from out of process // at any time. if (exInfo._notifyDebuggerSP == frameIter.SP) DebuggerNotify.FirstPassFrameEntered(exceptionObj, frameIter.ControlPC, frameIter.SP); UpdateStackTrace(exceptionObj, ref exInfo, ref isFirstRethrowFrame, ref prevFramePtr, ref isFirstFrame); byte* pHandler; if (FindFirstPassHandler(exceptionObj, startIdx, ref frameIter, out catchingTryRegionIdx, out pHandler)) { handlingFrameSP = frameIter.SP; pCatchHandler = pHandler; DebugVerifyHandlingFrame(handlingFrameSP); break; } } DebuggerNotify.EndFirstPass(exceptionObj, pCatchHandler, handlingFrameSP); if (pCatchHandler == null) { UnhandledExceptionFailFastViaClasslib( RhFailFastReason.PN_UnhandledException, exceptionObj, (IntPtr)prevControlPC, // IP of the last frame that did not handle the exception ref exInfo); } // We FailFast above if the exception goes unhandled. Therefore, we cannot run the second pass // without a catch handler. Debug.Assert(pCatchHandler != null, "We should have a handler if we're starting the second pass"); DebuggerNotify.BeginSecondPass(); // ------------------------------------------------ // // Second pass // // ------------------------------------------------ // Due to the stackwalker logic, we cannot tolerate triggering a GC from the dispatch code once we // are in the 2nd pass. This is because the stackwalker applies a particular unwind semantic to // 'collapse' funclets which gets confused when we walk out of the dispatch code and encounter the // 'main body' without first encountering the funclet. The thunks used to invoke 2nd-pass // funclets will always toggle this mode off before invoking them. InternalCalls.RhpSetThreadDoNotTriggerGC(); exInfo._passNumber = 2; startIdx = MaxTryRegionIdx; isValid = frameIter.Init(exInfo._pExContext); for (; isValid && ((byte*)frameIter.SP <= (byte*)handlingFrameSP); isValid = frameIter.Next(out startIdx)) { Debug.Assert(isValid, "second-pass EH unwind failed unexpectedly"); DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); if (frameIter.SP == handlingFrameSP) { // invoke only a partial second-pass here... InvokeSecondPass(ref exInfo, startIdx, catchingTryRegionIdx); break; } InvokeSecondPass(ref exInfo, startIdx); } // ------------------------------------------------ // // Call the handler and resume execution // // ------------------------------------------------ exInfo._idxCurClause = catchingTryRegionIdx; InternalCalls.RhpCallCatchFunclet( exceptionObj, pCatchHandler, frameIter.RegisterSet, ref exInfo); // currently, RhpCallCatchFunclet will resume after the catch Debug.Assert(false, "unreachable"); FallbackFailFast(RhFailFastReason.InternalError, null); } [System.Diagnostics.Conditional("DEBUG")] private static void DebugScanCallFrame(int passNumber, byte* ip, UIntPtr sp) { if (ip == null) { Debug.Assert(false, "false"); } } [System.Diagnostics.Conditional("DEBUG")] private static void DebugVerifyHandlingFrame(UIntPtr handlingFrameSP) { Debug.Assert(handlingFrameSP != MaxSP, "Handling frame must have an SP value"); Debug.Assert(((UIntPtr*)handlingFrameSP) > &handlingFrameSP, "Handling frame must have a valid stack frame pointer"); } private static void UpdateStackTrace(Exception exceptionObj, ref ExInfo exInfo, ref bool isFirstRethrowFrame, ref UIntPtr prevFramePtr, ref bool isFirstFrame) { // We use the fact that all funclet stack frames belonging to the same logical method activation // will have the same FramePointer value. Additionally, the stackwalker will return a sequence of // callbacks for all the funclet stack frames, one right after the other. The classlib doesn't // want to know about funclets, so we strip them out by only reporting the first frame of a // sequence of funclets. This is correct because the leafmost funclet is first in the sequence // and corresponds to the current 'IP state' of the method. UIntPtr curFramePtr = exInfo._frameIter.FramePointer; if ((prevFramePtr == UIntPtr.Zero) || (curFramePtr != prevFramePtr)) { AppendExceptionStackFrameViaClasslib(exceptionObj, (IntPtr)exInfo._frameIter.ControlPC, isFirstRethrowFrame, isFirstFrame); } prevFramePtr = curFramePtr; isFirstRethrowFrame = false; isFirstFrame = false; } private static bool FindFirstPassHandler(Exception exception, uint idxStart, ref StackFrameIterator frameIter, out uint tryRegionIdx, out byte* pHandler) { pHandler = null; tryRegionIdx = MaxTryRegionIdx; EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref frameIter, &pbMethodStartAddress, &ehEnum)) return false; byte* pbControlPC = frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause); curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; } RhEHClauseKind clauseKind = ehClause._clauseKind; if (((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_TYPED) && (clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FILTER)) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. if (clauseKind == RhEHClauseKind.RH_EH_CLAUSE_TYPED) { if (ShouldTypedClauseCatchThisException(exception, (EEType*)ehClause._pTargetType)) { pHandler = ehClause._handlerAddress; tryRegionIdx = curIdx; return true; } } else { byte* pFilterFunclet = ehClause._filterAddress; bool shouldInvokeHandler = InternalCalls.RhpCallFilterFunclet(exception, pFilterFunclet, frameIter.RegisterSet); if (shouldInvokeHandler) { pHandler = ehClause._handlerAddress; tryRegionIdx = curIdx; return true; } } } return false; } static EEType* s_pLowLevelObjectType; private static bool ShouldTypedClauseCatchThisException(Exception exception, EEType* pClauseType) { if (TypeCast.IsInstanceOfClass(exception, pClauseType) != null) return true; if (s_pLowLevelObjectType == null) { s_pLowLevelObjectType = new System.Object().EEType; } // This allows the typical try { } catch { }--which expands to a typed catch of System.Object--to work on // all objects when the clause is in the low level runtime code. This special case is needed because // objects from foreign type systems are sometimes throw back up at runtime code and this is the only way // to catch them outside of having a filter with no type check in it, which isn't currently possible to // write in C#. See https://github.com/dotnet/roslyn/issues/4388 if (pClauseType->IsEquivalentTo(s_pLowLevelObjectType)) return true; return false; } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart) { InvokeSecondPass(ref exInfo, idxStart, MaxTryRegionIdx); } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxLimit) { EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref exInfo._frameIter, &pbMethodStartAddress, &ehEnum)) return; byte* pbControlPC = exInfo._frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause) && curIdx < idxLimit; curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; } RhEHClauseKind clauseKind = ehClause._clauseKind; if ((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FAULT) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. // N.B. -- We need to suppress GC "in-between" calls to finallys in this loop because we do // not have the correct next-execution point live on the stack and, therefore, may cause a GC // hole if we allow a GC between invocation of finally funclets (i.e. after one has returned // here to the dispatcher, but before the next one is invoked). Once they are running, it's // fine for them to trigger a GC, obviously. // // As a result, RhpCallFinallyFunclet will set this state in the runtime upon return from the // funclet, and we need to reset it if/when we fall out of the loop and we know that the // method will no longer get any more GC callbacks. byte* pFinallyHandler = ehClause._handlerAddress; exInfo._idxCurClause = curIdx; InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet); exInfo._idxCurClause = MaxTryRegionIdx; } } [NativeCallable(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallingConvention = CallingConvention.Cdecl)] static public void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, PInvokeCallsiteReturnAddr); } [RuntimeExport("RhpFailFastForPInvokeExceptionCoop")] static public void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, classlibBreadcrumb); } } // static class EH }
//----------------------------------------------------------------------- // <copyright file="AOTSupportScanner.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- #if UNITY_EDITOR namespace Stratus.OdinSerializer.Editor { using Utilities; using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using System.Reflection; using UnityEngine.SceneManagement; public sealed class AOTSupportScanner : IDisposable { private bool scanning; private bool allowRegisteringScannedTypes; private HashSet<Type> seenSerializedTypes = new HashSet<Type>(); private static System.Diagnostics.Stopwatch smartProgressBarWatch = System.Diagnostics.Stopwatch.StartNew(); private static int smartProgressBarDisplaysSinceLastUpdate = 0; private static readonly MethodInfo PlayerSettings_GetPreloadedAssets_Method = typeof(PlayerSettings).GetMethod("GetPreloadedAssets", BindingFlags.Public | BindingFlags.Static, null, Type.EmptyTypes, null); private static readonly PropertyInfo Debug_Logger_Property = typeof(Debug).GetProperty("unityLogger") ?? typeof(Debug).GetProperty("logger"); public void BeginScan() { this.scanning = true; allowRegisteringScannedTypes = false; this.seenSerializedTypes.Clear(); FormatterLocator.OnLocatedEmittableFormatterForType += this.OnLocatedEmitType; FormatterLocator.OnLocatedFormatter += this.OnLocatedFormatter; Serializer.OnSerializedType += this.OnSerializedType; } public bool ScanPreloadedAssets(bool showProgressBar) { // The API does not exist in this version of Unity if (PlayerSettings_GetPreloadedAssets_Method == null) return true; UnityEngine.Object[] assets = (UnityEngine.Object[])PlayerSettings_GetPreloadedAssets_Method.Invoke(null, null); if (assets == null) return true; try { for (int i = 0; i < assets.Length; i++) { if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning preloaded assets for AOT support", (i + 1) + " / " + assets.Length, (float)i / assets.Length)) { return false; } var asset = assets[i]; if (asset == null) continue; if (AssetDatabase.Contains(asset)) { // Scan the asset and all its dependencies var path = AssetDatabase.GetAssetPath(asset); this.ScanAsset(path, true); } else { // Just scan the asset this.ScanObject(assets[i]); } } } finally { if (showProgressBar) { EditorUtility.ClearProgressBar(); } } return true; } public bool ScanAssetBundle(string bundle) { string[] assets = AssetDatabase.GetAssetPathsFromAssetBundle(bundle); foreach (var asset in assets) { this.ScanAsset(asset, true); } return true; } public bool ScanAllAssetBundles(bool showProgressBar) { try { string[] bundles = AssetDatabase.GetAllAssetBundleNames(); for (int i = 0; i < bundles.Length; i++) { var bundle = bundles[i]; if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning asset bundles for AOT support", bundle, (float)i / bundles.Length)) { return false; } this.ScanAssetBundle(bundle); } } finally { if (showProgressBar) { EditorUtility.ClearProgressBar(); } } return true; } public bool ScanAllResources(bool includeResourceDependencies, bool showProgressBar, List<string> resourcesPaths = null) { if (resourcesPaths == null) { resourcesPaths = new List<string>() {""}; } try { if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning resources for AOT support", "Loading resource assets", 0f)) { return false; } var resourcesSet = new HashSet<UnityEngine.Object>(); for (int i = 0; i < resourcesPaths.Count; i++) { var resourcesPath = resourcesPaths[i]; if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Listing resources for AOT support", resourcesPath, (float)i / resourcesPaths.Count)) { return false; } resourcesSet.UnionWith(Resources.LoadAll(resourcesPath)); } var resources = resourcesSet.ToArray(); for (int i = 0; i < resources.Length; i++) { if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning resource " + i + " for AOT support", resources[i].name, (float)i / resources.Length)) { return false; } var assetPath = AssetDatabase.GetAssetPath(resources[i]); // Exclude editor-only resources if (assetPath.ToLower().Contains("/editor/")) continue; this.ScanAsset(assetPath, includeAssetDependencies: includeResourceDependencies); } return true; } finally { if (showProgressBar) { EditorUtility.ClearProgressBar(); } } } public bool ScanBuildScenes(bool includeSceneDependencies, bool showProgressBar) { var scenePaths = EditorBuildSettings.scenes .Where(n => n.enabled) .Select(n => n.path) .ToArray(); return this.ScanScenes(scenePaths, includeSceneDependencies, showProgressBar); } public bool ScanScenes(string[] scenePaths, bool includeSceneDependencies, bool showProgressBar) { if (scenePaths.Length == 0) return true; bool formerForceEditorModeSerialization = UnitySerializationUtility.ForceEditorModeSerialization; try { UnitySerializationUtility.ForceEditorModeSerialization = true; bool hasDirtyScenes = false; for (int i = 0; i < EditorSceneManager.sceneCount; i++) { if (EditorSceneManager.GetSceneAt(i).isDirty) { hasDirtyScenes = true; break; } } if (hasDirtyScenes && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return false; } var oldSceneSetup = EditorSceneManager.GetSceneManagerSetup(); try { for (int i = 0; i < scenePaths.Length; i++) { var scenePath = scenePaths[i]; if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning scenes for AOT support", "Scene " + (i + 1) + "/" + scenePaths.Length + " - " + scenePath, (float)i / scenePaths.Length)) { return false; } if (!System.IO.File.Exists(scenePath)) { Debug.LogWarning("Skipped AOT scanning scene '" + scenePath + "' for a file not existing at the scene path."); continue; } Scene openScene = default(Scene); try { openScene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single); } catch { Debug.LogWarning("Skipped AOT scanning scene '" + scenePath + "' for throwing exceptions when trying to load it."); continue; } var sceneGOs = Resources.FindObjectsOfTypeAll<GameObject>(); foreach (var go in sceneGOs) { if (go.scene != openScene) continue; if ((go.hideFlags & HideFlags.DontSaveInBuild) == 0) { foreach (var component in go.GetComponents<ISerializationCallbackReceiver>()) { try { this.allowRegisteringScannedTypes = true; component.OnBeforeSerialize(); var prefabSupporter = component as ISupportsPrefabSerialization; if (prefabSupporter != null) { // Also force a serialization of the object's prefab modifications, in case there are unknown types in there List<UnityEngine.Object> objs = null; var mods = UnitySerializationUtility.DeserializePrefabModifications(prefabSupporter.SerializationData.PrefabModifications, prefabSupporter.SerializationData.PrefabModificationsReferencedUnityObjects); UnitySerializationUtility.SerializePrefabModifications(mods, ref objs); } } finally { this.allowRegisteringScannedTypes = false; } } } } } // Load a new empty scene that will be unloaded immediately, just to be sure we completely clear all changes made by the scan // Sometimes this fails for unknown reasons. In that case, swallow any exceptions, and just soldier on and hope for the best! // Additionally, also eat any debug logs that happen here, because logged errors can stop the build process, and we don't want // that to happen. UnityEngine.ILogger logger = null; if (Debug_Logger_Property != null) { logger = (UnityEngine.ILogger)Debug_Logger_Property.GetValue(null, null); } bool previous = true; try { if (logger != null) { previous = logger.logEnabled; logger.logEnabled = false; } EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); } catch { } finally { if (logger != null) { logger.logEnabled = previous; } } } finally { if (oldSceneSetup != null && oldSceneSetup.Length > 0) { if (showProgressBar) { EditorUtility.DisplayProgressBar("Restoring scene setup", "", 1.0f); } EditorSceneManager.RestoreSceneManagerSetup(oldSceneSetup); } } if (includeSceneDependencies) { for (int i = 0; i < scenePaths.Length; i++) { var scenePath = scenePaths[i]; if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning scene dependencies for AOT support", "Scene " + (i + 1) + "/" + scenePaths.Length + " - " + scenePath, (float)i / scenePaths.Length)) { return false; } string[] dependencies = AssetDatabase.GetDependencies(scenePath, recursive: true); foreach (var dependency in dependencies) { this.ScanAsset(dependency, includeAssetDependencies: false); // All dependencies of this asset were already included recursively by Unity } } } return true; } finally { if (showProgressBar) { EditorUtility.ClearProgressBar(); } UnitySerializationUtility.ForceEditorModeSerialization = formerForceEditorModeSerialization; } } public bool ScanAsset(string assetPath, bool includeAssetDependencies) { if (assetPath.EndsWith(".unity")) { return this.ScanScenes(new string[] { assetPath }, includeAssetDependencies, false); } if (!(assetPath.EndsWith(".asset") || assetPath.EndsWith(".prefab"))) { // ScanAsset can only scan .asset and .prefab assets. return false; } bool formerForceEditorModeSerialization = UnitySerializationUtility.ForceEditorModeSerialization; try { UnitySerializationUtility.ForceEditorModeSerialization = true; var assets = AssetDatabase.LoadAllAssetsAtPath(assetPath); if (assets == null || assets.Length == 0) { return false; } foreach (var asset in assets) { this.ScanObject(asset); } if (includeAssetDependencies) { string[] dependencies = AssetDatabase.GetDependencies(assetPath, recursive: true); foreach (var dependency in dependencies) { this.ScanAsset(dependency, includeAssetDependencies: false); // All dependencies were already included recursively by Unity } } return true; } finally { UnitySerializationUtility.ForceEditorModeSerialization = formerForceEditorModeSerialization; } } public void ScanObject(UnityEngine.Object obj) { if (obj is ISerializationCallbackReceiver) { bool formerForceEditorModeSerialization = UnitySerializationUtility.ForceEditorModeSerialization; try { UnitySerializationUtility.ForceEditorModeSerialization = true; this.allowRegisteringScannedTypes = true; (obj as ISerializationCallbackReceiver).OnBeforeSerialize(); } finally { this.allowRegisteringScannedTypes = false; UnitySerializationUtility.ForceEditorModeSerialization = formerForceEditorModeSerialization; } } } public List<Type> EndScan() { if (!this.scanning) throw new InvalidOperationException("Cannot end a scan when scanning has not begun."); var result = this.seenSerializedTypes.ToList(); this.Dispose(); return result; } public void Dispose() { if (this.scanning) { FormatterLocator.OnLocatedEmittableFormatterForType -= this.OnLocatedEmitType; FormatterLocator.OnLocatedFormatter -= this.OnLocatedFormatter; Serializer.OnSerializedType -= this.OnSerializedType; this.scanning = false; this.seenSerializedTypes.Clear(); this.allowRegisteringScannedTypes = false; } } private void OnLocatedEmitType(Type type) { if (!AllowRegisterType(type)) return; this.RegisterType(type); } private void OnSerializedType(Type type) { if (!AllowRegisterType(type)) return; this.RegisterType(type); } private void OnLocatedFormatter(IFormatter formatter) { var type = formatter.SerializedType; if (type == null) return; if (!AllowRegisterType(type)) return; this.RegisterType(type); } private static bool AllowRegisterType(Type type) { if (IsEditorOnlyAssembly(type.Assembly)) return false; if (type.IsGenericType) { foreach (var parameter in type.GetGenericArguments()) { if (!AllowRegisterType(parameter)) return false; } } return true; } private static bool IsEditorOnlyAssembly(Assembly assembly) { return EditorAssemblyNames.Contains(assembly.GetName().Name); } private static HashSet<string> EditorAssemblyNames = new HashSet<string>() { "Assembly-CSharp-Editor", "Assembly-UnityScript-Editor", "Assembly-Boo-Editor", "Assembly-CSharp-Editor-firstpass", "Assembly-UnityScript-Editor-firstpass", "Assembly-Boo-Editor-firstpass", typeof(Editor).Assembly.GetName().Name }; private void RegisterType(Type type) { if (!this.allowRegisteringScannedTypes) return; //if (type.IsAbstract || type.IsInterface) return; if (type.IsGenericType && (type.IsGenericTypeDefinition || !type.IsFullyConstructedGenericType())) return; //if (this.seenSerializedTypes.Add(type)) //{ // Debug.Log("Added " + type.GetNiceFullName()); //} this.seenSerializedTypes.Add(type); if (type.IsGenericType) { foreach (var arg in type.GetGenericArguments()) { this.RegisterType(arg); } } } private static bool DisplaySmartUpdatingCancellableProgressBar(string title, string details, float progress, int updateIntervalByMS = 200, int updateIntervalByCall = 50) { bool updateProgressBar = smartProgressBarWatch.ElapsedMilliseconds >= updateIntervalByMS || ++smartProgressBarDisplaysSinceLastUpdate >= updateIntervalByCall; if (updateProgressBar) { smartProgressBarWatch.Stop(); smartProgressBarWatch.Reset(); smartProgressBarWatch.Start(); smartProgressBarDisplaysSinceLastUpdate = 0; if (EditorUtility.DisplayCancelableProgressBar(title, details, progress)) { return true; } } return false; } } } #endif
// // Authors: // Atsushi Enomoto // // Copyright 2007 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Linq; using System.Xml; namespace System.Xml.Linq { internal abstract class XObject : IXmlLineInfo { internal XObject () { } XContainer owner; List<object> annotations; string baseuri; int line, column; public event EventHandler<XObjectChangeEventArgs> Changing; public event EventHandler<XObjectChangeEventArgs> Changed; public string BaseUri { get { return baseuri; } internal set { baseuri = value; } } public XDocument Document { get { if (this is XDocument) return (XDocument) this; for (XContainer e = owner; e != null; e = e.owner) if (e is XDocument) return (XDocument) e; return null; } } public abstract XmlNodeType NodeType { get; } public XElement Parent { get { return owner as XElement; } } internal XContainer Owner { get { return owner; } } internal void SetOwner (XContainer node) { owner = node; } public void AddAnnotation (object annotation) { if (annotation == null) throw new ArgumentNullException ("annotation"); if (annotations == null) annotations = new List<object> (); annotations.Add (annotation); } public T Annotation<T> () where T : class { return (T) Annotation (typeof (T)); } public object Annotation (Type type) { return Annotations (type).FirstOrDefault (); } public IEnumerable<T> Annotations<T> () where T : class { foreach (T o in Annotations (typeof (T))) yield return o; } public IEnumerable<object> Annotations (Type type) { if (type == null) throw new ArgumentNullException ("type"); if (annotations == null) yield break; foreach (object o in annotations) if (type.IsAssignableFrom (o.GetType ())) yield return o; } public void RemoveAnnotations<T> () where T : class { RemoveAnnotations (typeof (T)); } public void RemoveAnnotations (Type type) { if (annotations == null) return; for (int i = 0; i < annotations.Count; i++) if (type.IsAssignableFrom (annotations [i].GetType ())) annotations.RemoveAt (i); } internal int LineNumber { get { return line; } set { line = value; } } internal int LinePosition { get { return column; } set { column = value; } } int IXmlLineInfo.LineNumber { get { return LineNumber; } } int IXmlLineInfo.LinePosition { get { return LinePosition; } } bool IXmlLineInfo.HasLineInfo () { return line > 0; } internal void FillLineInfoAndBaseUri (XmlReader r, LoadOptions options) { if ((options & LoadOptions.SetLineInfo) != LoadOptions.None) { IXmlLineInfo li = r as IXmlLineInfo; if (li != null && li.HasLineInfo ()) { LineNumber = li.LineNumber; LinePosition = li.LinePosition; } } if ((options & LoadOptions.SetBaseUri) != LoadOptions.None) BaseUri = r.BaseURI; } internal void OnAddingObject (object addedObject) { OnChanging (addedObject, new XObjectChangeEventArgs (XObjectChange.Add)); } internal void OnAddedObject (object addedObject) { OnChanged (addedObject, new XObjectChangeEventArgs (XObjectChange.Add)); } internal void OnNameChanging (object renamedObject) { OnChanging (renamedObject, new XObjectChangeEventArgs (System.Xml.Linq.XObjectChange.Name)); } internal void OnNameChanged (object renamedObject) { OnChanged (renamedObject, new XObjectChangeEventArgs (System.Xml.Linq.XObjectChange.Name)); } internal void OnRemovingObject (object removedObject) { OnChanging (removedObject, new XObjectChangeEventArgs (XObjectChange.Remove)); } internal void OnRemovedObject (object removedObject) { OnChanged (removedObject, new XObjectChangeEventArgs (XObjectChange.Remove)); } internal void OnValueChanging (object changedObject) { OnChanging (changedObject, new XObjectChangeEventArgs (XObjectChange.Value)); } internal void OnValueChanged (object changedObject) { OnChanged (changedObject, new XObjectChangeEventArgs (XObjectChange.Value)); } void OnChanging (object sender, XObjectChangeEventArgs args) { if (Changing != null) Changing (sender, args); if (Parent != null) Parent.OnChanging (sender, args); } void OnChanged (object sender, XObjectChangeEventArgs args) { if (Changed != null) Changed (sender, args); if (Parent != null) Parent.OnChanged (sender, args); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class SolutionCrawlerLogger { private const string Id = "Id"; private const string Kind = "Kind"; private const string Analyzer = "Analyzer"; private const string DocumentCount = "DocumentCount"; private const string Enabled = "Enabled"; private const string AnalyzerCount = "AnalyzerCount"; private const string PersistentStorage = "PersistentStorage"; private const string GlobalOperation = "GlobalOperation"; private const string HigherPriority = "HigherPriority"; private const string LowerPriority = "LowerPriority"; private const string TopLevel = "TopLevel"; private const string MemberLevel = "MemberLevel"; private const string NewWorkItem = "NewWorkItem"; private const string UpdateWorkItem = "UpdateWorkItem"; private const string ProjectEnqueue = "ProjectEnqueue"; private const string ResetStates = "ResetStates"; private const string ProjectNotExist = "ProjectNotExist"; private const string DocumentNotExist = "DocumentNotExist"; private const string ProcessProject = "ProcessProject"; private const string OpenDocument = "OpenDocument"; private const string CloseDocument = "CloseDocument"; private const string SolutionHash = "SolutionHash"; private const string ProcessDocument = "ProcessDocument"; private const string ProcessDocumentCancellation = "ProcessDocumentCancellation"; private const string ProcessProjectCancellation = "ProcessProjectCancellation"; private const string ActiveFileEnqueue = "ActiveFileEnqueue"; private const string ActiveFileProcessDocument = "ActiveFileProcessDocument"; private const string ActiveFileProcessDocumentCancellation = "ActiveFileProcessDocumentCancellation"; private const string Max = "Maximum"; private const string Min = "Minimum"; private const string Median = "Median"; private const string Mean = "Mean"; private const string Mode = "Mode"; private const string Range = "Range"; private const string Count = "Count"; public static void LogRegistration(int correlationId, Workspace workspace) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Kind] = workspace.Kind; })); } public static void LogUnregistration(int correlationId) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogReanalyze(int correlationId, IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); m[DocumentCount] = documentIds == null ? 0 : documentIds.Count(); })); } public static void LogOptionChanged(int correlationId, bool value) { Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Enabled] = value; })); } public static void LogActiveFileAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer, correlationId, workspace, reordered); } public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer, correlationId, workspace, reordered); } private static void LogAnalyzersWorker( FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { if (workspace.Kind == WorkspaceKind.Preview) { return; } // log registered analyzers. Logger.Log(analyzersId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[AnalyzerCount] = reordered.Length; })); foreach (var analyzer in reordered) { Logger.Log(analyzerId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); })); } } public static void LogWorkCoordinatorShutdownTimeout(int correlationId) { Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind) { logAggregator.IncreaseCount(kind); } public static void LogWorkCoordiantorShutdown(int correlationId, LogAggregator logAggregator) { Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m => { m[Id] = correlationId; foreach (var kv in logAggregator) { var change = ((WorkspaceChangeKind)kv.Key).ToString(); m[change] = kv.Value.GetCount(); } })); } public static void LogGlobalOperation(LogAggregator logAggregator) { logAggregator.IncreaseCount(GlobalOperation); } public static void LogActiveFileEnqueue(LogAggregator logAggregator) { logAggregator.IncreaseCount(ActiveFileEnqueue); } public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId projectId) { logAggregator.IncreaseCount(ProjectEnqueue); } public static void LogWorkItemEnqueue( LogAggregator logAggregator, string language, DocumentId documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath activeMember, bool added) { logAggregator.IncreaseCount(language); logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem); if (documentId != null) { logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel); if (lowPriority) { logAggregator.IncreaseCount(LowerPriority); logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id)); } } foreach (var reason in reasons) { logAggregator.IncreaseCount(reason); } } public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(HigherPriority); logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId)); } public static void LogResetStates(LogAggregator logAggregator) { logAggregator.IncreaseCount(ResetStates); } public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers) { Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m => { var solutionHash = GetSolutionHash(solution); m[Id] = correlationId; m[SolutionHash] = solutionHash.ToString(); var statMap = new Dictionary<string, List<int>>(); foreach (var kv in logAggregator) { if (kv.Key is string) { m[kv.Key.ToString()] = kv.Value.GetCount(); continue; } if (kv.Key is ValueTuple<string, Guid>) { var tuple = (ValueTuple<string, Guid>)kv.Key; var list = statMap.GetOrAdd(tuple.Item1, _ => new List<int>()); list.Add(kv.Value.GetCount()); continue; } throw ExceptionUtilities.Unreachable; } foreach (var kv in statMap) { var key = kv.Key.ToString(); var result = LogAggregator.GetStatistics(kv.Value); m[CreateProperty(key, Max)] = result.Maximum; m[CreateProperty(key, Min)] = result.Minimum; m[CreateProperty(key, Median)] = result.Median; m[CreateProperty(key, Mean)] = result.Mean; m[CreateProperty(key, Mode)] = result.Mode; m[CreateProperty(key, Range)] = result.Range; m[CreateProperty(key, Count)] = result.Count; } })); foreach (var analyzer in analyzers) { var diagIncrementalAnalyzer = analyzer as BaseDiagnosticIncrementalAnalyzer; if (diagIncrementalAnalyzer != null) { diagIncrementalAnalyzer.LogAnalyzerCountSummary(); break; } } } private static int GetSolutionHash(Solution solution) { if (solution != null && solution.FilePath != null) { return solution.FilePath.ToLowerInvariant().GetHashCode(); } return 0; } private static string CreateProperty(string parent, string child) { return parent + "." + child; } public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(CloseDocument); logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId)); } public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(OpenDocument); logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId)); } public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid documentId, bool processed) { if (processed) { logAggregator.IncreaseCount(ActiveFileProcessDocument); } else { logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation); } } public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessDocument); } else { logAggregator.IncreaseCount(ProcessDocumentCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId)); } public static void LogProcessDocumentNotExist(LogAggregator logAggregator) { logAggregator.IncreaseCount(DocumentNotExist); } public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessProject); } else { logAggregator.IncreaseCount(ProcessProjectCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId)); } public static void LogProcessProjectNotExist(LogAggregator logAggregator) { logAggregator.IncreaseCount(ProjectNotExist); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Stack ** ** Purpose: An array implementation of a generic stack. ** ** Date: January 28, 2003 ** =============================================================================*/ namespace System.Collections.Generic { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security.Permissions; // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(System_StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] #if !SILVERLIGHT [Serializable()] #endif [System.Runtime.InteropServices.ComVisible(false)] public class Stack<T> : IEnumerable<T>, System.Collections.ICollection { private T[] _array; // Storage for stack elements private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in [....] w/ collection. #if !SILVERLIGHT [NonSerialized] #endif private Object _syncRoot; private const int _defaultCapacity = 4; static T[] _emptyArray = new T[0]; /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack"]/*' /> public Stack() { _array = _emptyArray; _size = 0; _version = 0; } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack1"]/*' /> public Stack(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNumRequired); _array = new T[capacity]; _size = 0; _version = 0; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack2"]/*' /> public Stack(IEnumerable<T> collection) { if (collection==null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); ICollection<T> c = collection as ICollection<T>; if( c != null) { int count = c.Count; _array = new T[count]; c.CopyTo(_array, 0); _size = count; } else { _size = 0; _array = new T[_defaultCapacity]; using(IEnumerator<T> en = collection.GetEnumerator()) { while(en.MoveNext()) { Push(en.Current); } } } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Count"]/*' /> public int Count { get { return _size; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IsSynchronized"]/*' /> bool System.Collections.ICollection.IsSynchronized { get { return false; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.SyncRoot"]/*' /> Object System.Collections.ICollection.SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Clear"]/*' /> public void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Contains"]/*' /> public bool Contains(T item) { int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default; while (count-- > 0) { if (((Object) item) == null) { if (((Object) _array[count]) == null) return true; } else if (_array[count] != null && c.Equals(_array[count], item) ) { return true; } } return false; } // Copies the stack into an array. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.CopyTo"]/*' /> public void CopyTo(T[] array, int arrayIndex) { if (array==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (arrayIndex < 0 || arrayIndex > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _size) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if (array==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if( array.GetLowerBound(0) != 0 ) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (arrayIndex < 0 || arrayIndex > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _size) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch(ArrayTypeMismatchException){ ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } // Returns an IEnumerator for this Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.GetEnumerator"]/*' /> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if( _size < threshold ) { T[] newarray = new T[_size]; Array.Copy(_array, 0, newarray, 0, _size); _array = newarray; _version++; } } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Peek"]/*' /> public T Peek() { if (_size==0) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack); return _array[_size-1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Pop"]/*' /> public T Pop() { if (_size == 0) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack); _version++; T item = _array[--_size]; _array[_size] = default(T); // Free memory quicker. return item; } // Pushes an item to the top of the stack. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Push"]/*' /> public void Push(T item) { if (_size == _array.Length) { T[] newArray = new T[(_array.Length == 0) ? _defaultCapacity : 2*_array.Length]; Array.Copy(_array, 0, newArray, 0, _size); _array = newArray; } _array[_size++] = item; _version++; } // Copies the Stack to an array, in the same order Pop would return the items. public T[] ToArray() { T[] objArray = new T[_size]; int i = 0; while(i < _size) { objArray[i] = _array[_size-i-1]; i++; } return objArray; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator"]/*' /> #if !SILVERLIGHT [Serializable()] #endif [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private Stack<T> _stack; private int _index; private int _version; private T currentElement; internal Enumerator(Stack<T> stack) { _stack = stack; _version = _stack._version; _index = -2; currentElement = default(T); } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Dispose"]/*' /> public void Dispose() { _index = -1; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.MoveNext"]/*' /> public bool MoveNext() { bool retval; if (_version != _stack._version) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size-1; retval = ( _index >= 0); if (retval) currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) currentElement = _stack._array[_index]; else currentElement = default(T); return retval; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Current"]/*' /> public T Current { get { if (_index == -2) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); if (_index == -1) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); return currentElement; } } Object System.Collections.IEnumerator.Current { get { if (_index == -2) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); if (_index == -1) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); return currentElement; } } void System.Collections.IEnumerator.Reset() { if (_version != _stack._version) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); _index = -2; currentElement = default(T); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void DivideSingle() { var test = new SimpleBinaryOpTest__DivideSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__DivideSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__DivideSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__DivideSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.Divide( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.Divide( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.Divide( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.Divide), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.Divide), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.Divide), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.Divide( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.Divide(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Divide(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Divide(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__DivideSingle(); var result = Sse.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.Divide(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] / right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(left[i] / right[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.Divide)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; using System.Management.Automation.Provider; using System.Reflection; using System.Linq; using System.Threading; using Dbg = System.Management.Automation; using System.Collections.Generic; namespace System.Management.Automation { /// <summary> /// Information about a loaded Cmdlet Provider /// </summary> /// /// <remarks> /// A cmdlet provider may want to derive from this class to provide their /// own public members to expose to the user or to cache information related to the provider. /// </remarks> public class ProviderInfo { /// <summary> /// Gets the System.Type of the class that implements the provider. /// </summary> public Type ImplementingType { get; } /// <summary> /// Gets the help file path for the provider. /// </summary> public string HelpFile { get; } = ""; /// <summary> /// The instance of session state the provider belongs to. /// </summary> private SessionState _sessionState; /// <summary> /// Gets the name of the provider. /// </summary> public string Name { get; } /// <summary> /// Gets the full name of the provider including the pssnapin name if available /// </summary> /// internal string FullName { get { string result = this.Name; if (!String.IsNullOrEmpty(this.PSSnapInName)) { result = String.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}\\{1}", this.PSSnapInName, this.Name); } // After converting core snapins to load as modules, the providers will have Module property populated else if (!string.IsNullOrEmpty(this.ModuleName)) { result = String.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}\\{1}", this.ModuleName, this.Name); } return result; } } /// <summary> /// Gets the Snap-in in which the provider is implemented. /// </summary> public PSSnapInInfo PSSnapIn { get; } /// <summary> /// Gets the pssnapin name that the provider is implemented in. /// </summary> /// internal string PSSnapInName { get { string result = null; if (PSSnapIn != null) { result = PSSnapIn.Name; } return result; } } internal string ApplicationBase { get { string psHome = null; try { psHome = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); } catch (System.Security.SecurityException) { psHome = null; } return psHome; } } /// <summary> /// Get the name of the module exporting this provider. /// </summary> public string ModuleName { get { if (PSSnapIn != null) return PSSnapIn.Name; if (Module != null) return Module.Name; return String.Empty; } } /// <summary> /// Gets the module the defined this provider. /// </summary> public PSModuleInfo Module { get; private set; } internal void SetModule(PSModuleInfo module) { Module = module; } /// <summary> /// Gets or sets the description for the provider /// </summary> public String Description { get; set; } /// <summary> /// Gets the capabilities that are implemented by the provider. /// </summary> public Provider.ProviderCapabilities Capabilities { get { if (!_capabilitiesRead) { try { // Get the CmdletProvider declaration attribute Type providerType = this.ImplementingType; var attrs = providerType.GetCustomAttributes<CmdletProviderAttribute>(false); var cmdletProviderAttributes = attrs as CmdletProviderAttribute[] ?? attrs.ToArray(); if (cmdletProviderAttributes.Length == 1) { _capabilities = cmdletProviderAttributes[0].ProviderCapabilities; _capabilitiesRead = true; } } catch (Exception e) // Catch-all OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); // Assume no capabilities for now } } return _capabilities; } // get } // Capabilities private ProviderCapabilities _capabilities = ProviderCapabilities.None; private bool _capabilitiesRead; /// <summary> /// Gets or sets the home for the provider. /// </summary> /// /// <remarks> /// The location can be either a fully qualified provider path /// or an Msh path. This is the location that is substituted for the ~. /// </remarks> public string Home { get; set; } // Home /// <summary> /// Gets an enumeration of drives that are available for /// this provider. /// </summary> public Collection<PSDriveInfo> Drives { get { return _sessionState.Drive.GetAllForProvider(FullName); } // get } // Drives /// <summary> /// A hidden drive for the provider that is used for setting /// the location to a provider-qualified path. /// </summary> private PSDriveInfo _hiddenDrive; /// <summary> /// Gets the hidden drive for the provider that is used /// for setting a location to a provider-qualified path. /// </summary> /// internal PSDriveInfo HiddenDrive { get { return _hiddenDrive; } // get } // HiddenDrive /// <summary> /// Gets the string representation of the instance which is the name of the provider. /// </summary> /// /// <returns> /// The name of the provider. If single-shell, the name is pssnapin-qualified. If custom-shell, /// the name is just the provider name. /// </returns> public override string ToString() { return FullName; } #if USE_TLS /// <summary> /// Allocates some thread local storage to an instance of the /// provider. We don't want to cache a single instance of the /// provider because that could lead to problems in a multi-threaded /// environment. /// </summary> private LocalDataStoreSlot instance = Thread.AllocateDataSlot(); #endif /// <summary> /// Gets or sets if the drive-root relative paths on drives of this provider /// are separated by a colon or not. /// /// This is true for all PSDrives on all platforms, except for filesystems on /// non-windows platforms /// </summary> public bool VolumeSeparatedByColon { get; internal set; } = true; /// <summary> /// Constructs an instance of the class using an existing reference /// as a template. /// </summary> /// /// <param name="providerInfo"> /// The provider information to copy to this instance. /// </param> /// /// <remarks> /// This constructor should be used by derived types to easily copying /// the base class members from an existing ProviderInfo. /// This is designed for use by a <see cref="System.Management.Automation.Provider.CmdletProvider"/> /// during calls to their <see cref="System.Management.Automation.Provider.CmdletProvider.Start(ProviderInfo)"/> method. /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="providerInfo"/> is null. /// </exception> protected ProviderInfo(ProviderInfo providerInfo) { if (providerInfo == null) { throw PSTraceSource.NewArgumentNullException("providerInfo"); } Name = providerInfo.Name; ImplementingType = providerInfo.ImplementingType; _capabilities = providerInfo._capabilities; Description = providerInfo.Description; _hiddenDrive = providerInfo._hiddenDrive; Home = providerInfo.Home; HelpFile = providerInfo.HelpFile; PSSnapIn = providerInfo.PSSnapIn; _sessionState = providerInfo._sessionState; VolumeSeparatedByColon = providerInfo.VolumeSeparatedByColon; } /// <summary> /// Constructor for the ProviderInfo class. /// </summary> /// /// <param name="sessionState"> /// The instance of session state that the provider is being added to. /// </param> /// /// <param name="implementingType"> /// The type that implements the provider /// </param> /// /// <param name="name"> /// The name of the provider. /// </param> /// /// <param name="helpFile"> /// The help file for the provider. /// </param> /// /// <param name="psSnapIn"> /// The Snap-In name for the provider. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="sessionState"/> is null. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="implementingType"/> is null. /// </exception> /// internal ProviderInfo( SessionState sessionState, Type implementingType, string name, string helpFile, PSSnapInInfo psSnapIn) : this(sessionState, implementingType, name, String.Empty, String.Empty, helpFile, psSnapIn) { } /// <summary> /// Constructor for the ProviderInfo class. /// </summary> /// /// <param name="sessionState"> /// The instance of session state that the provider is being added to. /// </param> /// /// <param name="implementingType"> /// The type that implements the provider /// </param> /// /// <param name="name"> /// The alternate name to use for the provider instead of the one specified /// in the .cmdletprovider file. /// </param> /// /// <param name="description"> /// The description of the provider. /// </param> /// /// <param name="home"> /// The home path for the provider. This must be an MSH path. /// </param> /// /// <param name="helpFile"> /// The help file for the provider. /// </param> /// /// <param name="psSnapIn"> /// The Snap-In for the provider. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="implementingType"/> or <paramref name="sessionState"/> is null. /// </exception> /// /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// internal ProviderInfo( SessionState sessionState, Type implementingType, string name, string description, string home, string helpFile, PSSnapInInfo psSnapIn) { // Verify parameters if (sessionState == null) { throw PSTraceSource.NewArgumentNullException("sessionState"); } if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("implementingType"); } if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } _sessionState = sessionState; Name = name; Description = description; Home = home; ImplementingType = implementingType; HelpFile = helpFile; PSSnapIn = psSnapIn; #if SUPPORTS_CMDLETPROVIDER_FILE LoadProviderFromPath(path); #endif // Create the hidden drive. The name doesn't really // matter since we are not adding this drive to a scope. _hiddenDrive = new PSDriveInfo( this.FullName, this, "", "", null); _hiddenDrive.Hidden = true; // TODO:PSL // this is probably not right here if (implementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) && !Platform.IsWindows) { VolumeSeparatedByColon = false; } } #if SUPPORTS_CMDLETPROVIDER_FILE /// <summary> /// Loads the provider from the specified path. /// </summary> /// /// <param name="path"> /// The path to a .cmdletprovider file to load the provider from. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="path"/> is null or empty. /// </exception> /// /// <exception cref="FileLoadException"> /// The file specified by <paramref name="path"/> could /// not be loaded as an XML document. /// </exception> /// /// <exception cref="FormatException"> /// If <paramref name="path"/> refers to a file that does /// not adhere to the appropriate CmdletProvider file format. /// </exception> /// private void LoadProviderFromPath(string path) { if (String.IsNullOrEmpty(path)) { throw tracer.NewArgumentException("path"); } Internal.CmdletProviderFileReader reader = Internal.CmdletProviderFileReader.CreateCmdletProviderFileReader(path); // Read the assembly info from the file assemblyInfo = reader.AssemblyInfo; // Read the type name from the file providerImplementationClassName = reader.TypeName; helpFile = reader.HelpFilePath; // Read the capabilities from the file capabilities = reader.Capabilities; capabilitiesRead = true; if (String.IsNullOrEmpty(name)) { name = reader.Name; } } // LoadProviderFromPath #endif /// <summary> /// Determines if the passed in name is either the fully-qualified pssnapin name or /// short name of the provider. /// </summary> /// /// <param name="providerName"> /// The name to compare with the provider name. /// </param> /// /// <returns> /// True if the name is the fully-qualified pssnapin name or the short name of the provider. /// </returns> /// internal bool NameEquals(string providerName) { PSSnapinQualifiedName qualifiedProviderName = PSSnapinQualifiedName.GetInstance(providerName); bool result = false; if (qualifiedProviderName != null) { // If the pssnapin name and provider name are specified, then both must match do // false loop { if (!String.IsNullOrEmpty(qualifiedProviderName.PSSnapInName)) { // After converting core snapins to load as modules, the providers will have Module property populated if (!String.Equals(qualifiedProviderName.PSSnapInName, this.PSSnapInName, StringComparison.OrdinalIgnoreCase) && !String.Equals(qualifiedProviderName.PSSnapInName, this.ModuleName, StringComparison.OrdinalIgnoreCase)) { break; } } result = String.Equals(qualifiedProviderName.ShortName, this.Name, StringComparison.OrdinalIgnoreCase); } while (false); } else { // If only the provider name is specified, then only the name must match result = String.Equals(providerName, Name, StringComparison.OrdinalIgnoreCase); } return result; } internal bool IsMatch(string providerName) { PSSnapinQualifiedName psSnapinQualifiedName = PSSnapinQualifiedName.GetInstance(providerName); WildcardPattern namePattern = null; if (psSnapinQualifiedName != null && WildcardPattern.ContainsWildcardCharacters(psSnapinQualifiedName.ShortName)) { namePattern = WildcardPattern.Get(psSnapinQualifiedName.ShortName, WildcardOptions.IgnoreCase); } return IsMatch(namePattern, psSnapinQualifiedName); } internal bool IsMatch(WildcardPattern namePattern, PSSnapinQualifiedName psSnapinQualifiedName) { bool result = false; if (psSnapinQualifiedName == null) { result = true; } else { if (namePattern == null) { if (String.Equals(Name, psSnapinQualifiedName.ShortName, StringComparison.OrdinalIgnoreCase) && IsPSSnapinNameMatch(psSnapinQualifiedName)) { result = true; } } else if (namePattern.IsMatch(Name) && IsPSSnapinNameMatch(psSnapinQualifiedName)) { result = true; } } return result; } private bool IsPSSnapinNameMatch(PSSnapinQualifiedName psSnapinQualifiedName) { bool result = false; if (String.IsNullOrEmpty(psSnapinQualifiedName.PSSnapInName) || String.Equals(psSnapinQualifiedName.PSSnapInName, PSSnapInName, StringComparison.OrdinalIgnoreCase)) { result = true; } return result; } /// <summary> /// Creates an instance of the provider /// </summary> /// /// <returns> /// An instance of the provider or null if one could not be created. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If an instance of the provider could not be created because the /// type could not be found in the assembly. /// </exception> /// internal Provider.CmdletProvider CreateInstance() { // It doesn't really seem that using thread local storage to store an // instance of the provider is really much of a performance gain and it // still causes problems with the CmdletProviderContext when piping two // commands together that use the same provider. // get-child -filter a*.txt | get-content // This pipeline causes problems when using a cached provider instance because // the CmdletProviderContext gets changed when get-content gets called. // When get-content finishes writing content from the first output of get-child // get-child gets control back and writes out a FileInfo but the WriteObject // from get-content gets used because the CmdletProviderContext is still from // that cmdlet. // Possible solutions are to not cache the provider instance, or to maintain // a CmdletProviderContext stack in ProviderBase. Each method invocation pushes // the current context and the last action of the method pops back to the // previous context. #if USE_TLS // Next see if we already have an instance in thread local storage object providerInstance = Thread.GetData(instance); if (providerInstance == null) { #else object providerInstance = null; #endif // Finally create an instance of the class Exception invocationException = null; try { providerInstance = Activator.CreateInstance(this.ImplementingType); } catch (TargetInvocationException targetException) { invocationException = targetException.InnerException; } catch (MissingMethodException) { } catch (MemberAccessException) { } catch (ArgumentException) { } #if USE_TLS // cache the instance in thread local storage Thread.SetData(instance, providerInstance); } #endif if (providerInstance == null) { ProviderNotFoundException e = null; if (invocationException != null) { e = new ProviderNotFoundException( this.Name, SessionStateCategory.CmdletProvider, "ProviderCtorException", SessionStateStrings.ProviderCtorException, invocationException.Message); } else { e = new ProviderNotFoundException( this.Name, SessionStateCategory.CmdletProvider, "ProviderNotFoundInAssembly", SessionStateStrings.ProviderNotFoundInAssembly); } throw e; } Provider.CmdletProvider result = providerInstance as Provider.CmdletProvider; Dbg.Diagnostics.Assert( result != null, "DiscoverProvider should verify that the class is derived from CmdletProvider so this is just validation of that"); result.SetProviderInformation(this); return result; } /// <summary> /// Get the output types specified on this provider for the cmdlet requested. /// </summary> internal void GetOutputTypes(string cmdletname, List<PSTypeName> listToAppend) { if (_providerOutputType == null) { _providerOutputType = new Dictionary<string, List<PSTypeName>>(); foreach (OutputTypeAttribute outputType in ImplementingType.GetCustomAttributes<OutputTypeAttribute>(false)) { if (string.IsNullOrEmpty(outputType.ProviderCmdlet)) { continue; } List<PSTypeName> l; if (!_providerOutputType.TryGetValue(outputType.ProviderCmdlet, out l)) { l = new List<PSTypeName>(); _providerOutputType[outputType.ProviderCmdlet] = l; } l.AddRange(outputType.Type); } } List<PSTypeName> cmdletOutputType = null; if (_providerOutputType.TryGetValue(cmdletname, out cmdletOutputType)) { listToAppend.AddRange(cmdletOutputType); } } private Dictionary<string, List<PSTypeName>> _providerOutputType; private PSNoteProperty _noteProperty; internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { if (_noteProperty == null) { Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); } return _noteProperty; } } // class ProviderInfo } // namespace System.Management.Automation
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2011, Grant Archibald // // 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 using System; using System.Collections.Generic; using System.Linq; using FluentMigrator.Builders.IfDatabase; using FluentMigrator.Infrastructure; using FluentMigrator.Runner; using Microsoft.Extensions.DependencyInjection; using Moq; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit.Builders.IfDatabase { [TestFixture] public class IfDatabaseExpressionRootTests { [Test] public void CallsDelegateIfDatabaseTypeApplies() { var delegateCalled = false; var context = ExecuteTestMigration(new[] { "SQLite" }, expr => { expr.Delegate(() => delegateCalled = true); }); context.Expressions.Count.ShouldBe(0); delegateCalled.ShouldBeTrue(); } [Test] public void DoesntCallsDelegateIfDatabaseTypeDoesntMatch() { var delegateCalled = false; var context = ExecuteTestMigration(new[] { "Blurb" }, expr => { expr.Delegate(() => delegateCalled = true); }); context.Expressions.Count.ShouldBe(0); delegateCalled.ShouldBeFalse(); } [Test] public void WillAddExpressionIfDatabaseTypeApplies() { var context = ExecuteTestMigration("SQLite"); context.Expressions.Count.ShouldBe(1); } [Test] public void WillAddExpressionIfProcessorInMigrationProcessorPredicate() { var context = ExecuteTestMigration(x => x == "SQLite"); context.Expressions.Count.ShouldBe(1); } [Test] public void WillNotAddExpressionIfProcessorNotInMigrationProcessorPredicate() { var context = ExecuteTestMigration(x => x == "Db2" || x == "Hana"); context.Expressions.Count.ShouldBe(0); } [Test] public void WillNotAddExpressionIfDatabaseTypeApplies() { var context = ExecuteTestMigration("Unknown"); context.Expressions.Count.ShouldBe(0); } [Test] public void WillNotAddExpressionIfProcessorNotMigrationProcessor() { var mock = new Mock<IMigrationProcessor>(); mock.SetupGet(x => x.DatabaseType).Returns("Unknown"); mock.SetupGet(x => x.DatabaseTypeAliases).Returns(new List<string>()); var context = ExecuteTestMigration(new List<string>() { "SQLite" }, mock); context.Expressions.Count.ShouldBe(0); } [Test] public void WillAddExpressionIfOneDatabaseTypeApplies() { var context = ExecuteTestMigration("SQLite", "Unknown"); context.Expressions.Count.ShouldBe(1); } [Test] public void WillAddAlterExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Alter.Table("Foo").AddColumn("Blah").AsString()); context.Expressions.Count.ShouldBeGreaterThan(0); } [Test] public void WillAddCreateExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Create.Table("Foo").WithColumn("Blah").AsString()); context.Expressions.Count.ShouldBeGreaterThan(0); } [Test] public void WillAddDeleteExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Delete.Table("Foo")); context.Expressions.Count.ShouldBeGreaterThan(0); } [Test] public void WillAddExecuteExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Execute.Sql("DROP TABLE Foo")); context.Expressions.Count.ShouldBeGreaterThan(0); } [Test] public void WillAddInsertExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Insert.IntoTable("Foo").Row(new { Id = 1 })); context.Expressions.Count.ShouldBeGreaterThan(0); } [Test] public void WillAddRenameExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Rename.Table("Foo").To("Foo2")); context.Expressions.Count.ShouldBeGreaterThan(0); } [Test] public void WillAddSchemaExpression() { var databaseTypes = new List<string>() { "Unknown" }; // Arrange var unknownProcessorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose); unknownProcessorMock.SetupGet(x => x.DatabaseType).Returns(databaseTypes.First()); unknownProcessorMock.SetupGet(x => x.DatabaseTypeAliases).Returns(new List<string>()); var context = ExecuteTestMigration(databaseTypes, unknownProcessorMock, m => m.Schema.Table("Foo").Exists()); context.Expressions.Count.ShouldBe(0); unknownProcessorMock.Verify(x => x.TableExists(null, "Foo")); } [Test] public void WillAddUpdateExpression() { var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Update.Table("Foo").Set(new { Id = 1 })); context.Expressions.Count.ShouldBeGreaterThan(0); } private IMigrationContext ExecuteTestMigration(params string[] databaseType) { return ExecuteTestMigration(databaseType, (IMock<IMigrationProcessor>)null); } private IMigrationContext ExecuteTestMigration(IEnumerable<string> databaseType, params Action<IIfDatabaseExpressionRoot>[] fluentEpression) { return ExecuteTestMigration(databaseType, null, fluentEpression); } private IMigrationContext ExecuteTestMigration(IEnumerable<string> databaseType, IMock<IMigrationProcessor> processor, params Action<IIfDatabaseExpressionRoot>[] fluentExpression) { // Initialize var services = ServiceCollectionExtensions.CreateServices() .ConfigureRunner(r => r.WithGlobalConnectionString("No connection")); if (processor != null) { services.WithProcessor(processor); } else { services = services.ConfigureRunner(r => r.AddSQLite()); } var serviceProvider = services .BuildServiceProvider(); var context = serviceProvider.GetRequiredService<IMigrationContext>(); // Arrange var expression = new IfDatabaseExpressionRoot(context, databaseType.ToArray()); // Act if (fluentExpression == null || fluentExpression.Length == 0) { expression.Create.Table("Foo").WithColumn("Id").AsInt16(); } else { foreach (var action in fluentExpression) { action(expression); } } return context; } private IMigrationContext ExecuteTestMigration(Predicate<string> databaseTypePredicate, params Action<IIfDatabaseExpressionRoot>[] fluentExpression) { // Initialize var serviceProvider = ServiceCollectionExtensions.CreateServices() .ConfigureRunner(r => r.AddSQLite().WithGlobalConnectionString("No connection")) .BuildServiceProvider(); var context = serviceProvider.GetRequiredService<IMigrationContext>(); // Arrange var expression = new IfDatabaseExpressionRoot(context, databaseTypePredicate); // Act if (fluentExpression == null || fluentExpression.Length == 0) expression.Create.Table("Foo").WithColumn("Id").AsInt16(); else { foreach (var action in fluentExpression) { action(expression); } } return context; } } }
// // XmlNamespaceManagerTests.cs // // Authors: // Jason Diamond (jason@injektilo.org) // Martin Willemoes Hansen (mwh@sysrq.dk) // // (C) 2002 Jason Diamond http://injektilo.org/ // (C) 2003 Martin Willemoes Hansen // using System; using System.Xml; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XmlNamespaceManagerTests { private XmlNameTable nameTable; private XmlNamespaceManager namespaceManager; [SetUp] public void GetReady () { nameTable = new NameTable (); namespaceManager = new XmlNamespaceManager (nameTable); } [Test] public void NewNamespaceManager () { // make sure that you can call PopScope when there aren't any to pop. Assert.IsTrue (!namespaceManager.PopScope ()); // the following strings should have been added to the name table by the // namespace manager. string xmlnsPrefix = nameTable.Get ("xmlns"); string xmlPrefix = nameTable.Get ("xml"); string stringEmpty = nameTable.Get (String.Empty); string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; // none of them should be null. Assert.IsNotNull (xmlnsPrefix); Assert.IsNotNull (xmlPrefix); Assert.IsNotNull (stringEmpty); Assert.IsNotNull (xmlnsNamespace); Assert.IsNotNull (xmlNamespace); // Microsoft's XmlNamespaceManager reports that these three // namespaces aren't declared for some reason. Assert.IsTrue (!namespaceManager.HasNamespace ("xmlns")); Assert.IsTrue (!namespaceManager.HasNamespace ("xml")); Assert.IsTrue (!namespaceManager.HasNamespace (String.Empty)); // these three namespaces are declared by default. Assert.AreEqual ("http://www.w3.org/2000/xmlns/", namespaceManager.LookupNamespace ("xmlns")); Assert.AreEqual ("http://www.w3.org/XML/1998/namespace", namespaceManager.LookupNamespace ("xml")); Assert.AreEqual (String.Empty, namespaceManager.LookupNamespace (String.Empty)); // the namespaces should be the same references found in the name table. Assert.AreSame (xmlnsNamespace, namespaceManager.LookupNamespace ("xmlns")); Assert.AreSame (xmlNamespace, namespaceManager.LookupNamespace ("xml")); Assert.AreSame (stringEmpty, namespaceManager.LookupNamespace (String.Empty)); // looking up undeclared namespaces should return null. Assert.IsNull (namespaceManager.LookupNamespace ("foo")); } [Test] public void AddNamespace () { // add a new namespace. namespaceManager.AddNamespace ("foo", "http://foo/"); // make sure the new namespace is there. Assert.IsTrue (namespaceManager.HasNamespace ("foo")); Assert.AreEqual ("http://foo/", namespaceManager.LookupNamespace ("foo")); // adding a different namespace with the same prefix // is allowed. namespaceManager.AddNamespace ("foo", "http://foo1/"); Assert.AreEqual ("http://foo1/", namespaceManager.LookupNamespace ("foo")); } [Test] public void AddNamespaceWithNameTable () { // add a known reference to the name table. string fooNamespace = "http://foo/"; nameTable.Add(fooNamespace); // create a new string with the same value but different address. string fooNamespace2 = "http://"; fooNamespace2 += "foo/"; // the references must be different in order for this test to prove anything. Assert.IsTrue (!Object.ReferenceEquals (fooNamespace, fooNamespace2)); // add the namespace with the reference that's not in the name table. namespaceManager.AddNamespace ("foo", fooNamespace2); // the returned reference should be the same one that's in the name table. Assert.AreSame (fooNamespace, namespaceManager.LookupNamespace ("foo")); } [Test] public void AddNamespace_XmlPrefix () { namespaceManager.AddNamespace ("xml", "http://www.w3.org/XML/1998/namespace"); namespaceManager.AddNamespace ("XmL", "http://foo/"); namespaceManager.AddNamespace ("xmlsomething", "http://foo/"); } [Test] [ExpectedException (typeof (ArgumentException))] public void AddNamespace_XmlPrefix_Invalid () { namespaceManager.AddNamespace ("xml", "http://foo/"); } [Test] public void PushScope () { // add a new namespace. namespaceManager.AddNamespace ("foo", "http://foo/"); // make sure the new namespace is there. Assert.IsTrue (namespaceManager.HasNamespace ("foo")); Assert.AreEqual ("http://foo/", namespaceManager.LookupNamespace ("foo")); // push a new scope. namespaceManager.PushScope (); // add a new namespace. namespaceManager.AddNamespace ("bar", "http://bar/"); // make sure the old namespace is not in this new scope. Assert.IsTrue (!namespaceManager.HasNamespace ("foo")); // but we're still supposed to be able to lookup the old namespace. Assert.AreEqual ("http://foo/", namespaceManager.LookupNamespace ("foo")); // make sure the new namespace is there. Assert.IsTrue (namespaceManager.HasNamespace ("bar")); Assert.AreEqual ("http://bar/", namespaceManager.LookupNamespace ("bar")); } [Test] public void PopScope () { // add some namespaces and a scope. PushScope (); // pop the scope. Assert.IsTrue (namespaceManager.PopScope ()); // make sure the first namespace is still there. Assert.IsTrue (namespaceManager.HasNamespace ("foo")); Assert.AreEqual ("http://foo/", namespaceManager.LookupNamespace ("foo")); // make sure the second namespace is no longer there. Assert.IsTrue (!namespaceManager.HasNamespace ("bar")); Assert.IsNull (namespaceManager.LookupNamespace ("bar")); // make sure there are no more scopes to pop. Assert.IsTrue (!namespaceManager.PopScope ()); // make sure that popping again doesn't cause an exception. Assert.IsTrue (!namespaceManager.PopScope ()); } [Test] public void PopScopeMustKeepAddedInScope () { namespaceManager = new XmlNamespaceManager (new NameTable ()); // clear namespaceManager .AddNamespace ("foo", "urn:foo"); // 0 namespaceManager .AddNamespace ("bar", "urn:bar"); // 0 namespaceManager .PushScope (); // 1 namespaceManager .PushScope (); // 2 namespaceManager .PopScope (); // 2 namespaceManager .PopScope (); // 1 namespaceManager .PopScope (); // 0 Assert.AreEqual ("urn:foo", namespaceManager.LookupNamespace ("foo")); Assert.AreEqual ("urn:bar", namespaceManager.LookupNamespace ("bar")); } [Test] public void AddPushPopRemove () { XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); string ns = nsmgr.NameTable.Add ("urn:foo"); nsmgr.AddNamespace ("foo", ns); Assert.AreEqual ("foo", nsmgr.LookupPrefix (ns)); nsmgr.PushScope (); Assert.AreEqual ("foo", nsmgr.LookupPrefix (ns)); nsmgr.PopScope (); Assert.AreEqual ("foo", nsmgr.LookupPrefix (ns)); nsmgr.RemoveNamespace ("foo", ns); Assert.IsNull (nsmgr.LookupPrefix (ns)); } [Test] public void LookupPrefix () { // This test should use an empty nametable. XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); nsmgr.NameTable.Add ("urn:hoge"); nsmgr.NameTable.Add ("urn:fuga"); nsmgr.AddNamespace (string.Empty, "urn:hoge"); Assert.IsNull (nsmgr.LookupPrefix ("urn:fuga")); Assert.AreEqual (String.Empty, nsmgr.LookupPrefix ("urn:hoge")); } string suffix = "oo"; [Test] public void AtomizedLookup () { if (DateTime.Now.Year == 0) suffix = String.Empty; XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); nsmgr.AddNamespace ("foo", "urn:foo"); Assert.IsNotNull (nsmgr.LookupPrefix ("urn:foo")); // FIXME: This returns registered URI inconsistently. // Assert.IsNull (nsmgr.LookupPrefix ("urn:f" + suffix), "It is not atomized and thus should be failed"); } [Test] public void TryToAddPrefixXml () { NameTable nt = new NameTable (); XmlNamespaceManager nsmgr = new XmlNamespaceManager (nt); nsmgr.AddNamespace ("xml", "http://www.w3.org/XML/1998/namespace"); } [Test] [ExpectedException (typeof (ArgumentException))] public void TryToAddPrefixXmlns () { NameTable nt = new NameTable (); XmlNamespaceManager nsmgr = new XmlNamespaceManager (nt); nsmgr.AddNamespace ("xmlns", "http://www.w3.org/2000/xmlns/"); } #if NET_2_0 XmlNamespaceScope l = XmlNamespaceScope.Local; XmlNamespaceScope x = XmlNamespaceScope.ExcludeXml; XmlNamespaceScope a = XmlNamespaceScope.All; [Test] [Category ("NotDotNet")] // MS bug public void GetNamespacesInScope () { XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); Assert.AreEqual (0, nsmgr.GetNamespacesInScope (l).Count, "#1"); Assert.AreEqual (0, nsmgr.GetNamespacesInScope (x).Count, "#2"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (a).Count, "#3"); nsmgr.AddNamespace ("foo", "urn:foo"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (l).Count, "#4"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (x).Count, "#5"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (a).Count, "#6"); // default namespace nsmgr.AddNamespace ("", "urn:empty"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (l).Count, "#7"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (x).Count, "#8"); Assert.AreEqual (3, nsmgr.GetNamespacesInScope (a).Count, "#9"); // PushScope nsmgr.AddNamespace ("foo", "urn:foo"); nsmgr.PushScope (); Assert.AreEqual (0, nsmgr.GetNamespacesInScope (l).Count, "#10"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (x).Count, "#11"); Assert.AreEqual (3, nsmgr.GetNamespacesInScope (a).Count, "#12"); // PopScope nsmgr.PopScope (); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (l).Count, "#13"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (x).Count, "#14"); Assert.AreEqual (3, nsmgr.GetNamespacesInScope (a).Count, "#15"); nsmgr.AddNamespace ("", ""); // MS bug - it should return 1 for .Local but it returns 2 instead. Assert.AreEqual (1, nsmgr.GetNamespacesInScope (l).Count, "#16"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (x).Count, "#17"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (a).Count, "#18"); } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Collections; using System.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { internal sealed class SqlConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class DEFAULT { internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const string AttachDBFilename = ""; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const string Current_Language = ""; internal const string Data_Source = ""; internal const bool Encrypt = false; internal const string FailoverPartner = ""; internal const string Initial_Catalog = ""; internal const bool Integrated_Security = false; internal const int Load_Balance_Timeout = 0; // default of 0 means don't use internal const bool MARS = false; internal const int Max_Pool_Size = 100; internal const int Min_Pool_Size = 0; internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; internal const int Packet_Size = 8000; internal const string Password = ""; internal const bool Persist_Security_Info = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string Type_System_Version = ""; internal const string User_ID = ""; internal const bool User_Instance = false; internal const bool Replication = false; internal const int Connect_Retry_Count = 1; internal const int Connect_Retry_Interval = 10; } // SqlConnection ConnectionString Options // keys must be lowercase! internal static class KEY { internal const string ApplicationIntent = "applicationintent"; internal const string Application_Name = "application name"; internal const string AsynchronousProcessing = "asynchronous processing"; internal const string AttachDBFilename = "attachdbfilename"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; internal const string Data_Source = "data source"; internal const string Encrypt = "encrypt"; internal const string Enlist = "enlist"; internal const string FailoverPartner = "failover partner"; internal const string Initial_Catalog = "initial catalog"; internal const string Integrated_Security = "integrated security"; internal const string Load_Balance_Timeout = "load balance timeout"; internal const string MARS = "multipleactiveresultsets"; internal const string Max_Pool_Size = "max pool size"; internal const string Min_Pool_Size = "min pool size"; internal const string MultiSubnetFailover = "multisubnetfailover"; internal const string Network_Library = "network library"; internal const string Packet_Size = "packet size"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Pooling = "pooling"; internal const string TransactionBinding = "transaction binding"; internal const string TrustServerCertificate = "trustservercertificate"; internal const string Type_System_Version = "type system version"; internal const string User_ID = "user id"; internal const string User_Instance = "user instance"; internal const string Workstation_Id = "workstation id"; internal const string Replication = "replication"; internal const string Connect_Retry_Count = "connectretrycount"; internal const string Connect_Retry_Interval = "connectretryinterval"; } // Constant for the number of duplicate options in the connnection string private static class SYNONYM { // application name internal const string APP = "app"; internal const string Async = "async"; // attachDBFilename internal const string EXTENDED_PROPERTIES = "extended properties"; internal const string INITIAL_FILE_NAME = "initial file name"; // connect timeout internal const string CONNECTION_TIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; // current language internal const string LANGUAGE = "language"; // data source internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORK_ADDRESS = "network address"; // initial catalog internal const string DATABASE = "database"; // integrated security internal const string TRUSTED_CONNECTION = "trusted_connection"; // load balance timeout internal const string Connection_Lifetime = "connection lifetime"; // network library internal const string NET = "net"; internal const string NETWORK = "network"; // password internal const string Pwd = "pwd"; // persist security info internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; // user id internal const string UID = "uid"; internal const string User = "user"; // workstation id internal const string WSID = "wsid"; // make sure to update SynonymCount value below when adding or removing synonyms } internal const int SynonymCount = 18; internal const int DeprecatedSynonymCount = 3; internal enum TypeSystem { Latest = 2008, SQLServer2000 = 2000, SQLServer2005 = 2005, SQLServer2008 = 2008, SQLServer2012 = 2012, } internal static class TYPESYSTEMVERSION { internal const string Latest = "Latest"; internal const string SQL_Server_2000 = "SQL Server 2000"; internal const string SQL_Server_2005 = "SQL Server 2005"; internal const string SQL_Server_2008 = "SQL Server 2008"; internal const string SQL_Server_2012 = "SQL Server 2012"; } static private Hashtable s_sqlClientSynonyms; private readonly bool _integratedSecurity; private readonly bool _encrypt; private readonly bool _trustServerCertificate; private readonly bool _mars; private readonly bool _persistSecurityInfo; private readonly bool _pooling; private readonly bool _replication; private readonly bool _userInstance; private readonly bool _multiSubnetFailover; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; private readonly int _minPoolSize; private readonly int _packetSize; private readonly int _connectRetryCount; private readonly int _connectRetryInterval; private readonly ApplicationIntent _applicationIntent; private readonly string _applicationName; private readonly string _attachDBFileName; private readonly string _currentLanguage; private readonly string _dataSource; private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB private readonly string _failoverPartner; private readonly string _initialCatalog; private readonly string _password; private readonly string _userID; private readonly string _workstationId; private readonly TypeSystem _typeSystemVersion; internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms()) { ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing); ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset); ThrowUnsupportedIfKeywordSet(KEY.Context_Connection); ThrowUnsupportedIfKeywordSet(KEY.Enlist); ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding); // Network Library has its own special error message if (ContainsKey(KEY.Network_Library)) { throw SQL.NetworkLibraryKeywordNotSupported(); } _integratedSecurity = ConvertValueToIntegratedSecurity(); _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } if (true == _userInstance && !ADP.IsEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (ADP.IsEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount < 0) || (_connectRetryCount > 255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } } // This c-tor is used to create SSE and user instance connection strings when user instance is set to true // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _encrypt = connectionOptions._encrypt; _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _workstationId = connectionOptions._workstationId; _typeSystemVersion = connectionOptions._typeSystemVersion; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); } internal bool IntegratedSecurity { get { return _integratedSecurity; } } // We always initialize in Async mode so that both synchronous and asynchronous methods // will work. In the future we can deprecate the keyword entirely. internal bool Asynchronous { get { return true; } } // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security internal bool ConnectionReset { get { return true; } } // internal bool EnableUdtDownload { get { return _enableUdtDownload;} } internal bool Encrypt { get { return _encrypt; } } internal bool TrustServerCertificate { get { return _trustServerCertificate; } } internal bool MARS { get { return _mars; } } internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } } internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } } internal bool Pooling { get { return _pooling; } } internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } internal int MinPoolSize { get { return _minPoolSize; } } internal int PacketSize { get { return _packetSize; } } internal int ConnectRetryCount { get { return _connectRetryCount; } } internal int ConnectRetryInterval { get { return _connectRetryInterval; } } internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } } internal string ApplicationName { get { return _applicationName; } } internal string AttachDBFilename { get { return _attachDBFileName; } } internal string CurrentLanguage { get { return _currentLanguage; } } internal string DataSource { get { return _dataSource; } } internal string LocalDBInstance { get { return _localDBInstance; } } internal string FailoverPartner { get { return _failoverPartner; } } internal string InitialCatalog { get { return _initialCatalog; } } internal string Password { get { return _password; } } internal string UserID { get { return _userID; } } internal string WorkstationId { get { return _workstationId; } } internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } } private static bool CompareHostName(ref string host, string name, bool fixup) { // same computer name or same computer name + "\named instance" bool equal = false; if (host.Equals(name, StringComparison.OrdinalIgnoreCase)) { if (fixup) { host = "."; } equal = true; } else if (host.StartsWith(name + @"\", StringComparison.OrdinalIgnoreCase)) { if (fixup) { host = "." + host.Substring(name.Length); } equal = true; } return equal; } // this hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string internal static Hashtable GetParseSynonyms() { Hashtable hash = s_sqlClientSynonyms; if (null == hash) { hash = new Hashtable(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount); hash.Add(KEY.ApplicationIntent, KEY.ApplicationIntent); hash.Add(KEY.Application_Name, KEY.Application_Name); hash.Add(KEY.AsynchronousProcessing, KEY.AsynchronousProcessing); hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename); hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout); hash.Add(KEY.Connection_Reset, KEY.Connection_Reset); hash.Add(KEY.Context_Connection, KEY.Context_Connection); hash.Add(KEY.Current_Language, KEY.Current_Language); hash.Add(KEY.Data_Source, KEY.Data_Source); hash.Add(KEY.Encrypt, KEY.Encrypt); hash.Add(KEY.Enlist, KEY.Enlist); hash.Add(KEY.FailoverPartner, KEY.FailoverPartner); hash.Add(KEY.Initial_Catalog, KEY.Initial_Catalog); hash.Add(KEY.Integrated_Security, KEY.Integrated_Security); hash.Add(KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout); hash.Add(KEY.MARS, KEY.MARS); hash.Add(KEY.Max_Pool_Size, KEY.Max_Pool_Size); hash.Add(KEY.Min_Pool_Size, KEY.Min_Pool_Size); hash.Add(KEY.MultiSubnetFailover, KEY.MultiSubnetFailover); hash.Add(KEY.Network_Library, KEY.Network_Library); hash.Add(KEY.Packet_Size, KEY.Packet_Size); hash.Add(KEY.Password, KEY.Password); hash.Add(KEY.Persist_Security_Info, KEY.Persist_Security_Info); hash.Add(KEY.Pooling, KEY.Pooling); hash.Add(KEY.Replication, KEY.Replication); hash.Add(KEY.TrustServerCertificate, KEY.TrustServerCertificate); hash.Add(KEY.TransactionBinding, KEY.TransactionBinding); hash.Add(KEY.Type_System_Version, KEY.Type_System_Version); hash.Add(KEY.User_ID, KEY.User_ID); hash.Add(KEY.User_Instance, KEY.User_Instance); hash.Add(KEY.Workstation_Id, KEY.Workstation_Id); hash.Add(KEY.Connect_Retry_Count, KEY.Connect_Retry_Count); hash.Add(KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval); hash.Add(SYNONYM.APP, KEY.Application_Name); hash.Add(SYNONYM.Async, KEY.AsynchronousProcessing); hash.Add(SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename); hash.Add(SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename); hash.Add(SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.LANGUAGE, KEY.Current_Language); hash.Add(SYNONYM.ADDR, KEY.Data_Source); hash.Add(SYNONYM.ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.NETWORK_ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.SERVER, KEY.Data_Source); hash.Add(SYNONYM.DATABASE, KEY.Initial_Catalog); hash.Add(SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security); hash.Add(SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout); hash.Add(SYNONYM.NET, KEY.Network_Library); hash.Add(SYNONYM.NETWORK, KEY.Network_Library); hash.Add(SYNONYM.Pwd, KEY.Password); hash.Add(SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info); hash.Add(SYNONYM.UID, KEY.User_ID); hash.Add(SYNONYM.User, KEY.User_ID); hash.Add(SYNONYM.WSID, KEY.Workstation_Id); Debug.Assert(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount == hash.Count, "incorrect initial ParseSynonyms size"); s_sqlClientSynonyms = hash; } return hash; } internal string ObtainWorkstationId() { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; if (null == result) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted // the information is shared with the server, but not directly with the user result = string.Empty; } return result; } private void ValidateValueLength(string value, int limit, string key) { if (limit < value.Length) { throw ADP.InvalidConnectionOptionValueLength(key, limit); } } internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent() { object value = base.Parsetable[KEY.ApplicationIntent]; if (value == null) { return DEFAULT.ApplicationIntent; } // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor, // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool) try { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } // ArgumentException and other types are raised as is (no wrapping) } internal void ThrowUnsupportedIfKeywordSet(string keyword) { if (ContainsKey(keyword)) { throw SQL.UnsupportedKeyword(keyword); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System { // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [Runtime.Versioning.NonVersionable] // This only applies to field layout [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>, ISpanFormattable { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; // Do not rename (binary serialization) private short _b; // Do not rename (binary serialization) private short _c; // Do not rename (binary serialization) private byte _d; // Do not rename (binary serialization) private byte _e; // Do not rename (binary serialization) private byte _f; // Do not rename (binary serialization) private byte _g; // Do not rename (binary serialization) private byte _h; // Do not rename (binary serialization) private byte _i; // Do not rename (binary serialization) private byte _j; // Do not rename (binary serialization) private byte _k; // Do not rename (binary serialization) //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. public Guid(byte[] b) : this(new ReadOnlySpan<byte>(b ?? throw new ArgumentNullException(nameof(b)))) { } // Creates a new guid from a read-only span. public Guid(ReadOnlySpan<byte> b) { if (b.Length != 16) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b)); _a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0]; _b = (short)(b[5] << 8 | b[4]); _c = (short)(b[7] << 8 | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d == null) throw new ArgumentNullException(nameof(d)); // Check that array is not too big if (d.Length != 8) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid _parsedGuid; internal GuidParseThrowStyle _throwStyle; private ParseFailureKind _failure; private string _failureMessageID; private object _failureMessageFormatArgument; private string _failureArgumentName; private Exception _innerException; internal void Init(GuidParseThrowStyle canThrow) { _throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { _failure = ParseFailureKind.NativeException; _innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); _failure = failure; _failureMessageID = failureMessageID; _failureMessageFormatArgument = failureMessageFormatArgument; _failureArgumentName = failureArgumentName; _innerException = innerException; if (_throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(_failureArgumentName, SR.GetResourceString(_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(SR.GetResourceString(_failureMessageID), _innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(SR.Format(SR.GetResourceString(_failureMessageID), _failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(SR.GetResourceString(_failureMessageID)); case ParseFailureKind.NativeException: return _innerException; default: Debug.Fail("Unknown GuidParseFailure: " + _failure); return new FormatException(SR.Format_GuidUnrecognized); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(string g) { if (g == null) { throw new ArgumentNullException(nameof(g)); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result._parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(string input) => Parse(input != null ? (ReadOnlySpan<char>)input : throw new ArgumentNullException(nameof(input))); public static Guid Parse(ReadOnlySpan<char> input) { GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result._parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(string input, out Guid result) { if (input == null) { result = default(Guid); return false; } return TryParse((ReadOnlySpan<char>)input, out result); } public static bool TryParse(ReadOnlySpan<char> input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult._parsedGuid; return true; } else { result = default(Guid); return false; } } public static Guid ParseExact(string input, string format) => ParseExact( input != null ? (ReadOnlySpan<char>)input : throw new ArgumentNullException(nameof(input)), format != null ? (ReadOnlySpan<char>)format : throw new ArgumentNullException(nameof(format))); public static Guid ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format) { if (format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } GuidStyles style; switch (format[0]) { case 'D': case 'd': style = GuidStyles.DigitFormat; break; case 'N': case 'n': style = GuidStyles.NumberFormat; break; case 'B': case 'b': style = GuidStyles.BraceFormat; break; case 'P': case 'p': style = GuidStyles.ParenthesisFormat; break; case 'X': case 'x': style = GuidStyles.HexFormat; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result._parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(string input, string format, out Guid result) { if (input == null) { result = default(Guid); return false; } return TryParseExact((ReadOnlySpan<char>)input, format, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, out Guid result) { if (format.Length != 1) { result = default(Guid); return false; } GuidStyles style; switch (format[0]) { case 'D': case 'd': style = GuidStyles.DigitFormat; break; case 'N': case 'n': style = GuidStyles.NumberFormat; break; case 'B': case 'b': style = GuidStyles.BraceFormat; break; case 'P': case 'p': style = GuidStyles.ParenthesisFormat; break; case 'X': case 'x': style = GuidStyles.HexFormat; break; default: // invalid guid format specification result = default(Guid); return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult._parsedGuid; return true; } else { result = default(Guid); return false; } } private static bool TryParseGuid(ReadOnlySpan<char> guidString, GuidStyles flags, ref GuidResult result) { guidString = guidString.Trim(); // Remove whitespace from beginning and end if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } // Check for dashes bool dashesExistInString = guidString.IndexOf('-') >= 0; if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch (IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(ReadOnlySpan<char> guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if (guidString.Length == 0 || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace)); return false; } // Check for '0x' if (!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } if (!StringToInt(guidString.Slice(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result)) return false; // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } // Read in the number if (!StringToShort(guidString.Slice(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result)) return false; // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } // Read in the number if (!StringToShort(guidString.Slice(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result)) return false; // Check for '{' if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace)); return false; } // Prepare for loop numLen++; Span<byte> bytes = stackalloc byte[8]; for (int i = 0; i < bytes.Length; i++) { // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if (i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBraceAfterLastNumber)); return false; } } // Read in the number int signedNumber; if (!StringToInt(guidString.Slice(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) { return false; } uint number = (uint)signedNumber; // check for overflow if (number > 255) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Overflow_Byte)); return false; } bytes[i] = (byte)number; } result._parsedGuid._d = bytes[0]; result._parsedGuid._e = bytes[1]; result._parsedGuid._f = bytes[2]; result._parsedGuid._g = bytes[3]; result._parsedGuid._h = bytes[4]; result._parsedGuid._i = bytes[5]; result._parsedGuid._j = bytes[6]; result._parsedGuid._k = bytes[7]; // Check for last '}' if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidEndBrace)); return false; } // Check if we have extra characters at the end if (numStart + numLen + 1 != guidString.Length - 1) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_ExtraJunkAtEnd)); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(ReadOnlySpan<char> guidString, ref GuidResult result) { int startPos = 0; int temp; long templ; int currentPos = 0; if (guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } for (int i = 0; i < guidString.Length; i++) { char ch = guidString[i]; if (ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = char.ToUpperInvariant(ch); if (upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar)); return false; } if (!StringToInt(guidString.Slice(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Slice(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Slice(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Slice(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } result._parsedGuid._d = (byte)(temp >> 8); result._parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result._parsedGuid._f = (byte)(temp >> 8); result._parsedGuid._g = (byte)(temp); temp = (int)(templ); result._parsedGuid._h = (byte)(temp >> 24); result._parsedGuid._i = (byte)(temp >> 16); result._parsedGuid._j = (byte)(temp >> 8); result._parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(ReadOnlySpan<char> guidString, ref GuidResult result) { int startPos = 0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0] == '{') { if (guidString.Length != 38 || guidString[37] != '}') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } startPos = 1; } else if (guidString[0] == '(') { if (guidString.Length != 38 || guidString[37] != ')') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } startPos = 1; } else if (guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } if (guidString[8 + startPos] != '-' || guidString[13 + startPos] != '-' || guidString[18 + startPos] != '-' || guidString[23 + startPos] != '-') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidDashes)); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result._parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result._parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result._parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos = currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } result._parsedGuid._d = (byte)(temp >> 8); result._parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result._parsedGuid._f = (byte)(temp >> 8); result._parsedGuid._g = (byte)(temp); temp = (int)(templ); result._parsedGuid._h = (byte)(temp >> 24); result._parsedGuid._i = (byte)(temp >> 16); result._parsedGuid._j = (byte)(temp >> 8); result._parsedGuid._k = (byte)(temp); return true; } private static bool StringToShort(ReadOnlySpan<char> str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { int parsePos = 0; return StringToShort(str, ref parsePos, requiredLength, flags, out result, ref parseResult); } private static bool StringToShort(ReadOnlySpan<char> str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, ref parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } private static bool StringToInt(ReadOnlySpan<char> str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { int parsePos = 0; return StringToInt(str, ref parsePos, requiredLength, flags, out result, ref parseResult); } private static bool StringToInt(ReadOnlySpan<char> str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = parsePos; try { result = ParseNumbers.StringToInt(str, 16, flags, ref parsePos); } catch (OverflowException ex) { if (parseResult._throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(SR.Format_GuidUnrecognized, ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult._throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar)); return false; } return true; } private static unsafe bool StringToLong(ReadOnlySpan<char> str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, ref parsePos); } catch (OverflowException ex) { if (parseResult._throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(SR.Format_GuidUnrecognized, ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult._throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static ReadOnlySpan<char> EatAllWhitespace(ReadOnlySpan<char> str) { // Find the first whitespace character. If there is none, just return the input. int i; for (i = 0; i < str.Length && !char.IsWhiteSpace(str[i]); i++) ; if (i == str.Length) { return str; } // There was at least one whitespace. Copy over everything prior to it to a new array. var chArr = new char[str.Length]; int newLength = 0; if (i > 0) { newLength = i; str.Slice(0, i).CopyTo(chArr); } // Loop through the remaining chars, copying over non-whitespace. for (; i < str.Length; i++) { char c = str[i]; if (!char.IsWhiteSpace(c)) { chArr[newLength++] = c; } } // Return the string with the whitespace removed. return new ReadOnlySpan<char>(chArr, 0, newLength); } private static bool IsHexPrefix(ReadOnlySpan<char> str, int i) => i + 1 < str.Length && str[i] == '0' && (str[i + 1] == 'x' || char.ToLowerInvariant(str[i + 1]) == 'x'); [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteByteHelper(Span<byte> destination) { destination[0] = (byte)(_a); destination[1] = (byte)(_a >> 8); destination[2] = (byte)(_a >> 16); destination[3] = (byte)(_a >> 24); destination[4] = (byte)(_b); destination[5] = (byte)(_b >> 8); destination[6] = (byte)(_c); destination[7] = (byte)(_c >> 8); destination[8] = _d; destination[9] = _e; destination[10] = _f; destination[11] = _g; destination[12] = _h; destination[13] = _i; destination[14] = _j; destination[15] = _k; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { var g = new byte[16]; WriteByteHelper(g); return g; } // Returns whether bytes are sucessfully written to given span. public bool TryWriteBytes(Span<byte> destination) { if (destination.Length < 16) return false; WriteByteHelper(destination); return true; } // Returns the guid in "registry" format. public override string ToString() { return ToString("D", null); } public override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. return _a ^ Unsafe.Add(ref _a, 1) ^ Unsafe.Add(ref _a, 2) ^ Unsafe.Add(ref _a, 3); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(object o) { Guid g; // Check that o is a Guid first if (o == null || !(o is Guid)) return false; else g = (Guid)o; // Now compare each of the elements return g._a == _a && Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) && Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) && Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3); } public bool Equals(Guid g) { // Now compare each of the elements return g._a == _a && Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) && Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) && Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3); } private int GetResult(uint me, uint them) { if (me < them) { return -1; } return 1; } public int CompareTo(object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value)); } Guid g = (Guid)value; if (g._a != _a) { return GetResult((uint)_a, (uint)g._a); } if (g._b != _b) { return GetResult((uint)_b, (uint)g._b); } if (g._c != _c) { return GetResult((uint)_c, (uint)g._c); } if (g._d != _d) { return GetResult(_d, g._d); } if (g._e != _e) { return GetResult(_e, g._e); } if (g._f != _f) { return GetResult(_f, g._f); } if (g._g != _g) { return GetResult(_g, g._g); } if (g._h != _h) { return GetResult(_h, g._h); } if (g._i != _i) { return GetResult(_i, g._i); } if (g._j != _j) { return GetResult(_j, g._j); } if (g._k != _k) { return GetResult(_k, g._k); } return 0; } public int CompareTo(Guid value) { if (value._a != _a) { return GetResult((uint)_a, (uint)value._a); } if (value._b != _b) { return GetResult((uint)_b, (uint)value._b); } if (value._c != _c) { return GetResult((uint)_c, (uint)value._c); } if (value._d != _d) { return GetResult(_d, value._d); } if (value._e != _e) { return GetResult(_e, value._e); } if (value._f != _f) { return GetResult(_f, value._f); } if (value._g != _g) { return GetResult(_g, value._g); } if (value._h != _h) { return GetResult(_h, value._h); } if (value._i != _i) { return GetResult(_i, value._i); } if (value._j != _j) { return GetResult(_j, value._j); } if (value._k != _k) { return GetResult(_k, value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements return a._a == b._a && Unsafe.Add(ref a._a, 1) == Unsafe.Add(ref b._a, 1) && Unsafe.Add(ref a._a, 2) == Unsafe.Add(ref b._a, 2) && Unsafe.Add(ref a._a, 3) == Unsafe.Add(ref b._a, 3); } public static bool operator !=(Guid a, Guid b) { // Now compare each of the elements return a._a != b._a || Unsafe.Add(ref a._a, 1) != Unsafe.Add(ref b._a, 1) || Unsafe.Add(ref a._a, 2) != Unsafe.Add(ref b._a, 2) || Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3); } public string ToString(string format) { return ToString(format, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static char HexToChar(int a) { a = a & 0xf; return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); } unsafe private static int HexsToChars(char* guidChars, int a, int b) { guidChars[0] = HexToChar(a >> 4); guidChars[1] = HexToChar(a); guidChars[2] = HexToChar(b >> 4); guidChars[3] = HexToChar(b); return 4; } unsafe private static int HexsToCharsHexOutput(char* guidChars, int a, int b) { guidChars[0] = '0'; guidChars[1] = 'x'; guidChars[2] = HexToChar(a >> 4); guidChars[3] = HexToChar(a); guidChars[4] = ','; guidChars[5] = '0'; guidChars[6] = 'x'; guidChars[7] = HexToChar(b >> 4); guidChars[8] = HexToChar(b); return 9; } // IFormattable interface // We currently ignore provider public string ToString(string format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; // all acceptable format strings are of length 1 if (format.Length != 1) throw new FormatException(SR.Format_InvalidGuidFormatSpecification); int guidSize; switch (format[0]) { case 'D': case 'd': guidSize = 36; break; case 'N': case 'n': guidSize = 32; break; case 'B': case 'b': case 'P': case 'p': guidSize = 38; break; case 'X': case 'x': guidSize = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } string guidString = string.FastAllocateString(guidSize); int bytesWritten; bool result = TryFormat(new Span<char>(ref guidString.GetRawStringData(), guidString.Length), out bytesWritten, format); Debug.Assert(result && bytesWritten == guidString.Length, "Formatting guid should have succeeded."); return guidString; } // Returns whether the guid is successfully formatted as a span. public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default) { if (format.Length == 0) format = "D"; // all acceptable format strings are of length 1 if (format.Length != 1) throw new FormatException(SR.Format_InvalidGuidFormatSpecification); bool dash = true; bool hex = false; int braces = 0; int guidSize; switch (format[0]) { case 'D': case 'd': guidSize = 36; break; case 'N': case 'n': dash = false; guidSize = 32; break; case 'B': case 'b': braces = '{' + ('}' << 16); guidSize = 38; break; case 'P': case 'p': braces = '(' + (')' << 16); guidSize = 38; break; case 'X': case 'x': braces = '{' + ('}' << 16); dash = false; hex = true; guidSize = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } if (destination.Length < guidSize) { charsWritten = 0; return false; } unsafe { fixed (char* guidChars = &MemoryMarshal.GetReference(destination)) { char * p = guidChars; if (braces != 0) *p++ = (char)braces; if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _a >> 24, _a >> 16); p += HexsToChars(p, _a >> 8, _a); *p++ = ','; *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _b >> 8, _b); *p++ = ','; *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _c >> 8, _c); *p++ = ','; *p++ = '{'; p += HexsToCharsHexOutput(p, _d, _e); *p++ = ','; p += HexsToCharsHexOutput(p, _f, _g); *p++ = ','; p += HexsToCharsHexOutput(p, _h, _i); *p++ = ','; p += HexsToCharsHexOutput(p, _j, _k); *p++ = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] p += HexsToChars(p, _a >> 24, _a >> 16); p += HexsToChars(p, _a >> 8, _a); if (dash) *p++ = '-'; p += HexsToChars(p, _b >> 8, _b); if (dash) *p++ = '-'; p += HexsToChars(p, _c >> 8, _c); if (dash) *p++ = '-'; p += HexsToChars(p, _d, _e); if (dash) *p++ = '-'; p += HexsToChars(p, _f, _g); p += HexsToChars(p, _h, _i); p += HexsToChars(p, _j, _k); } if (braces != 0) *p++ = (char)(braces >> 16); Debug.Assert(p - guidChars == guidSize); } } charsWritten = guidSize; return true; } bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider) { // Like with the IFormattable implementation, provider is ignored. return TryFormat(destination, out charsWritten, format); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; namespace Microsoft.TemplateEngine.Utils { public class InMemoryFileSystem : IPhysicalFileSystem, IFileLastWriteTimeSource { private class FileSystemDirectory { public string Name { get; } public string FullPath { get; } public Dictionary<string, FileSystemDirectory> Directories { get; } public Dictionary<string, FileSystemFile> Files { get; } public FileSystemDirectory(string name, string fullPath) { Name = name; FullPath = fullPath; Directories = new Dictionary<string, FileSystemDirectory>(); Files = new Dictionary<string, FileSystemFile>(); } } private readonly FileSystemDirectory _root; private readonly IPhysicalFileSystem _basis; private class FileSystemFile { private byte[] _data; private int _currentReaders; private int _currentWriters; private readonly object _sync = new object(); public string Name { get; } public string FullPath { get; } public FileSystemFile(string name, string fullPath) { Name = name; FullPath = fullPath; _data = new byte[0]; } public Stream OpenRead() { if (_currentWriters > 0) { throw new IOException("File is currently locked for writing"); } lock (_sync) { if (_currentWriters > 0) { throw new IOException("File is currently locked for writing"); } ++_currentReaders; return new DisposingStream(new MemoryStream(_data, false), () => { lock (_sync) { --_currentReaders; } }); } } public Stream OpenWrite() { if (_currentReaders > 0) { throw new IOException("File is currently locked for reading"); } if (_currentWriters > 0) { throw new IOException("File is currently locked for writing"); } lock (_sync) { if (_currentReaders > 0) { throw new IOException("File is currently locked for reading"); } if (_currentWriters > 0) { throw new IOException("File is currently locked for writing"); } ++_currentWriters; MemoryStream target = new MemoryStream(); return new DisposingStream(target, () => { lock (_sync) { --_currentWriters; _data = new byte[target.Length]; target.Position = 0; target.Read(_data, 0, _data.Length); LastWriteTimeUtc = DateTime.UtcNow; } }); } } public FileAttributes Attributes { get; set; } public DateTime LastWriteTimeUtc { get; private set; } } private class DisposingStream : Stream { private bool _isDisposed; private readonly Stream _basis; private readonly Action _onDispose; public DisposingStream(Stream basis, Action onDispose) { _onDispose = onDispose; _basis = basis; } public override bool CanRead => _basis.CanRead; public override bool CanSeek => _basis.CanSeek; public override bool CanWrite => _basis.CanWrite; public override long Length => _basis.Length; public override long Position { get => _basis.Position; set => _basis.Position = value; } public override void Flush() => _basis.Flush(); public override int Read(byte[] buffer, int offset, int count) => _basis.Read(buffer, offset, count); public override long Seek(long offset, SeekOrigin origin) => _basis.Seek(offset, origin); public override void SetLength(long value) => _basis.SetLength(value); public override void Write(byte[] buffer, int offset, int count) => _basis.Write(buffer, offset, count); protected override void Dispose(bool disposing) { if (!_isDisposed) { _isDisposed = true; _onDispose(); } base.Dispose(disposing); } } public InMemoryFileSystem(string root, IPhysicalFileSystem basis) { _basis = basis; _root = new FileSystemDirectory(Path.GetFileName(root.TrimEnd('/', '\\')), root); IsPathInCone(root, out root); _root = new FileSystemDirectory(Path.GetFileName(root.TrimEnd('/', '\\')), root); } public void CreateDirectory(string path) { if (!IsPathInCone(path, out string processedPath)) { _basis.CreateDirectory(path); return; } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); if (string.IsNullOrEmpty(rel)) { return; } string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } } public Stream CreateFile(string path) { if (!IsPathInCone(path, out string processedPath)) { return _basis.CreateFile(path); } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } FileSystemFile targetFile; if (!currentDir.Files.TryGetValue(parts[parts.Length - 1], out targetFile)) { targetFile = new FileSystemFile(parts[parts.Length - 1], Path.Combine(currentDir.FullPath, parts[parts.Length - 1])); currentDir.Files[parts[parts.Length - 1]] = targetFile; } return targetFile.OpenWrite(); } public void DirectoryDelete(string path, bool recursive) { if (!IsPathInCone(path, out string processedPath)) { //TODO: handle cases where a portion of what would be deleted is inside our cone // and parts are outside _basis.DirectoryDelete(path, recursive); return; } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); if (string.IsNullOrEmpty(rel)) { return; } string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; FileSystemDirectory parent = null; for (int i = 0; i < parts.Length; ++i) { parent = currentDir; FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { return; } currentDir = dir; } if (!recursive && (currentDir.Directories.Count > 0 || currentDir.Files.Count > 0)) { throw new IOException("Directory is not empty"); } parent.Directories.Remove(currentDir.Name); } public bool DirectoryExists(string directory) { if (!IsPathInCone(directory, out string processedPath)) { return _basis.DirectoryExists(directory); } directory = processedPath; string rel = directory.Substring(_root.FullPath.Length).Trim('/', '\\'); if (string.IsNullOrEmpty(rel)) { return true; } string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { return false; } currentDir = dir; } return true; } public IEnumerable<string> EnumerateDirectories(string path, string pattern, SearchOption searchOption) { if (!IsPathInCone(path, out string processedPath)) { //TODO: Handle cases where part of the directory set is inside our cone and part is not foreach (string s in _basis.EnumerateDirectories(path, pattern, searchOption)) { yield return s; } yield break; } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); FileSystemDirectory currentDir = _root; if (!string.IsNullOrEmpty(rel)) { string[] parts = rel.Split('/', '\\'); for (int i = 0; i < parts.Length; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { yield break; } currentDir = dir; } } Regex rx = new Regex(Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".")); if (searchOption == SearchOption.TopDirectoryOnly) { foreach (KeyValuePair<string, FileSystemDirectory> entry in currentDir.Directories) { if (rx.IsMatch(entry.Key)) { yield return entry.Value.FullPath; } } yield break; } Stack<IEnumerator<KeyValuePair<string, FileSystemDirectory>>> directories = new Stack<IEnumerator<KeyValuePair<string, FileSystemDirectory>>>(); IEnumerator<KeyValuePair<string, FileSystemDirectory>> current = currentDir.Directories.GetEnumerator(); bool moveNext; while ((moveNext = current.MoveNext()) || directories.Count > 0) { while (!moveNext) { current.Dispose(); if (directories.Count == 0) { break; } current = directories.Pop(); moveNext = current.MoveNext(); } if (!moveNext) { break; } if (rx.IsMatch(current.Current.Key)) { yield return current.Current.Value.FullPath; } directories.Push(current); current = current.Current.Value.Directories.GetEnumerator(); } } public IEnumerable<string> EnumerateFiles(string path, string pattern, SearchOption searchOption) { if (!IsPathInCone(path, out string processedPath)) { //TODO: Handle cases where part of the directory set is inside our cone and part is not foreach (string s in _basis.EnumerateFiles(path, pattern, searchOption)) { yield return s; } yield break; } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); FileSystemDirectory currentDir = _root; if (!string.IsNullOrEmpty(rel)) { string[] parts = rel.Split('/', '\\'); for (int i = 0; i < parts.Length; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { yield break; } currentDir = dir; } } Regex rx = new Regex(Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".")); foreach (KeyValuePair<string, FileSystemFile> entry in currentDir.Files) { if (rx.IsMatch(entry.Key)) { yield return entry.Value.FullPath; } } if (searchOption == SearchOption.TopDirectoryOnly) { yield break; } Stack<IEnumerator<KeyValuePair<string, FileSystemDirectory>>> directories = new Stack<IEnumerator<KeyValuePair<string, FileSystemDirectory>>>(); Stack<FileSystemDirectory> parentDirectories = new Stack<FileSystemDirectory>(); IEnumerator<KeyValuePair<string, FileSystemDirectory>> current = currentDir.Directories.GetEnumerator(); bool moveNext; while ((moveNext = current.MoveNext()) || directories.Count > 0) { while (!moveNext) { current.Dispose(); if (directories.Count == 0) { break; } current = directories.Pop(); moveNext = current.MoveNext(); } if (!moveNext) { break; } foreach (KeyValuePair<string, FileSystemFile> entry in current.Current.Value.Files) { if (rx.IsMatch(entry.Key)) { yield return entry.Value.FullPath; } } directories.Push(current); current = current.Current.Value.Directories.GetEnumerator(); } } public IEnumerable<string> EnumerateFileSystemEntries(string directoryName, string pattern, SearchOption searchOption) { if (!IsPathInCone(directoryName, out string processedPath)) { //TODO: Handle cases where part of the directory set is inside our cone and part is not foreach (string s in _basis.EnumerateFileSystemEntries(directoryName, pattern, searchOption)) { yield return s; } yield break; } directoryName = processedPath; string rel = directoryName.Substring(_root.FullPath.Length).Trim('/', '\\'); FileSystemDirectory currentDir = _root; if (!string.IsNullOrEmpty(rel)) { string[] parts = rel.Split('/', '\\'); for (int i = 0; i < parts.Length; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { yield break; } currentDir = dir; } } Regex rx = new Regex("^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$"); foreach (KeyValuePair<string, FileSystemFile> entry in currentDir.Files) { if (rx.IsMatch(entry.Key)) { yield return entry.Value.FullPath; } } foreach (KeyValuePair<string, FileSystemDirectory> entry in currentDir.Directories) { if (rx.IsMatch(entry.Key)) { yield return entry.Value.FullPath; } } if (searchOption == SearchOption.TopDirectoryOnly) { yield break; } Stack<IEnumerator<KeyValuePair<string, FileSystemDirectory>>> directories = new Stack<IEnumerator<KeyValuePair<string, FileSystemDirectory>>>(); IEnumerator<KeyValuePair<string, FileSystemDirectory>> current = currentDir.Directories.GetEnumerator(); bool moveNext; while ((moveNext = current.MoveNext()) || directories.Count > 0) { while (!moveNext) { current.Dispose(); if (directories.Count == 0) { break; } current = directories.Pop(); moveNext = current.MoveNext(); } if (!moveNext) { break; } if (rx.IsMatch(current.Current.Key)) { yield return current.Current.Value.FullPath; } foreach (KeyValuePair<string, FileSystemFile> entry in currentDir.Files) { if (rx.IsMatch(entry.Key)) { yield return entry.Value.FullPath; } } directories.Push(current); current = current.Current.Value.Directories.GetEnumerator(); } } public void FileCopy(string sourcePath, string targetPath, bool overwrite) { if (!overwrite && FileExists(targetPath)) { throw new IOException($"File already exists {targetPath}"); } using (Stream s = OpenRead(sourcePath)) using (Stream t = CreateFile(targetPath)) { s.CopyTo(t); } } public void FileDelete(string path) { if (!IsPathInCone(path, out string processedPath)) { _basis.FileDelete(path); return; } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } currentDir.Files.Remove(parts[parts.Length - 1]); } public bool FileExists(string file) { if (!IsPathInCone(file, out string processedPath)) { return _basis.FileExists(file); } file = processedPath; string rel = file.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { return false; } currentDir = dir; } return currentDir.Files.ContainsKey(parts[parts.Length - 1]); } public string GetCurrentDirectory() { return Directory.GetCurrentDirectory(); } public Stream OpenRead(string path) { if (!IsPathInCone(path, out string processedPath)) { return _basis.OpenRead(path); } path = processedPath; string rel = path.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } FileSystemFile targetFile; if (!currentDir.Files.TryGetValue(parts[parts.Length - 1], out targetFile)) { throw new FileNotFoundException("File not found", path); } return targetFile.OpenRead(); } public string ReadAllText(string path) { using (Stream s = OpenRead(path)) using (StreamReader r = new StreamReader(s, Encoding.UTF8, true, 8192, true)) { return r.ReadToEnd(); } } public void WriteAllText(string path, string value) { using (Stream s = CreateFile(path)) using (StreamWriter r = new StreamWriter(s, Encoding.UTF8, 8192, true)) { r.Write(value); } } private bool IsPathInCone(string path, out string processedPath) { if (!Path.IsPathRooted(path)) { path = Path.Combine(GetCurrentDirectory(), path); } path = path.Replace('\\', '/'); bool leadSlash = path[0] == '/'; if (leadSlash) { path = path.Substring(1); } string[] parts = path.Split('/'); List<string> realParts = new List<string>(); for (int i = 0; i < parts.Length; ++i) { if (string.IsNullOrEmpty(parts[i])) { continue; } switch (parts[i]) { case ".": continue; case "..": realParts.RemoveAt(realParts.Count - 1); break; default: realParts.Add(parts[i]); break; } } if (leadSlash) { realParts.Insert(0, ""); } processedPath = string.Join(Path.DirectorySeparatorChar + "", realParts); if (processedPath.Equals(_root.FullPath) || processedPath.StartsWith(_root.FullPath.TrimEnd('/', '\\') + Path.DirectorySeparatorChar)) { return true; } else { return false; } } public FileAttributes GetFileAttributes(string file) { if (!IsPathInCone(file, out string processedPath)) { return _basis.GetFileAttributes(file); } file = processedPath; string rel = file.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } FileSystemFile targetFile; if (!currentDir.Files.TryGetValue(parts[parts.Length - 1], out targetFile)) { throw new FileNotFoundException("File not found", file); } return targetFile.Attributes; } public void SetFileAttributes(string file, FileAttributes attributes) { if (!IsPathInCone(file, out string processedPath)) { _basis.SetFileAttributes(file, attributes); return; } file = processedPath; string rel = file.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } FileSystemFile targetFile; if (!currentDir.Files.TryGetValue(parts[parts.Length - 1], out targetFile)) { throw new FileNotFoundException("File not found", file); } targetFile.Attributes = attributes; } public DateTime GetLastWriteTimeUtc(string file) { if (!IsPathInCone(file, out string processedPath)) { if (_basis is IFileLastWriteTimeSource lastWriteTimeSource) return lastWriteTimeSource.GetLastWriteTimeUtc(file); throw new NotImplementedException("Basis file system must implement IFileLastWriteTimeSource"); } file = processedPath; string rel = file.Substring(_root.FullPath.Length).Trim('/', '\\'); string[] parts = rel.Split('/', '\\'); FileSystemDirectory currentDir = _root; for (int i = 0; i < parts.Length - 1; ++i) { FileSystemDirectory dir; if (!currentDir.Directories.TryGetValue(parts[i], out dir)) { dir = new FileSystemDirectory(parts[i], Path.Combine(currentDir.FullPath, parts[i])); currentDir.Directories[parts[i]] = dir; } currentDir = dir; } FileSystemFile targetFile; if (!currentDir.Files.TryGetValue(parts[parts.Length - 1], out targetFile)) { throw new FileNotFoundException("File not found", file); } return targetFile.LastWriteTimeUtc; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Orleans.Hosting; using Orleans; using Orleans.Concurrency; using Orleans.Providers; using Orleans.Providers.Streams.SimpleMessageStream; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; #pragma warning disable 618 namespace UnitTests { public class ReentrancyTests : OrleansTestingBase, IClassFixture<ReentrancyTests.Fixture> { public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.Globals.AllowCallChainReentrancy = true; }); builder.AddSiloBuilderConfigurator<ReentrancyTestsSiloBuilderConfigurator>(); } } private readonly ITestOutputHelper output; private readonly Fixture fixture; private readonly TestCluster hostedCluster; public ReentrancyTests(ITestOutputHelper output, Fixture fixture) { this.output = output; this.fixture = fixture; hostedCluster = fixture.HostedCluster; } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void ReentrantGrain() { var reentrant = this.fixture.GrainFactory.GetGrain<IReentrantGrain>(GetRandomGrainId()); reentrant.SetSelf(reentrant).Wait(); try { Assert.True(reentrant.Two().Wait(2000), "Grain should reenter"); } catch (Exception ex) { Assert.True(false, string.Format("Unexpected exception {0}: {1}", ex.Message, ex.StackTrace)); } this.fixture.Logger.Info("Reentrancy ReentrantGrain Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateReturnsTrue() { var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId()); grain.SetSelf(grain).Wait(); try { Assert.True(grain.TwoReentrant().Wait(2000), "Grain should reenter when MayInterleave predicate returns true"); } catch (Exception ex) { Assert.True(false, string.Format("Unexpected exception {0}: {1}", ex.Message, ex.StackTrace)); } this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateReturnsTrue Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void NonReentrantGrain_WithMayInterleavePredicate_StreamItemDelivery_WhenPredicateReturnsTrue() { var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId()); grain.SubscribeToStream().Wait(); try { grain.PushToStream("reentrant").Wait(2000); } catch (Exception ex) { Assert.True(false, string.Format("Unexpected exception {0}: {1}", ex.Message, ex.StackTrace)); } this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_StreamItemDelivery_WhenPredicateReturnsTrue Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateThrows() { var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId()); grain.SetSelf(grain).Wait(); try { grain.Exceptional().Wait(2000); } catch (Exception ex) { Assert.IsType<OrleansException>(ex.GetBaseException()); Assert.NotNull(ex.GetBaseException().InnerException); Assert.IsType<ApplicationException>(ex.GetBaseException().InnerException); Assert.True(ex.GetBaseException().InnerException?.Message == "boom", "Should fail with Orleans runtime exception having all of neccessary details"); } this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateThrows Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task IsReentrant() { IReentrantTestSupportGrain grain = this.fixture.GrainFactory.GetGrain<IReentrantTestSupportGrain>(0); var grainFullName = typeof(ReentrantGrain).FullName; Assert.True(await grain.IsReentrant(grainFullName)); grainFullName = typeof(NonRentrantGrain).FullName; Assert.False(await grain.IsReentrant(grainFullName)); grainFullName = typeof(UnorderedNonRentrantGrain).FullName; Assert.False(await grain.IsReentrant(grainFullName)); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task Callchain_Reentrancy_OneWayMessage_Disabled_2() { var grain = this.fixture.GrainFactory.GetGrain<INonReentrantGrain>(1); await grain.SetSelf(grain); var initialCounter = await grain.GetCounter(); var counter = await grain.GetCounterAndScheduleIncrement(); Assert.Equal(initialCounter, counter); this.fixture.Logger.Info("Callchain_Reentrancy_OneWayMessage_Disabled_2 OK - no reentrancy."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task Callchain_Reentrancy_InterleavingSecondCall_Enabled() { var grain = fixture.GrainFactory.GetGrain<INonReentrantGrain>(0); var target = fixture.GrainFactory.GetGrain<INonReentrantGrain>(1); var gcts = new GrainCancellationTokenSource(); grain.DoAsyncWork(TimeSpan.FromHours(1), gcts.Token).Ignore(); var i = 1; var pingResult = await grain.PingSelfThroughOtherInterleaving(target, i); Assert.Equal(i, pingResult); await gcts.Cancel(); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task Callchain_Reentrancy_TimerOrigin_Enabled() { var grain = fixture.GrainFactory.GetGrain<INonReentrantGrain>(0); await grain.ScheduleDelayedIncrement(grain, TimeSpan.FromMilliseconds(1)); await Task.Delay(TimeSpan.FromMilliseconds(200)); var counter = await grain.GetCounter(); var expected = 1; Assert.Equal(expected, counter); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void Reentrancy_Deadlock_1() { List<Task> done = new List<Task>(); var grain1 = this.fixture.GrainFactory.GetGrain<IReentrantSelfManagedGrain>(1); grain1.SetDestination(2).Wait(); done.Add(grain1.Ping(15)); var grain2 = this.fixture.GrainFactory.GetGrain<IReentrantSelfManagedGrain>(2); grain2.SetDestination(1).Wait(); done.Add(grain2.Ping(15)); Task.WhenAll(done).Wait(); this.fixture.Logger.Info("ReentrancyTest_Deadlock_1 OK - no deadlock."); } // TODO: [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] [Fact(Skip = "Ignore"), TestCategory("Failures"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void Reentrancy_Deadlock_2() { List<Task> done = new List<Task>(); var grain1 = this.fixture.GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(1); grain1.SetDestination(2).Wait(); var grain2 = this.fixture.GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(2); grain2.SetDestination(1).Wait(); this.fixture.Logger.Info("ReentrancyTest_Deadlock_2 is about to call grain1.Ping()"); done.Add(grain1.Ping(15)); this.fixture.Logger.Info("ReentrancyTest_Deadlock_2 is about to call grain2.Ping()"); done.Add(grain2.Ping(15)); Task.WhenAll(done).Wait(); this.fixture.Logger.Info("ReentrancyTest_Deadlock_2 OK - no deadlock."); } [Fact, TestCategory("Failures"), TestCategory("Tasks"), TestCategory("Reentrancy")] private async Task NonReentrantFanOut() { var grain = fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<int>>(Guid.NewGuid()); var target = fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<int>>(Guid.NewGuid()); await grain.CallOtherLongRunningTask(target, 2, TimeSpan.FromSeconds(1)); await Assert.ThrowsAsync<TimeoutException>( () => target.FanOutOtherLongRunningTask(grain, 2, TimeSpan.FromSeconds(10), 5)); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_Task_Reentrant() { await Do_FanOut_Task_Join(0, false, false); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_Task_NonReentrant() { await Do_FanOut_Task_Join(0, true, false); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_Task_Reentrant_Chain() { await Do_FanOut_Task_Join(0, false, true); } // TODO: [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] [Fact(Skip ="Ignore"), TestCategory("Failures"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_Task_NonReentrant_Chain() { await Do_FanOut_Task_Join(0, true, true); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_AC_Reentrant() { await Do_FanOut_AC_Join(0, false, false); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_AC_NonReentrant() { await Do_FanOut_AC_Join(0, true, false); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_AC_Reentrant_Chain() { await Do_FanOut_AC_Join(0, false, true); } [TestCategory("MultithreadingFailures")] // TODO: [TestCategory("Functional")] [Fact(Skip ="Ignore"), TestCategory("Tasks"), TestCategory("Reentrancy")] public async Task FanOut_AC_NonReentrant_Chain() { await Do_FanOut_AC_Join(0, true, true); } [Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void FanOut_Task_Stress_Reentrant() { const int numLoops = 5; const int blockSize = 10; TimeSpan timeout = TimeSpan.FromSeconds(40); Do_FanOut_Stress(numLoops, blockSize, timeout, false, false); } [Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void FanOut_Task_Stress_NonReentrant() { const int numLoops = 5; const int blockSize = 10; TimeSpan timeout = TimeSpan.FromSeconds(40); Do_FanOut_Stress(numLoops, blockSize, timeout, true, false); } [Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void FanOut_AC_Stress_Reentrant() { const int numLoops = 5; const int blockSize = 10; TimeSpan timeout = TimeSpan.FromSeconds(40); Do_FanOut_Stress(numLoops, blockSize, timeout, false, true); } [Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void FanOut_AC_Stress_NonReentrant() { const int numLoops = 5; const int blockSize = 10; TimeSpan timeout = TimeSpan.FromSeconds(40); Do_FanOut_Stress(numLoops, blockSize, timeout, true, true); } // ---------- Utility methods ---------- private async Task Do_FanOut_Task_Join(int offset, bool doNonReentrant, bool doCallChain) { const int num = 10; int id = random.Next(); if (doNonReentrant) { IFanOutGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutGrain>(id); if (doCallChain) { await grain.FanOutNonReentrant_Chain(offset*num, num); } else { await grain.FanOutNonReentrant(offset * num, num); } } else { IFanOutGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutGrain>(id); if (doCallChain) { await grain.FanOutReentrant_Chain(offset*num, num); } else { await grain.FanOutReentrant(offset * num, num); } } } private async Task Do_FanOut_AC_Join(int offset, bool doNonReentrant, bool doCallChain) { const int num = 10; int id = random.Next(); if (doNonReentrant) { IFanOutACGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutACGrain>(id); if (doCallChain) { await grain.FanOutACNonReentrant_Chain(offset * num, num); } else { await grain.FanOutACNonReentrant(offset * num, num); } } else { IFanOutACGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutACGrain>(id); if (doCallChain) { await grain.FanOutACReentrant_Chain(offset * num, num); } else { await grain.FanOutACReentrant(offset * num, num); } } } private readonly TimeSpan MaxStressExecutionTime = TimeSpan.FromMinutes(2); private void Do_FanOut_Stress(int numLoops, int blockSize, TimeSpan timeout, bool doNonReentrant, bool doAC) { Stopwatch totalTime = Stopwatch.StartNew(); List<Task> promises = new List<Task>(); for (int i = 0; i < numLoops; i++) { output.WriteLine("Start loop {0}", i); Stopwatch loopClock = Stopwatch.StartNew(); for (int j = 0; j < blockSize; j++) { int offset = j; output.WriteLine("Start inner loop {0}", j); Stopwatch innerClock = Stopwatch.StartNew(); Task promise = Task.Run(() => { return doAC ? Do_FanOut_AC_Join(offset, doNonReentrant, false) : Do_FanOut_Task_Join(offset, doNonReentrant, false); }); promises.Add(promise); output.WriteLine("Inner loop {0} - Created Tasks. Elapsed={1}", j, innerClock.Elapsed); bool ok = Task.WhenAll(promises).Wait(timeout); if (!ok) throw new TimeoutException(); output.WriteLine("Inner loop {0} - Finished Join. Elapsed={1}", j, innerClock.Elapsed); promises.Clear(); } output.WriteLine("End loop {0} Elapsed={1}", i, loopClock.Elapsed); } TimeSpan elapsed = totalTime.Elapsed; Assert.True(elapsed < MaxStressExecutionTime, $"Stress test execution took too long: {elapsed}"); } } public class DisabledCallChainReentrancyTests : OrleansTestingBase, IClassFixture<DisabledCallChainReentrancyTests.Fixture> { public class Fixture : BaseTestClusterFixture { public ClusterConfiguration ClusterConfiguration { get; private set; } protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.Globals.AllowCallChainReentrancy = false; this.ClusterConfiguration = legacy.ClusterConfiguration; }); builder.AddSiloBuilderConfigurator<ReentrancyTestsSiloBuilderConfigurator>(); } } private readonly ITestOutputHelper output; private readonly Fixture fixture; private readonly TestCluster hostedCluster; public DisabledCallChainReentrancyTests(ITestOutputHelper output, Fixture fixture) { this.output = output; this.fixture = fixture; hostedCluster = fixture.HostedCluster; } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void NonReentrantGrain_WithMessageInterleavesPredicate_StreamItemDelivery_WhenPredicateReturnsFalse() { var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId()); grain.SubscribeToStream().Wait(); bool timeout = false; bool deadlock = false; try { timeout = !grain.PushToStream("foo").Wait(2000); } catch (Exception exc) { Exception baseExc = exc.GetBaseException(); if (baseExc.GetType().Equals(typeof(DeadlockException))) { deadlock = true; } else { Assert.True(false, string.Format("Unexpected exception {0}: {1}", exc.Message, exc.StackTrace)); } } if (this.fixture.ClusterConfiguration.Globals.PerformDeadlockDetection) { Assert.True(deadlock, "Non-reentrant grain should deadlock on stream item delivery to itself when CanInterleave predicate returns false"); } else { Assert.True(timeout, "Non-reentrant grain should timeout on stream item delivery to itself when CanInterleave predicate returns false"); } this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMessageInterleavesPredicate_StreamItemDelivery_WhenPredicateReturnsFalse Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void NonReentrantGrain() { INonReentrantGrain nonreentrant = this.fixture.GrainFactory.GetGrain<INonReentrantGrain>(GetRandomGrainId()); nonreentrant.SetSelf(nonreentrant).Wait(); bool timeout = false; bool deadlock = false; try { timeout = !nonreentrant.Two().Wait(2000); } catch (Exception exc) { Exception baseExc = exc.GetBaseException(); if (baseExc.GetType().Equals(typeof(DeadlockException))) { deadlock = true; } else { Assert.True(false, string.Format("Unexpected exception {0}: {1}", exc.Message, exc.StackTrace)); } } if (this.fixture.ClusterConfiguration.Globals.PerformDeadlockDetection) { Assert.True(deadlock, "Non-reentrant grain should deadlock"); } else { Assert.True(timeout, "Non-reentrant grain should timeout"); } this.fixture.Logger.Info("Reentrancy NonReentrantGrain Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateReturnsFalse() { var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId()); grain.SetSelf(grain).Wait(); bool timeout = false; bool deadlock = false; try { timeout = !grain.Two().Wait(2000); } catch (Exception exc) { Exception baseExc = exc.GetBaseException(); if (baseExc.GetType().Equals(typeof(DeadlockException))) { deadlock = true; } else { Assert.True(false, string.Format("Unexpected exception {0}: {1}", exc.Message, exc.StackTrace)); } } if (this.fixture.ClusterConfiguration.Globals.PerformDeadlockDetection) { Assert.True(deadlock, "Non-reentrant grain should deadlock when MayInterleave predicate returns false"); } else { Assert.True(timeout, "Non-reentrant grain should timeout when MayInterleave predicate returns false"); } this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateReturnsFalse Test finished OK."); } [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")] public void UnorderedNonReentrantGrain() { IUnorderedNonReentrantGrain unonreentrant = this.fixture.GrainFactory.GetGrain<IUnorderedNonReentrantGrain>(GetRandomGrainId()); unonreentrant.SetSelf(unonreentrant).Wait(); bool timeout = false; bool deadlock = false; try { timeout = !unonreentrant.Two().Wait(2000); } catch (Exception exc) { Exception baseExc = exc.GetBaseException(); if (baseExc.GetType().Equals(typeof(DeadlockException))) { deadlock = true; } else { Assert.True(false, $"Unexpected exception {exc.Message}: {exc.StackTrace}"); } } if (this.fixture.ClusterConfiguration.Globals.PerformDeadlockDetection) { Assert.True(deadlock, "Non-reentrant grain should deadlock"); } else { Assert.True(timeout, "Non-reentrant grain should timeout"); } this.fixture.Logger.Info("Reentrancy UnorderedNonReentrantGrain Test finished OK."); } } internal class ReentrancyTestsSiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddSimpleMessageStreamProvider("sms") .AddMemoryGrainStorage("MemoryStore") .AddMemoryGrainStorage("PubSubStore") .AddMemoryGrainStorageAsDefault(); } } } #pragma warning restore 618
/* * 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 NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Basic scene object tests (create, read and delete but not update). /// </summary> [TestFixture] public class SceneObjectBasicTests : OpenSimTestCase { // [TearDown] // public void TearDown() // { // Console.WriteLine("TearDown"); // GC.Collect(); // Thread.Sleep(3000); // } // public class GcNotify // { // public static AutoResetEvent gcEvent = new AutoResetEvent(false); // private static bool _initialized = false; // // public static void Initialize() // { // if (!_initialized) // { // _initialized = true; // new GcNotify(); // } // } // // private GcNotify(){} // // ~GcNotify() // { // if (!Environment.HasShutdownStarted && // !AppDomain.CurrentDomain.IsFinalizingForUnload()) // { // Console.WriteLine("GcNotify called"); // gcEvent.Set(); // new GcNotify(); // } // } // } /// <summary> /// Test adding an object to a scene. /// </summary> [Test] public void TestAddSceneObject() { TestHelpers.InMethod(); Scene scene = new SceneHelpers().SetupScene(); int partsToTestCount = 3; SceneObjectGroup so = SceneHelpers.CreateSceneObject(partsToTestCount, TestHelpers.ParseTail(0x1), "obj1", 0x10); SceneObjectPart[] parts = so.Parts; Assert.That(scene.AddNewSceneObject(so, false), Is.True); SceneObjectGroup retrievedSo = scene.GetSceneObjectGroup(so.UUID); SceneObjectPart[] retrievedParts = retrievedSo.Parts; //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same Assert.That(retrievedSo.PrimCount, Is.EqualTo(partsToTestCount)); for (int i = 0; i < partsToTestCount; i++) { Assert.That(retrievedParts[i].Name, Is.EqualTo(parts[i].Name)); Assert.That(retrievedParts[i].UUID, Is.EqualTo(parts[i].UUID)); } } [Test] /// <summary> /// It shouldn't be possible to add a scene object if one with that uuid already exists in the scene. /// </summary> public void TestAddExistingSceneObjectUuid() { TestHelpers.InMethod(); Scene scene = new SceneHelpers().SetupScene(); string obj1Name = "Alfred"; string obj2Name = "Betty"; UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001"); SceneObjectPart part1 = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = obj1Name, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True); SceneObjectPart part2 = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = obj2Name, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part2), false), Is.False); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid); //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same Assert.That(retrievedPart.Name, Is.EqualTo(obj1Name)); Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid)); } /// <summary> /// Test retrieving a scene object via the local id of one of its parts. /// </summary> [Test] public void TestGetSceneObjectByPartLocalId() { TestHelpers.InMethod(); Scene scene = new SceneHelpers().SetupScene(); int partsToTestCount = 3; SceneObjectGroup so = SceneHelpers.CreateSceneObject(partsToTestCount, TestHelpers.ParseTail(0x1), "obj1", 0x10); SceneObjectPart[] parts = so.Parts; scene.AddNewSceneObject(so, false); // Test getting via the root part's local id Assert.That(scene.GetGroupByPrim(so.LocalId), Is.Not.Null); // Test getting via a non root part's local id Assert.That(scene.GetGroupByPrim(parts[partsToTestCount - 1].LocalId), Is.Not.Null); // Test that we don't get back an object for a local id that doesn't exist Assert.That(scene.GetGroupByPrim(999), Is.Null); // Now delete the scene object and check again scene.DeleteSceneObject(so, false); Assert.That(scene.GetGroupByPrim(so.LocalId), Is.Null); Assert.That(scene.GetGroupByPrim(parts[partsToTestCount - 1].LocalId), Is.Null); } /// <summary> /// Test deleting an object from a scene. /// </summary> /// <remarks> /// This is the most basic form of delete. For all more sophisticated forms of derez (done asynchrnously /// and where object can be taken to user inventory, etc.), see SceneObjectDeRezTests. /// </remarks> [Test] public void TestDeleteSceneObject() { TestHelpers.InMethod(); TestScene scene = new SceneHelpers().SetupScene(); SceneObjectGroup so = SceneHelpers.AddSceneObject(scene); Assert.That(so.IsDeleted, Is.False); scene.DeleteSceneObject(so, false); Assert.That(so.IsDeleted, Is.True); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId); Assert.That(retrievedPart, Is.Null); } /// <summary> /// Changing a scene object uuid changes the root part uuid. This is a valid operation if the object is not /// in a scene and is useful if one wants to supply a UUID directly rather than use the one generated by /// OpenSim. /// </summary> [Test] public void TestChangeSceneObjectUuid() { string rootPartName = "rootpart"; UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001"); string childPartName = "childPart"; UUID childPartUuid = new UUID("00000000-0000-0000-0001-000000000000"); SceneObjectPart rootPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid }; SceneObjectPart linkPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = childPartName, UUID = childPartUuid }; SceneObjectGroup sog = new SceneObjectGroup(rootPart); sog.AddPart(linkPart); Assert.That(sog.UUID, Is.EqualTo(rootPartUuid)); Assert.That(sog.RootPart.UUID, Is.EqualTo(rootPartUuid)); Assert.That(sog.Parts.Length, Is.EqualTo(2)); UUID newRootPartUuid = new UUID("00000000-0000-0000-0000-000000000002"); sog.UUID = newRootPartUuid; Assert.That(sog.UUID, Is.EqualTo(newRootPartUuid)); Assert.That(sog.RootPart.UUID, Is.EqualTo(newRootPartUuid)); Assert.That(sog.Parts.Length, Is.EqualTo(2)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Roslyn.CSharp.Tests { public class IntellisenseFacts : AbstractAutoCompleteTestFixture { private readonly ILogger _logger; public IntellisenseFacts(ITestOutputHelper output) : base(output) { this._logger = this.LoggerFactory.CreateLogger<IntellisenseFacts>(); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task DisplayText_is_correct_for_property(string filename) { const string input = @"public class Class1 { public int Foo { get; set; } public Class1() { Foo$$ } }"; var completions = await FindCompletionsAsync(filename, input, wantSnippet: true); ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task DisplayText_is_correct_for_variable(string filename) { const string input = @"public class Class1 { public Class1() { var foo = 1; foo$$ } }"; var completions = await FindCompletionsAsync(filename, input, wantSnippet: true); ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "foo"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task DisplayText_matches_snippet_for_snippet_response(string filename) { const string input = @"public class Class1 { public Class1() { Foo$$ } public void Foo(int bar = 1) { } }"; var completions = await FindCompletionsAsync(filename, input, wantSnippet: true); ContainsCompletions(completions.Select(c => c.DisplayText).Take(2), "Foo()", "Foo(int bar = 1)"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task DisplayText_matches_snippet_for_non_snippet_response(string filename) { const string input = @"public class Class1 { public Class1() { Foo$$ } public void Foo(int bar = 1) { } }"; var completions = await FindCompletionsAsync(filename, input, wantSnippet: false); ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo(int bar = 1)"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_camel_case_completions(string filename) { const string input = @"public class Class1 { public Class1() { System.Guid.tp$$ } }"; var completions = await FindCompletionsAsync(filename, input); ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "TryParse"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_sub_sequence_completions(string filename) { const string input = @"public class Class1 { public Class1() { System.Guid.ng$$ } }"; var completions = await FindCompletionsAsync(filename, input); ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "NewGuid"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_method_header(string filename) { const string input = @"public class Class1 { public Class1() { System.Guid.ng$$ } }"; var completions = await FindCompletionsAsync(filename, input); ContainsCompletions(completions.Select(c => c.MethodHeader).Take(1), "NewGuid()"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_variable_before_class(string filename) { const string input = @"public class MyClass1 { public MyClass1() { var myvar = 1; my$$ } }"; var completions = await FindCompletionsAsync(filename, input); ContainsCompletions(completions.Select(c => c.CompletionText), "myvar", "MyClass1"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_class_before_variable(string filename) { const string input = @"public class MyClass1 { public MyClass1() { var myvar = 1; My$$ } }"; var completions = await FindCompletionsAsync(filename, input); ContainsCompletions(completions.Select(c => c.CompletionText), "MyClass1", "myvar"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_empty_sequence_in_invalid_context(string filename) { const string source = @"public class MyClass1 { public MyClass1() { var x$$ } }"; var completions = await FindCompletionsAsync(filename, source); ContainsCompletions(completions.Select(c => c.CompletionText), Array.Empty<string>()); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_attribute_without_attribute_suffix(string filename) { const string source = @"using System; public class BarAttribute : Attribute {} [B$$ public class Foo {}"; var completions = await FindCompletionsAsync(filename, source); ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "Bar"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_members_in_object_initializer_context(string filename) { const string source = @"public class MyClass1 { public string Foo {get; set;} } public class MyClass2 { public MyClass2() { var c = new MyClass1 { F$$ } } "; var completions = await FindCompletionsAsync(filename, source); ContainsCompletions(completions.Select(c => c.CompletionText), "Foo"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_parameter_name_inside_a_method(string filename) { const string source = @"public class MyClass1 { public void SayHi(string text) {} } public class MyClass2 { public MyClass2() { var c = new MyClass1(); c.SayHi(te$$ } } "; var completions = await FindCompletionsAsync(filename, source); ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "text:"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_override_signatures(string filename) { const string source = @"class Foo { public virtual void Test(string text) {} public virtual void Test(string text, string moreText) {} } class FooChild : Foo { override $$ } "; var completions = await FindCompletionsAsync(filename, source); ContainsCompletions(completions.Select(c => c.CompletionText), "Equals(object obj)", "GetHashCode()", "Test(string text)", "Test(string text, string moreText)", "ToString()"); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_cref_completion(string filename) { const string source = @" /// <summary> /// A comment. <see cref=""My$$"" /> for more details /// </summary> public class MyClass1 { } "; var completions = await FindCompletionsAsync(filename, source); ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "MyClass1"); } [Fact] public async Task Returns_host_object_members_in_csx() { const string source = "Prin$$"; var completions = await FindCompletionsAsync("dummy.csx", source); ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "Print", "PrintOptions" }); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Is_suggestion_mode_true_for_lambda_expression_position1(string filename) { const string source = @" using System; class C { int CallMe(int i) => 42; void M(Func<int, int> a) { } void M() { M(c$$ } } "; var completions = await FindCompletionsAsync(filename, source); Assert.True(completions.All(c => c.IsSuggestionMode)); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Is_suggestion_mode_true_for_lambda_expression_position2(string filename) { const string source = @" using System; class C { int CallMe(int i) => 42; void M() { Func<int, int> a = c$$ } } "; var completions = await FindCompletionsAsync(filename, source); Assert.True(completions.All(c => c.IsSuggestionMode)); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Is_suggestion_mode_false_for_normal_position1(string filename) { const string source = @" using System; class C { int CallMe(int i) => 42; void M(int a) { } void M() { M(c$$ } } "; var completions = await FindCompletionsAsync(filename, source); Assert.True(completions.All(c => !c.IsSuggestionMode)); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Is_suggestion_mode_false_for_normal_position2(string filename) { const string source = @" using System; class C { int CallMe(int i) => 42; void M() { int a = c$$ } } "; var completions = await FindCompletionsAsync(filename, source); Assert.True(completions.All(c => !c.IsSuggestionMode)); } [Fact] public async Task Scripting_by_default_returns_completions_for_CSharp7_1() { const string source = @" var number1 = 1; var number2 = 2; var tuple = (number1, number2); tuple.n$$ "; var completions = await FindCompletionsAsync("dummy.csx", source); ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "number1", "number2" }); } private void ContainsCompletions(IEnumerable<string> completions, params string[] expected) { if (!completions.SequenceEqual(expected)) { var builder = new StringBuilder(); builder.AppendLine("Expected"); builder.AppendLine("--------"); foreach (var completion in expected) { builder.AppendLine(completion); } builder.AppendLine(); builder.AppendLine("Found"); builder.AppendLine("-----"); foreach (var completion in completions) { builder.AppendLine(completion); } this._logger.LogError(builder.ToString()); } Assert.Equal(expected, completions.ToArray()); } } }
using System; using System.Data; using System.Web.UI; using Vevo; using Vevo.Domain; using Vevo.Domain.Base; using Vevo.Domain.Products; using Vevo.Domain.Stores; using Vevo.Shared.Utilities; using Vevo.Shared.DataAccess; using Vevo.Deluxe.Domain.Products; using Vevo.Deluxe.Domain; public partial class AdminAdvanced_Components_ProductDetails : AdminAdvancedBaseUserControl { #region Private private enum Mode { Add, Edit }; private Mode _mode = Mode.Add; private string Action { get { string value = MainContext.QueryString["action"]; if (!String.IsNullOrEmpty( value )) { return value; } else { return "0"; } } } private void ClearInputFields() { uxProductInfo.ClearInputFields(); uxGiftCertificate.ClearInputFields(); uxProductAttributes.ClearInputFields(); uxGiftCertificate.SetGiftCertificateControlsVisibility( IsEditMode() ); //Recurring Edit uxRecurring.ClearInputFields(); uxProductSubscription.ClearInputFields(); uxProductKit.ClearInputFields(); } private void PopulateControls() { PopulateLanguageSection(); if (ConvertUtilities.ToInt32( CurrentID ) > 0) { Product product = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() ); uxProductAttributes.PopulateControls( product, "0" ); uxGiftCertificate.PopulateControls( product ); if (product.IsGiftCertificate) { uxGiftCertificate.PopulateGiftData( (GiftCertificateProduct) product ); uxGiftCertificate.SetGiftCertificateControlsVisibility( IsEditMode() ); } uxRecurring.PopulateControls( product ); if (KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName )) { uxProductSubscription.PopulateControls( product ); } uxProductAttributes.IsFixPrice( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring, uxProductAttributes.IsCallForPrice ); uxProductKit.PopulateControls( product ); } } private void CopyVisible( bool value ) { uxCopyButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxCopyConfirmButton.TargetControlID = "uxCopyButton"; uxConfirmModalPopup.TargetControlID = "uxCopyButton"; } else { uxCopyConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxCopyConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void DisplayControlsByVersion() { uxProductAttributes.SetDisplayControls(); uxGiftCertificate.SetDisplayControl( DataAccessContext.Configurations.GetBoolValue( "GiftCertificateEnabled" ) ); if (IsEditMode()) { CopyVisible( true ); } } private void Language_RefreshHandler( object sender, EventArgs e ) { PopulateLanguageSection(); } private string AddNew() { Product product; product = uxGiftCertificate.Setup( uxLanguageControl.CurrentCulture ); product = SetUpProduct( product ); ProductSubscription subscriptionItem = uxProductSubscription.Setup( product ); product = DataAccessContext.ProductRepository.Save( product ); DataAccessContextDeluxe.ProductSubscriptionRepository.SaveAll( product.ProductID, subscriptionItem.ProductSubscriptions ); uxMessage.DisplayMessage( Resources.ProductMessages.AddSuccess ); return product.ProductID; } private void Update() { try { if (Page.IsValid) { if (uxProductInfo.ConvertToCategoryIDs().Length > 0) { if (!uxProductAttributes.VerifyInputListOption()) { DisplayErrorOption(); return; } string price; string retailPrice; string wholeSalePrice; string wholeSalePrice2; string wholeSalePrice3; decimal giftAmount; if (uxProductAttributes.IsFixPrice( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring, uxProductAttributes.IsCallForPrice )) { price = uxProductAttributes.Price; retailPrice = uxProductAttributes.RetailPrice; wholeSalePrice = uxProductAttributes.WholeSalePrice; wholeSalePrice2 = uxProductAttributes.WholeSalePrice2; wholeSalePrice3 = uxProductAttributes.WholeSalePrice3; giftAmount = ConvertUtilities.ToDecimal( uxGiftCertificate.GiftAmount ); } else { price = "0"; retailPrice = "0"; wholeSalePrice = "0"; wholeSalePrice2 = "0"; wholeSalePrice3 = "0"; giftAmount = 0m; } string storeID = new StoreRetriever().GetCurrentStoreID(); Product product = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, storeID ); product = SetUpProduct( product ); product = DataAccessContext.ProductRepository.Save( product ); uxMessage.DisplayMessage( Resources.ProductMessages.UpdateSuccess ); AdminUtilities.ClearSiteMapCache(); PopulateControls(); } else { uxMessage.DisplayError( Resources.ProductMessages.AddErrorCategoryEmpty ); return; } } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } private DataTable CurrentStockOption { get { if (ViewState["CurrentStockOption"] == null) return null; else return (DataTable) ViewState["CurrentStockOption"]; } set { ViewState["CurrentStockOption"] = value; } } private void DisplayErrorOption() { uxMessage.DisplayError( Resources.ProductOptionMessages.InvalidInputList ); } private void EnforcePermission() { if (!MainContext.IsPostBack && !IsAdminModifiable()) { if (IsEditMode()) { uxEditButton.Visible = false; CopyVisible( false ); uxProductAttributes.HideUploadButton(); } else { uxAddButton.Visible = false; uxProductImageList.HideUploadImageButton(); } } } private void PopulateLink() { uxLastAddLink.Visible = false; uxReviewLink.Visible = false; uxImageListLink.Visible = false; if (IsEditMode()) { uxReviewLink.Visible = true; GetReviewLink(); uxImageListLink.Visible = true; GetImageListsLink(); } } private void GetReviewLink() { uxReviewLink.PageName = "ProductReviewList.ascx"; uxReviewLink.PageQueryString = "ProductID=" + CurrentID; } private void GetImageListsLink() { uxImageListLink.PageName = "ProductImageList.ascx"; uxImageListLink.PageQueryString = "ProductID=" + CurrentID; } private void GetLastAddProductLink( string productID ) { uxLastAddLink.PageName = "ProductEdit.ascx"; uxLastAddLink.PageQueryString = "ProductID=" + productID; } private void CopyRemainingProductLocales( Product originalProduct, string newProductID ) { string storeID = new StoreRetriever().GetCurrentStoreID(); Product newProduct = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, newProductID, storeID ); newProduct.ImageSecondary = String.Empty; foreach (ILocale locale in originalProduct.GetLocales()) { if (locale.CultureID != newProduct.Locales[uxLanguageControl.CurrentCulture].CultureID) { ProductLocale newLocale = new ProductLocale(); newLocale.CultureID = originalProduct.Locales[locale.CultureID].CultureID; newLocale.Name = originalProduct.Locales[locale.CultureID].Name; newLocale.ShortDescription = originalProduct.Locales[locale.CultureID].ShortDescription; newLocale.LongDescription = originalProduct.Locales[locale.CultureID].LongDescription; newProduct.Locales.Add( newLocale ); } } DataAccessContext.ProductRepository.Save( newProduct ); } private Product SetUpProduct( Product product ) { product = uxProductInfo.Setup( product ); product = uxRecurring.Setup( product ); product = uxProductAttributes.Setup( product, "0" ); product = uxProductKit.Setup( product ); product.ShippingCost = ConvertUtilities.ToDecimal( "0" ); product.IsGiftCertificate = uxGiftCertificate.IsGiftCertificate; product.IsFixedPrice = uxProductAttributes.IsFixPrice( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring, uxProductAttributes.IsCallForPrice ); product.ImageSecondary = uxProductImageList.SecondaryImage(); product = uxProductImageList.Update( product ); //Clear anything before change it. //product.ProductImages.Clear(); product.ProductStocks.Clear(); product.ProductOptionGroups.Clear(); product.ProductShippingCosts.Clear(); product.SetUseDefaultValueMetaKeyword( "0", true ); product.SetUseDefaultValueMetaDescription( "0", true ); uxProductAttributes.AddOptionGroup( product ); uxProductAttributes.CreateStockOption( product ); uxProductAttributes.UpdateProductShippingCost( product ); uxProductAttributes.SetProductSpecifications( product ); ProductImageData.PopulateProductImages( product ); ProductImageData.Clear(); return product; } private void ProductSubscriptionCondition() { if (uxProductSubscription.IsProductSubscription) { //set disable control uxProductKit.DisableProductKitControl(); uxProductSubscription.ShowProductSubscription(); uxProductAttributes.SetEnabledControlsForProductSubscription( false ); } else { //set enable control uxProductKit.EnableProductKitControl(); uxProductSubscription.HideProductSubscription(); uxProductAttributes.SetEnabledControlsForProductSubscription( true ); } } private void RecurringCondition() { //Add code for Recurring. if (uxRecurring.IsRecurring) { uxRecurring.ShowRecurring(); } else { uxRecurring.HideRecurring(); } } private void GiftCertificateCondition() { if (uxGiftCertificate.IsGiftCertificate) { uxProductKit.DisableProductKitControl(); uxProductSubscription.DisableProductScuscriptionControl(); uxRecurring.DisableRecurring(); } else { uxRecurring.EnableRecurring(); } } private void ProductKitCondition() { if (uxProductKit.IsProductKit) { uxProductKit.SetIsProductKit( true ); uxProductAttributes.SetProductKitControlVisible( true ); uxProductSubscription.DisableProductScuscriptionControl(); uxProductAttributes.IsDownloadableEnabled( false ); } else { uxProductKit.SetIsProductKit( false ); uxProductAttributes.SetProductKitControlVisible( false ); uxProductSubscription.EnableProductScuscriptionControl(); uxProductAttributes.IsDownloadableEnabled( true ); } } private void ShowHideGiftCertifiateControl() { if (uxProductKit.IsProductKit || uxProductSubscription.IsProductSubscription || uxRecurring.IsRecurring) { uxGiftCertificate.IsGiftCertificateEnabled( false ); } else { uxGiftCertificate.IsGiftCertificateEnabled( true ); } } private void ShowHideQuantityDiscount() { if (uxProductKit.IsProductKit || uxProductSubscription.IsProductSubscription) { uxProductAttributes.SetEnabledQuantityDiscount( false ); } else { uxProductAttributes.SetEnabledQuantityDiscount( true ); } } private void ShowHideMinMaxQTY() { if (uxProductSubscription.IsProductSubscription) { uxProductAttributes.SetEnabledMinMaxQTY( false ); uxProductAttributes.SetMinQuantity( 1 ); uxProductAttributes.SetMaxQuantity( 1 ); } else { uxProductAttributes.SetEnabledMinMaxQTY( true ); } } private void ShowHideDownloadable() { if (uxProductKit.IsProductKit || uxRecurring.IsRecurring) { uxProductAttributes.IsDownloadableEnabled( false ); } else { uxProductAttributes.IsDownloadableEnabled( true ); } } #endregion #region Protected protected string CurrentID { get { if (IsEditMode()) return MainContext.QueryString["ProductID"]; else return "0"; } } protected void Page_Load( object sender, EventArgs e ) { uxLanguageControl.BubbleEvent += new EventHandler( Language_RefreshHandler ); uxProductInfo.CurrentCulture = uxLanguageControl.CurrentCulture; uxProductAttributes.CurrentCulture = uxLanguageControl.CurrentCulture; uxProductAttributes.PopulateShippingCostControl(); uxProductAttributes.PopulateSpecificationItemControls(); uxProductImageList.PopulateControls(); if (!MainContext.IsPostBack) { uxProductAttributes.InitTaxClassDrop(); uxProductAttributes.InitDiscountDrop(); PopulateLink(); uxProductAttributes.PopulateDropdown(); uxProductAttributes.SetEditMode( IsEditMode() ); uxProductSubscription.InitDropDown(); } } protected void Page_PreRender( object sender, EventArgs e ) { if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName )) { ucProductSubscriptionTR.Visible = false; } if (Action == "copy" && !MainContext.IsPostBack) { uxMessage.DisplayMessage( Resources.ProductMessages.CopySuccess ); } if (!MainContext.IsPostBack) { uxProductAttributes.SetOptionList(); } if (IsEditMode()) { if (!MainContext.IsPostBack) { uxAddButton.Visible = false; PopulateControls(); if (CurrentID != null && int.Parse( CurrentID ) >= 0) { Product product = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() ); uxProductAttributes.SelectOptionList( product ); uxProductAttributes.PopulateStockOptionControl(); } } } else { if (!MainContext.IsPostBack) { uxEditButton.Visible = false; CopyVisible( false ); PopulateControls(); uxProductAttributes.HideStockOption(); uxProductIDTR.Visible = false; uxProductAttributes.PopulateStockVisibility(); uxGiftCertificate.IsGiftCertificateEnabled( true ); //Add code for Recurring. uxRecurring.HideRecurring(); } } uxProductAttributes.RestoreSessionData(); uxProductAttributes.SetWholesaleVisible( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring ); uxProductAttributes.SetRetailPriceVisible( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring ); uxProductAttributes.SetProductRatingVisible( uxGiftCertificate.IsGiftCertificate ); uxGiftCertificate.SetGiftCertificateControlsVisibility( IsEditMode() ); ProductSubscriptionCondition(); RecurringCondition(); ProductKitCondition(); GiftCertificateCondition(); ShowHideGiftCertifiateControl(); ShowHideQuantityDiscount(); ShowHideDownloadable(); ShowHideMinMaxQTY(); uxProductAttributes.SetFixedShippingCostVisibility( uxGiftCertificate.IsGiftCertificate ); uxProductAttributes.SetVisibleSpecificationControls(); DisplayControlsByVersion(); EnforcePermission(); } protected void uxSaveAndViewImageLinkButton_Click( object sender, EventArgs e ) { Update(); MainContext.RedirectMainControl( "ProductImageList.ascx", "ProductID=" + CurrentID ); } protected void uxAddButton_Click( object sender, EventArgs e ) { try { if (Page.IsValid) { if (uxProductAttributes.IsProductSkuExist()) { uxMessage.DisplayError( Resources.ProductMessages.AddErrorSkuExist ); return; } if (uxProductInfo.ConvertToCategoryIDs().Length <= 0) { uxMessage.DisplayError( Resources.ProductMessages.AddErrorCategoryEmpty ); return; } if (uxProductKit.IsProductKit) { if (uxProductKit.GetSelectedGroupID().Length <= 0) { uxMessage.DisplayError( Resources.ProductMessages.AddErrorProductKitEmpty ); return; } } if (!uxProductAttributes.VerifyInputListOption()) { DisplayErrorOption(); return; } uxProductAttributes.SetStockWhenAdd(); string productID = AddNew(); uxLastAddLink.Visible = true; GetLastAddProductLink( productID ); ClearInputFields(); uxProductAttributes.PopulateStockOptionControl(); AdminUtilities.ClearSiteMapCache(); } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } protected void uxEditButton_Click( object sender, EventArgs e ) { Update(); } protected void uxCopyButton_Click( object sender, EventArgs e ) { try { if (Page.IsValid) { if (!uxProductAttributes.VerifyInputListOption()) { DisplayErrorOption(); return; } string newProductID = AddNew(); Product originalProduct = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() ); CopyRemainingProductLocales( originalProduct, newProductID ); ClearInputFields(); uxProductAttributes.PopulateStockOptionControl(); AdminUtilities.ClearSiteMapCache(); MainContext.RedirectMainControl( "ProductEdit.ascx", String.Format( "ProductID={0}&action=copy", newProductID ) ); } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } protected void uxIsFixedPriceDrop_SelectedIndexChanged( object sender, EventArgs e ) { uxStatusHidden.Value = "Refresh"; } #endregion #region Public Methods public bool IsEditMode() { return (_mode == Mode.Edit); } public void SetEditMode() { _mode = Mode.Edit; } public int GetNumberOfCategories() { return DataAccessContext.CategoryRepository.GetAll( uxLanguageControl.CurrentCulture, "CategoryID" ).Count; } private void PopulateLanguageSection() { if (CurrentID != null && int.Parse( CurrentID ) > 0) { Product product = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() ); } uxProductInfo.CurrentCulture = uxLanguageControl.CurrentCulture; uxProductAttributes.CurrentCulture = uxLanguageControl.CurrentCulture; uxProductKit.CurrentCulture = uxLanguageControl.CurrentCulture; uxProductImageList.CurrentCulture = uxLanguageControl.CurrentCulture; } #endregion }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Runtime.InteropServices; using AOT; namespace UnityEngine.XR.iOS { /// <summary> /// A struct that allows us go from native Matrix4x4 to managed /// </summary> public struct UnityARMatrix4x4 { public Vector4 column0; public Vector4 column1; public Vector4 column2; public Vector4 column3; public UnityARMatrix4x4(Vector4 c0, Vector4 c1, Vector4 c2, Vector4 c3) { column0 = c0; column1 = c1; column2 = c2; column3 = c3; } }; [Serializable] public struct UnityVideoParams { public int yWidth; public int yHeight; public int screenOrientation; public float texCoordScale; public IntPtr cvPixelBufferPtr; }; struct internal_UnityARCamera { public UnityARMatrix4x4 worldTransform; public UnityARMatrix4x4 projectionMatrix; public ARTrackingState trackingState; public ARTrackingStateReason trackingReason; public UnityVideoParams videoParams; public UnityMarshalLightData lightData; public UnityARMatrix4x4 displayTransform; public uint getPointCloudData; public uint getLightEstimation; }; public struct UnityARCamera { public UnityARMatrix4x4 worldTransform; public UnityARMatrix4x4 projectionMatrix; public ARTrackingState trackingState; public ARTrackingStateReason trackingReason; public UnityVideoParams videoParams; public UnityARLightData lightData; public UnityARMatrix4x4 displayTransform; public Vector3[] pointCloudData; public UnityARCamera(UnityARMatrix4x4 wt, UnityARMatrix4x4 pm, ARTrackingState ats, ARTrackingStateReason atsr, UnityVideoParams uvp, UnityARLightData lightDat, UnityARMatrix4x4 dt, Vector3[] pointCloud) { worldTransform = wt; projectionMatrix = pm; trackingState = ats; trackingReason = atsr; videoParams = uvp; lightData = lightDat; displayTransform = dt; pointCloudData = pointCloud; } }; public struct UnityARUserAnchorData { public IntPtr ptrIdentifier; /** The transformation matrix that defines the anchor's rotation, translation and scale in world coordinates. */ public UnityARMatrix4x4 transform; public string identifierStr { get { return Marshal.PtrToStringAuto(this.ptrIdentifier); } } public static UnityARUserAnchorData UnityARUserAnchorDataFromGameObject(GameObject go) { // create an anchor data struct from a game object transform Matrix4x4 matrix = Matrix4x4.TRS(go.transform.position, go.transform.rotation, go.transform.localScale); UnityARUserAnchorData ad = new UnityARUserAnchorData(); ad.transform.column0 = matrix.GetColumn(0); ad.transform.column1 = matrix.GetColumn(1); ad.transform.column2 = matrix.GetColumn(2); ad.transform.column3 = matrix.GetColumn(3); return ad; } }; public struct UnityARHitTestResult { /** The type of the hit-test result. */ public ARHitTestResultType type; /** The distance from the camera to the intersection in meters. */ public double distance; /** The transformation matrix that defines the intersection's rotation, translation and scale relative to the anchor or nearest feature point. */ public Matrix4x4 localTransform; /** The transformation matrix that defines the intersection's rotation, translation and scale relative to the world. */ public Matrix4x4 worldTransform; /** The anchor that the hit-test intersected. */ public IntPtr anchor; /** True if the test represents a valid hit test. Data is undefined otherwise. */ public bool isValid; }; public enum UnityARAlignment { UnityARAlignmentGravity, UnityARAlignmentGravityAndHeading, UnityARAlignmentCamera } public enum UnityARPlaneDetection { None = 0, Horizontal = (1 << 0), Vertical = (1 << 1), HorizontalAndVertical = (1 << 1) | (1 << 0) } public struct ARKitSessionConfiguration { public UnityARAlignment alignment; public bool getPointCloudData; public bool enableLightEstimation; public bool IsSupported { get { return IsARKitSessionConfigurationSupported(); } private set { } } public ARKitSessionConfiguration(UnityARAlignment alignment = UnityARAlignment.UnityARAlignmentGravity, bool getPointCloudData = false, bool enableLightEstimation = false) { this.getPointCloudData = getPointCloudData; this.alignment = alignment; this.enableLightEstimation = enableLightEstimation; } #if UNITY_EDITOR || !UNITY_IOS private bool IsARKitSessionConfigurationSupported() { return true; } #else [DllImport("__Internal")] private static extern bool IsARKitSessionConfigurationSupported(); #endif } public struct ARKitWorldTrackingSessionConfiguration { public UnityARAlignment alignment; public UnityARPlaneDetection planeDetection; public bool getPointCloudData; public bool enableLightEstimation; public bool enableAutoFocus; public IntPtr videoFormat; public string arResourceGroupName; public bool IsSupported { get { return IsARKitWorldTrackingSessionConfigurationSupported(); } private set { } } public ARKitWorldTrackingSessionConfiguration(UnityARAlignment alignment = UnityARAlignment.UnityARAlignmentGravity, UnityARPlaneDetection planeDetection = UnityARPlaneDetection.Horizontal, bool getPointCloudData = false, bool enableLightEstimation = false, bool enableAutoFocus = true, IntPtr vidFormat = default(IntPtr), string arResourceGroup = null) { this.getPointCloudData = getPointCloudData; this.alignment = alignment; this.planeDetection = planeDetection; this.enableLightEstimation = enableLightEstimation; this.enableAutoFocus = enableAutoFocus; this.videoFormat = vidFormat; this.arResourceGroupName = arResourceGroup; } #if UNITY_EDITOR || !UNITY_IOS private bool IsARKitWorldTrackingSessionConfigurationSupported() { return true; } #else [DllImport("__Internal")] private static extern bool IsARKitWorldTrackingSessionConfigurationSupported(); #endif } public struct ARKitFaceTrackingConfiguration { public UnityARAlignment alignment; public bool enableLightEstimation; public bool IsSupported { get { return IsARKitFaceTrackingConfigurationSupported(); } private set { } } public ARKitFaceTrackingConfiguration(UnityARAlignment alignment = UnityARAlignment.UnityARAlignmentGravity, bool enableLightEstimation = false) { this.alignment = alignment; this.enableLightEstimation = enableLightEstimation; } #if UNITY_EDITOR || !UNITY_IOS private bool IsARKitFaceTrackingConfigurationSupported() { return true; } #else [DllImport("__Internal")] private static extern bool IsARKitFaceTrackingConfigurationSupported(); #endif } public enum UnityARSessionRunOption { /** The session will reset tracking. */ ARSessionRunOptionResetTracking = (1 << 0), /** The session will remove existing anchors. */ ARSessionRunOptionRemoveExistingAnchors = (1 << 1) } public class UnityARSessionNativeInterface { // public delegate void ARFrameUpdate(UnityARMatrix4x4 cameraPos, UnityARMatrix4x4 projection); // public static event ARFrameUpdate ARFrameUpdatedEvent; // Plane Anchors public delegate void ARFrameUpdate(UnityARCamera camera); public static event ARFrameUpdate ARFrameUpdatedEvent; public delegate void ARAnchorAdded(ARPlaneAnchor anchorData); public static event ARAnchorAdded ARAnchorAddedEvent; public delegate void ARAnchorUpdated(ARPlaneAnchor anchorData); public static event ARAnchorUpdated ARAnchorUpdatedEvent; public delegate void ARAnchorRemoved(ARPlaneAnchor anchorData); public static event ARAnchorRemoved ARAnchorRemovedEvent; // User Anchors public delegate void ARUserAnchorAdded(ARUserAnchor anchorData); public static event ARUserAnchorAdded ARUserAnchorAddedEvent; public delegate void ARUserAnchorUpdated(ARUserAnchor anchorData); public static event ARUserAnchorUpdated ARUserAnchorUpdatedEvent; public delegate void ARUserAnchorRemoved(ARUserAnchor anchorData); public static event ARUserAnchorRemoved ARUserAnchorRemovedEvent; // Face Anchors public delegate void ARFaceAnchorAdded(ARFaceAnchor anchorData); public static event ARFaceAnchorAdded ARFaceAnchorAddedEvent; public delegate void ARFaceAnchorUpdated(ARFaceAnchor anchorData); public static event ARFaceAnchorUpdated ARFaceAnchorUpdatedEvent; public delegate void ARFaceAnchorRemoved(ARFaceAnchor anchorData); public static event ARFaceAnchorRemoved ARFaceAnchorRemovedEvent; // Image Anchors public delegate void ARImageAnchorAdded(ARImageAnchor anchorData); public static event ARImageAnchorAdded ARImageAnchorAddedEvent; public delegate void ARImageAnchorUpdated(ARImageAnchor anchorData); public static event ARImageAnchorUpdated ARImageAnchorUpdatedEvent; public delegate void ARImageAnchorRemoved(ARImageAnchor anchorData); public static event ARImageAnchorRemoved ARImageAnchorRemovedEvent; public delegate void ARSessionFailed(string error); public static event ARSessionFailed ARSessionFailedEvent; public delegate void ARSessionCallback(); public delegate bool ARSessionLocalizeCallback(); public static event ARSessionCallback ARSessionInterruptedEvent; public static event ARSessionCallback ARSessioninterruptionEndedEvent; public delegate void ARSessionTrackingChanged(UnityARCamera camera); public static event ARSessionTrackingChanged ARSessionTrackingChangedEvent; public static bool ARSessionShouldAttemptRelocalization { get; set; } delegate void internal_ARFrameUpdate(internal_UnityARCamera camera); public delegate void internal_ARAnchorAdded(UnityARAnchorData anchorData); public delegate void internal_ARAnchorUpdated(UnityARAnchorData anchorData); public delegate void internal_ARAnchorRemoved(UnityARAnchorData anchorData); public delegate void internal_ARUserAnchorAdded(UnityARUserAnchorData anchorData); public delegate void internal_ARUserAnchorUpdated(UnityARUserAnchorData anchorData); public delegate void internal_ARUserAnchorRemoved(UnityARUserAnchorData anchorData); public delegate void internal_ARFaceAnchorAdded(UnityARFaceAnchorData anchorData); public delegate void internal_ARFaceAnchorUpdated(UnityARFaceAnchorData anchorData); public delegate void internal_ARFaceAnchorRemoved(UnityARFaceAnchorData anchorData); public delegate void internal_ARImageAnchorAdded(UnityARImageAnchorData anchorData); public delegate void internal_ARImageAnchorUpdated(UnityARImageAnchorData anchorData); public delegate void internal_ARImageAnchorRemoved(UnityARImageAnchorData anchorData); delegate void internal_ARSessionTrackingChanged(internal_UnityARCamera camera); private static UnityARCamera s_Camera; #if !UNITY_EDITOR && UNITY_IOS private IntPtr m_NativeARSession; [DllImport("__Internal")] private static extern IntPtr unity_CreateNativeARSession(); [DllImport("__Internal")] private static extern void session_SetSessionCallbacks(IntPtr nativeSession, internal_ARFrameUpdate frameCallback, ARSessionFailed sessionFailed, ARSessionCallback sessionInterrupted, ARSessionCallback sessionInterruptionEnded, ARSessionLocalizeCallback sessionShouldRelocalize, internal_ARSessionTrackingChanged trackingChanged); [DllImport("__Internal")] private static extern void session_SetPlaneAnchorCallbacks(IntPtr nativeSession, internal_ARAnchorAdded anchorAddedCallback, internal_ARAnchorUpdated anchorUpdatedCallback, internal_ARAnchorRemoved anchorRemovedCallback); [DllImport("__Internal")] private static extern void session_SetUserAnchorCallbacks(IntPtr nativeSession, internal_ARUserAnchorAdded userAnchorAddedCallback, internal_ARUserAnchorUpdated userAnchorUpdatedCallback, internal_ARUserAnchorRemoved userAnchorRemovedCallback); [DllImport("__Internal")] private static extern void session_SetImageAnchorCallbacks(IntPtr nativeSession, internal_ARImageAnchorAdded imageAnchorAddedCallback, internal_ARImageAnchorUpdated imageAnchorUpdatedCallback, internal_ARImageAnchorRemoved imageAnchorRemovedCallback); [DllImport("__Internal")] private static extern void session_SetFaceAnchorCallbacks(IntPtr nativeSession, internal_ARFaceAnchorAdded faceAnchorAddedCallback, internal_ARFaceAnchorUpdated faceAnchorUpdatedCallback, internal_ARFaceAnchorRemoved faceAnchorRemovedCallback); [DllImport("__Internal")] private static extern void StartWorldTrackingSession(IntPtr nativeSession, ARKitWorldTrackingSessionConfiguration configuration); [DllImport("__Internal")] private static extern void StartWorldTrackingSessionWithOptions(IntPtr nativeSession, ARKitWorldTrackingSessionConfiguration configuration, UnityARSessionRunOption runOptions); [DllImport("__Internal")] private static extern void StartSession(IntPtr nativeSession, ARKitSessionConfiguration configuration); [DllImport("__Internal")] private static extern void StartSessionWithOptions(IntPtr nativeSession, ARKitSessionConfiguration configuration, UnityARSessionRunOption runOptions); [DllImport("__Internal")] private static extern void StartFaceTrackingSession(IntPtr nativeSession, ARKitFaceTrackingConfiguration configuration); [DllImport("__Internal")] private static extern void StartFaceTrackingSessionWithOptions(IntPtr nativeSession, ARKitFaceTrackingConfiguration configuration, UnityARSessionRunOption runOptions); [DllImport("__Internal")] private static extern void PauseSession(IntPtr nativeSession); [DllImport("__Internal")] private static extern int HitTest(IntPtr nativeSession, ARPoint point, ARHitTestResultType types); [DllImport("__Internal")] private static extern UnityARHitTestResult GetLastHitTestResult(int index); [DllImport("__Internal")] private static extern ARTextureHandles GetVideoTextureHandles(); [DllImport("__Internal")] private static extern float GetAmbientIntensity(); [DllImport("__Internal")] private static extern int GetTrackingQuality(); [DllImport("__Internal")] private static extern bool GetARPointCloud (ref IntPtr verts, ref uint vertLength); [DllImport("__Internal")] private static extern void SetCameraNearFar (float nearZ, float farZ); [DllImport("__Internal")] private static extern void CapturePixelData (int enable, IntPtr pYPixelBytes, IntPtr pUVPixelBytes); [DllImport("__Internal")] private static extern UnityARUserAnchorData SessionAddUserAnchor (IntPtr nativeSession, UnityARUserAnchorData anchorData); [DllImport("__Internal")] private static extern void SessionRemoveUserAnchor (IntPtr nativeSession, [MarshalAs(UnmanagedType.LPStr)] string anchorIdentifier); [DllImport("__Internal")] private static extern void SessionSetWorldOrigin (IntPtr nativeSession, Matrix4x4 worldMatrix); [DllImport("__Internal")] private static extern bool Native_IsARKit_1_5_Supported(); #endif public static bool IsARKit_1_5_Supported() { #if !UNITY_EDITOR && UNITY_IOS return Native_IsARKit_1_5_Supported(); #else return true; //since we might need to do some editor shenanigans #endif } public UnityARSessionNativeInterface() { #if !UNITY_EDITOR && UNITY_IOS m_NativeARSession = unity_CreateNativeARSession(); session_SetSessionCallbacks(m_NativeARSession, _frame_update, _ar_session_failed, _ar_session_interrupted, _ar_session_interruption_ended, _ar_session_should_relocalize, _ar_tracking_changed); session_SetPlaneAnchorCallbacks(m_NativeARSession, _anchor_added, _anchor_updated, _anchor_removed); session_SetUserAnchorCallbacks(m_NativeARSession, _user_anchor_added, _user_anchor_updated, _user_anchor_removed); session_SetFaceAnchorCallbacks(m_NativeARSession, _face_anchor_added, _face_anchor_updated, _face_anchor_removed); session_SetImageAnchorCallbacks(m_NativeARSession, _image_anchor_added, _image_anchor_updated, _image_anchor_removed); #endif } static UnityARSessionNativeInterface s_UnityARSessionNativeInterface = null; public static UnityARSessionNativeInterface GetARSessionNativeInterface() { if (s_UnityARSessionNativeInterface == null) { s_UnityARSessionNativeInterface = new UnityARSessionNativeInterface(); } return s_UnityARSessionNativeInterface; } #if UNITY_EDITOR public static void SetStaticCamera(UnityARCamera scamera) { s_Camera = scamera; } public static void RunFrameUpdateCallbacks() { if (ARFrameUpdatedEvent != null) { ARFrameUpdatedEvent(s_Camera); } } public static void RunAddAnchorCallbacks(ARPlaneAnchor arPlaneAnchor) { if (ARAnchorAddedEvent != null) { ARAnchorAddedEvent(arPlaneAnchor); } } public static void RunUpdateAnchorCallbacks(ARPlaneAnchor arPlaneAnchor) { if (ARAnchorUpdatedEvent != null) { ARAnchorUpdatedEvent(arPlaneAnchor); } } public static void RunRemoveAnchorCallbacks(ARPlaneAnchor arPlaneAnchor) { if (ARAnchorRemovedEvent != null) { ARAnchorRemovedEvent(arPlaneAnchor); } } public static void RunAddAnchorCallbacks(ARFaceAnchor arFaceAnchor) { if (ARFaceAnchorAddedEvent != null) { ARFaceAnchorAddedEvent(arFaceAnchor); } } public static void RunUpdateAnchorCallbacks(ARFaceAnchor arFaceAnchor) { if (ARFaceAnchorUpdatedEvent != null) { ARFaceAnchorUpdatedEvent(arFaceAnchor); } } public static void RunRemoveAnchorCallbacks(ARFaceAnchor arFaceAnchor) { if (ARFaceAnchorRemovedEvent != null) { ARFaceAnchorRemovedEvent(arFaceAnchor); } } private static void CreateRemoteFaceTrackingConnection(ARKitFaceTrackingConfiguration config, UnityARSessionRunOption runOptions) { GameObject go = new GameObject("ARKitFaceTrackingRemoteConnection"); ARKitFaceTrackingRemoteConnection addComp = go.AddComponent<ARKitFaceTrackingRemoteConnection>(); addComp.enableLightEstimation = config.enableLightEstimation; addComp.resetTracking = (runOptions & UnityARSessionRunOption.ARSessionRunOptionResetTracking) != 0; addComp.removeExistingAnchors = (runOptions & UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors) != 0; } private static void CreateRemoteWorldTrackingConnection(ARKitWorldTrackingSessionConfiguration config, UnityARSessionRunOption runOptions) { GameObject go = new GameObject("ARKitWorldTrackingRemoteConnection"); ARKitRemoteConnection addComp = go.AddComponent<ARKitRemoteConnection>(); addComp.planeDetection = config.planeDetection; addComp.startAlignment = config.alignment; addComp.getPointCloud = config.getPointCloudData; addComp.enableLightEstimation = config.enableLightEstimation; addComp.resetTracking = (runOptions & UnityARSessionRunOption.ARSessionRunOptionResetTracking) != 0; addComp.removeExistingAnchors = (runOptions & UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors) != 0; } #endif public Matrix4x4 GetCameraPose() { Matrix4x4 matrix = new Matrix4x4(); matrix.SetColumn(0, s_Camera.worldTransform.column0); matrix.SetColumn(1, s_Camera.worldTransform.column1); matrix.SetColumn(2, s_Camera.worldTransform.column2); matrix.SetColumn(3, s_Camera.worldTransform.column3); return matrix; } public Matrix4x4 GetCameraProjection() { Matrix4x4 matrix = new Matrix4x4(); matrix.SetColumn(0, s_Camera.projectionMatrix.column0); matrix.SetColumn(1, s_Camera.projectionMatrix.column1); matrix.SetColumn(2, s_Camera.projectionMatrix.column2); matrix.SetColumn(3, s_Camera.projectionMatrix.column3); return matrix; } public void SetCameraClipPlanes(float nearZ, float farZ) { #if !UNITY_EDITOR && UNITY_IOS SetCameraNearFar (nearZ, farZ); #endif } public void SetCapturePixelData(bool enable, IntPtr pYByteArray, IntPtr pUVByteArray) { #if !UNITY_EDITOR && UNITY_IOS int iEnable = enable ? 1 : 0; CapturePixelData (iEnable,pYByteArray, pUVByteArray); #endif } [MonoPInvokeCallback(typeof(internal_ARFrameUpdate))] static void _frame_update(internal_UnityARCamera camera) { UnityARCamera pubCamera = new UnityARCamera(); pubCamera.projectionMatrix = camera.projectionMatrix; pubCamera.worldTransform = camera.worldTransform; pubCamera.trackingState = camera.trackingState; pubCamera.trackingReason = camera.trackingReason; pubCamera.videoParams = camera.videoParams; if (camera.getLightEstimation == 1) { pubCamera.lightData = camera.lightData; } pubCamera.displayTransform = camera.displayTransform; s_Camera = pubCamera; if (camera.getPointCloudData == 1) { UpdatePointCloudData(ref s_Camera); } if (ARFrameUpdatedEvent != null) { ARFrameUpdatedEvent(s_Camera); } } [MonoPInvokeCallback(typeof(internal_ARSessionTrackingChanged))] static void _ar_tracking_changed(internal_UnityARCamera camera) { // we only update the current camera's tracking state since that's all // this cllback is for s_Camera.trackingState = camera.trackingState; s_Camera.trackingReason = camera.trackingReason; if (ARSessionTrackingChangedEvent != null) { ARSessionTrackingChangedEvent(s_Camera); } } static void UpdatePointCloudData(ref UnityARCamera camera) { IntPtr ptrResultVerts = IntPtr.Zero; uint resultVertLength = 0; bool success = false; #if !UNITY_EDITOR && UNITY_IOS success = GetARPointCloud (ref ptrResultVerts, ref resultVertLength); #endif float[] resultVertices = null; if (success) { // Load the results into a managed array. resultVertices = new float[resultVertLength]; Marshal.Copy(ptrResultVerts, resultVertices, 0, (int)resultVertLength); Vector3[] verts = new Vector3[(resultVertLength / 4)]; for (int count = 0; count < resultVertLength; count++) { verts[count / 4].x = resultVertices[count++]; verts[count / 4].y = resultVertices[count++]; verts[count / 4].z = -resultVertices[count++]; } camera.pointCloudData = verts; } } static ARUserAnchor GetUserAnchorFromAnchorData(UnityARUserAnchorData anchor) { //get the identifier for this anchor from the pointer ARUserAnchor arUserAnchor = new ARUserAnchor(); arUserAnchor.identifier = Marshal.PtrToStringAuto(anchor.ptrIdentifier); Matrix4x4 matrix = new Matrix4x4(); matrix.SetColumn(0, anchor.transform.column0); matrix.SetColumn(1, anchor.transform.column1); matrix.SetColumn(2, anchor.transform.column2); matrix.SetColumn(3, anchor.transform.column3); arUserAnchor.transform = matrix; return arUserAnchor; } static ARHitTestResult GetHitTestResultFromResultData(UnityARHitTestResult resultData) { ARHitTestResult arHitTestResult = new ARHitTestResult(); arHitTestResult.type = resultData.type; arHitTestResult.distance = resultData.distance; arHitTestResult.localTransform = resultData.localTransform; arHitTestResult.worldTransform = resultData.worldTransform; arHitTestResult.isValid = resultData.isValid; if (resultData.anchor != IntPtr.Zero) { arHitTestResult.anchorIdentifier = Marshal.PtrToStringAuto(resultData.anchor); } return arHitTestResult; } #region Plane Anchors #if !UNITY_EDITOR && UNITY_IOS [MonoPInvokeCallback(typeof(internal_ARAnchorAdded))] static void _anchor_added(UnityARAnchorData anchor) { if (ARAnchorAddedEvent != null) { ARPlaneAnchor arPlaneAnchor = new ARPlaneAnchor(anchor); ARAnchorAddedEvent(arPlaneAnchor); } } [MonoPInvokeCallback(typeof(internal_ARAnchorUpdated))] static void _anchor_updated(UnityARAnchorData anchor) { if (ARAnchorUpdatedEvent != null) { ARPlaneAnchor arPlaneAnchor = new ARPlaneAnchor(anchor); ARAnchorUpdatedEvent(arPlaneAnchor); } } [MonoPInvokeCallback(typeof(internal_ARAnchorRemoved))] static void _anchor_removed(UnityARAnchorData anchor) { if (ARAnchorRemovedEvent != null) { ARPlaneAnchor arPlaneAnchor = new ARPlaneAnchor(anchor); ARAnchorRemovedEvent(arPlaneAnchor); } } #endif #endregion #region User Anchors [MonoPInvokeCallback(typeof(internal_ARUserAnchorAdded))] static void _user_anchor_added(UnityARUserAnchorData anchor) { if (ARUserAnchorAddedEvent != null) { ARUserAnchor arUserAnchor = GetUserAnchorFromAnchorData(anchor); ARUserAnchorAddedEvent(arUserAnchor); } } [MonoPInvokeCallback(typeof(internal_ARUserAnchorUpdated))] static void _user_anchor_updated(UnityARUserAnchorData anchor) { if (ARUserAnchorUpdatedEvent != null) { ARUserAnchor arUserAnchor = GetUserAnchorFromAnchorData(anchor); ARUserAnchorUpdatedEvent(arUserAnchor); } } [MonoPInvokeCallback(typeof(internal_ARUserAnchorRemoved))] static void _user_anchor_removed(UnityARUserAnchorData anchor) { if (ARUserAnchorRemovedEvent != null) { ARUserAnchor arUserAnchor = GetUserAnchorFromAnchorData(anchor); ARUserAnchorRemovedEvent(arUserAnchor); } } #endregion #region Face Anchors #if !UNITY_EDITOR && UNITY_IOS [MonoPInvokeCallback(typeof(internal_ARFaceAnchorAdded))] static void _face_anchor_added(UnityARFaceAnchorData anchor) { if (ARFaceAnchorAddedEvent != null) { ARFaceAnchor arFaceAnchor = new ARFaceAnchor(anchor); ARFaceAnchorAddedEvent(arFaceAnchor); } } [MonoPInvokeCallback(typeof(internal_ARFaceAnchorUpdated))] static void _face_anchor_updated(UnityARFaceAnchorData anchor) { if (ARFaceAnchorUpdatedEvent != null) { ARFaceAnchor arFaceAnchor = new ARFaceAnchor(anchor); ARFaceAnchorUpdatedEvent(arFaceAnchor); } } [MonoPInvokeCallback(typeof(internal_ARFaceAnchorRemoved))] static void _face_anchor_removed(UnityARFaceAnchorData anchor) { if (ARFaceAnchorRemovedEvent != null) { ARFaceAnchor arFaceAnchor = new ARFaceAnchor(anchor); ARFaceAnchorRemovedEvent(arFaceAnchor); } } #endif #endregion #region Image Anchors [MonoPInvokeCallback(typeof(internal_ARImageAnchorAdded))] static void _image_anchor_added(UnityARImageAnchorData anchor) { if (ARImageAnchorAddedEvent != null) { ARImageAnchor arImageAnchor = new ARImageAnchor(anchor); ARImageAnchorAddedEvent(arImageAnchor); } } [MonoPInvokeCallback(typeof(internal_ARImageAnchorUpdated))] static void _image_anchor_updated(UnityARImageAnchorData anchor) { if (ARImageAnchorUpdatedEvent != null) { ARImageAnchor arImageAnchor = new ARImageAnchor(anchor); ARImageAnchorUpdatedEvent(arImageAnchor); } } [MonoPInvokeCallback(typeof(internal_ARImageAnchorRemoved))] static void _image_anchor_removed(UnityARImageAnchorData anchor) { if (ARImageAnchorRemovedEvent != null) { ARImageAnchor arImageAnchor = new ARImageAnchor(anchor); ARImageAnchorRemovedEvent(arImageAnchor); } } #endregion [MonoPInvokeCallback(typeof(ARSessionFailed))] static void _ar_session_failed(string error) { if (ARSessionFailedEvent != null) { ARSessionFailedEvent(error); } } [MonoPInvokeCallback(typeof(ARSessionCallback))] static void _ar_session_interrupted() { Debug.Log("ar_session_interrupted"); if (ARSessionInterruptedEvent != null) { ARSessionInterruptedEvent(); } } [MonoPInvokeCallback(typeof(ARSessionCallback))] static void _ar_session_interruption_ended() { Debug.Log("ar_session_interruption_ended"); if (ARSessioninterruptionEndedEvent != null) { ARSessioninterruptionEndedEvent(); } } [MonoPInvokeCallback(typeof(ARSessionLocalizeCallback))] static bool _ar_session_should_relocalize() { Debug.Log("_ar_session_should_relocalize"); return ARSessionShouldAttemptRelocalization; } public void RunWithConfigAndOptions(ARKitWorldTrackingSessionConfiguration config, UnityARSessionRunOption runOptions) { #if !UNITY_EDITOR && UNITY_IOS StartWorldTrackingSessionWithOptions (m_NativeARSession, config, runOptions); #elif UNITY_EDITOR CreateRemoteWorldTrackingConnection(config, runOptions); #endif } public void RunWithConfig(ARKitWorldTrackingSessionConfiguration config) { #if !UNITY_EDITOR && UNITY_IOS StartWorldTrackingSession(m_NativeARSession, config); #elif UNITY_EDITOR UnityARSessionRunOption runOptions = UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors | UnityARSessionRunOption.ARSessionRunOptionResetTracking; CreateRemoteWorldTrackingConnection(config, runOptions); #endif } public void Run() { RunWithConfig(new ARKitWorldTrackingSessionConfiguration(UnityARAlignment.UnityARAlignmentGravity, UnityARPlaneDetection.Horizontal)); } public void RunWithConfigAndOptions(ARKitSessionConfiguration config, UnityARSessionRunOption runOptions) { #if !UNITY_EDITOR && UNITY_IOS StartSessionWithOptions (m_NativeARSession, config, runOptions); #endif } public void RunWithConfig(ARKitSessionConfiguration config) { #if !UNITY_EDITOR && UNITY_IOS StartSession(m_NativeARSession, config); #endif } public void RunWithConfigAndOptions(ARKitFaceTrackingConfiguration config, UnityARSessionRunOption runOptions) { #if !UNITY_EDITOR && UNITY_IOS StartFaceTrackingSessionWithOptions (m_NativeARSession, config, runOptions); #elif UNITY_EDITOR CreateRemoteFaceTrackingConnection(config, runOptions); #endif } public void RunWithConfig(ARKitFaceTrackingConfiguration config) { #if !UNITY_EDITOR && UNITY_IOS StartFaceTrackingSession(m_NativeARSession, config); #elif UNITY_EDITOR UnityARSessionRunOption runOptions = UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors | UnityARSessionRunOption.ARSessionRunOptionResetTracking; CreateRemoteFaceTrackingConnection(config, runOptions); #endif } public void Pause() { #if !UNITY_EDITOR && UNITY_IOS PauseSession(m_NativeARSession); #endif } public List<ARHitTestResult> HitTest(ARPoint point, ARHitTestResultType types) { List<ARHitTestResult> results = new List<ARHitTestResult>(); return HitTest(point, types, results); } public List<ARHitTestResult> HitTest(ARPoint point, ARHitTestResultType types, List<ARHitTestResult> results) { results.Clear(); #if !UNITY_EDITOR && UNITY_IOS int numResults = HitTest(m_NativeARSession, point, types); for (int i = 0; i < numResults; ++i) { var result = GetLastHitTestResult(i); results.Add(GetHitTestResultFromResultData(result)); } return results; #else return results; #endif } #if !UNITY_EDITOR && UNITY_IOS public ARTextureHandles GetARVideoTextureHandles() { return GetVideoTextureHandles (); } [Obsolete("Hook ARFrameUpdatedEvent instead and get UnityARCamera.ambientIntensity")] public float GetARAmbientIntensity() { return GetAmbientIntensity (); } [Obsolete("Hook ARFrameUpdatedEvent instead and get UnityARCamera.trackingState")] public int GetARTrackingQuality() { return GetTrackingQuality(); } #endif public UnityARUserAnchorData AddUserAnchor(UnityARUserAnchorData anchorData) { #if !UNITY_EDITOR && UNITY_IOS return SessionAddUserAnchor(m_NativeARSession, anchorData); #else return new UnityARUserAnchorData(); #endif } public UnityARUserAnchorData AddUserAnchorFromGameObject(GameObject go) { #if !UNITY_EDITOR && UNITY_IOS UnityARUserAnchorData data = AddUserAnchor(UnityARUserAnchorData.UnityARUserAnchorDataFromGameObject(go)); return data; #else return new UnityARUserAnchorData(); #endif } public void RemoveUserAnchor(string anchorIdentifier) { #if !UNITY_EDITOR && UNITY_IOS SessionRemoveUserAnchor(m_NativeARSession, anchorIdentifier); #endif } public void SetWorldOrigin(Transform worldTransform) { #if !UNITY_EDITOR && UNITY_IOS //convert from Unity coord system to ARKit Matrix4x4 worldMatrix = UnityARMatrixOps.UnityToARKitCoordChange(worldTransform.position, worldTransform.rotation); SessionSetWorldOrigin (m_NativeARSession, worldMatrix); #endif } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; namespace THNETII.TypeConverter { /// <summary> /// Helper class that provides Enum-String Conversions. /// </summary> public static class EnumStringConverter { private delegate bool EnumTryParseFunc<T>(string s, out T value) where T : struct, Enum; private enum PlaceholderEnum : int { } private static class EnumValues<T> where T : struct, Enum { public static readonly Type TypeRef = typeof(T); public static readonly EnumTryParseFunc<T> NumericTryParse = InitializeNumericTryParse(); public static readonly IDictionary<string, T> StringToValue = InitializeStringToValueDictionary(); public static readonly IDictionary<T, string> ValueToString = InitializeValueToStringDictionary(); static void InitializeConversionDictionary(Action<string, T> dictionaryAddValueAction) { var ti = TypeRef.GetTypeInfo(); foreach (var fi in ti.DeclaredFields.Where(i => i.IsStatic)) { T v = (T)fi.GetValue(null); string s = fi.Name; dictionaryAddValueAction(s, v); } } static IDictionary<string, T> InitializeStringToValueDictionary() { var stringToValue = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); InitializeConversionDictionary((s, v) => { if (s is null) return; if (!stringToValue.ContainsKey(s)) stringToValue[s] = v; }); return stringToValue; } static IDictionary<T, string> InitializeValueToStringDictionary() { var valueToString = new Dictionary<T, string>(); InitializeConversionDictionary((s, v) => { if (!valueToString.ContainsKey(v)) valueToString[v] = s; }); return valueToString; } static EnumTryParseFunc<T> InitializeNumericTryParse() { var numericType = Enum.GetUnderlyingType(typeof(T)); var miGeneric = ((Func<NumberStringConverter<int>, EnumTryParseFunc<PlaceholderEnum>>)InitializeNumericTryParseFromUnderlyingType<int, PlaceholderEnum>) #if NETSTANDARD1_3 .GetMethodInfo() #else // !NETSTANDARD1_3 .Method #endif // !NETSTANDARD1_3 .GetGenericMethodDefinition(); var numberConverterType = typeof(NumberStringConverter<>) #if NETSTANDARD1_3 .GetTypeInfo() #endif // NETSTANDARD1_3 .MakeGenericType(numericType); var primitiveConverter = NumberStringConverter.CurrentCulture; var numericConverterProperty = primitiveConverter.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Static) .FirstOrDefault(pi => pi.PropertyType == numberConverterType); if (numericConverterProperty is PropertyInfo) { var numberConverter = numericConverterProperty.GetValue(primitiveConverter); var miNumeric = miGeneric.MakeGenericMethod(numericType, typeof(T)); return (EnumTryParseFunc<T>)miNumeric.Invoke(null, new[] { numberConverter }); } return null!; } static EnumTryParseFunc<TEnum> InitializeNumericTryParseFromUnderlyingType<TNumeric, TEnum>(NumberStringConverter<TNumeric> numberStringConverter) where TNumeric : unmanaged, IFormattable where TEnum : unmanaged, Enum { return TryParse; bool TryParse(string s, out TEnum value) { if (numberStringConverter.TryParse(s, out var numeric)) { unsafe { TEnum* pNumeric = (TEnum*)&numeric; value = *pNumeric; } } value = default; return false; } } } /// <summary> /// Converts the string representation of the constant name, serialization name or the numeric value of one /// or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, or numeric value to convert.</param> /// <returns>The converted value as an instance of <typeparamref name="T"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T Parse<T>(string? s) where T : struct, Enum { if (TryParse(s, out T value)) return value; return (T)Enum.Parse(EnumValues<T>.TypeRef, s, ignoreCase: true); } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the default value for <typeparamref name="T"/> in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or the default value of <typeparamref name="T"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s) where T : struct, Enum => ParseOrDefault<T>(s, @default: default); /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the specified alternate value in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="default">The default value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or <paramref name="default"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s, T @default) where T : struct, Enum { if (TryParse(s, out T value)) return value; return @default; } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the specified alternate value in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="defaultFactory">The factory that produces the value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. Must not be <see langword="null"/>.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or the return value from <paramref name="defaultFactory"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="defaultFactory"/> is <see langword="null"/>.</exception> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s, Func<T> defaultFactory) where T : struct, Enum { if (TryParse(s, out T value)) return value; else if (defaultFactory is null) throw new ArgumentNullException(nameof(defaultFactory)); return defaultFactory(); } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the specified alternate value in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="defaultFactory">The factory that produces the value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. Must not be <see langword="null"/>.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or the return value from <paramref name="defaultFactory"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="defaultFactory"/> is <see langword="null"/>.</exception> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s, Func<string?, T> defaultFactory) where T : struct, Enum { if (TryParse(s, out T value)) return value; else if (defaultFactory is null) throw new ArgumentNullException(nameof(defaultFactory)); return defaultFactory(s); } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns <see langword="null"/> in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or <see langword="null"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T? ParseOrNull<T>(string? s) where T : struct, Enum { if (TryParse(s, out T value)) return value; return null; } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns <see langword="null"/> in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="value">The converted value of <paramref name="s"/> if the method returns <see langword="true"/>.</param> /// <returns> /// <see langword="true"/> if <paramref name="s"/> was successfully converted to a value of <typeparamref name="T"/>; otherwise, <see langword="false"/>. /// </returns> /// <remarks>If this method returns <see langword="false"/>, the out-value of the <paramref name="value"/> parameter is not defined.</remarks> [SuppressMessage("Microsoft.Design", "CA1000")] public static bool TryParse<T>(string? s, out T value) where T : struct, Enum { if (!(s is null)) { if (EnumValues<T>.StringToValue.TryGetValue(s, out value) || EnumValues<T>.NumericTryParse(s, out value)) return true; } return Enum.TryParse(s, out value); } /// <summary> /// Returns the name or the default string representation of the specified value. /// </summary> /// <typeparam name="T">The enumeration type to convert from.</typeparam> /// <param name="value">The value of <typeparamref name="T"/> to serialize.</param> [SuppressMessage("Microsoft.Design", "CA1000")] public static string ToString<T>(T value) where T : struct, Enum { if (EnumValues<T>.ValueToString.TryGetValue(value, out string s)) return s; return value.ToString(); } } }
using System; using System.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal class OpenSslX509Encoder : IX509Pal { public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters) { switch (oid.Value) { case Oids.RsaRsa: return BuildRsaPublicKey(encodedKeyValue); } // NotSupportedException is what desktop and CoreFx-Windows throw in this situation. throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } public unsafe string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flag) { using (SafeX509NameHandle x509Name = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_X509_NAME, encodedDistinguishedName)) { Interop.libcrypto.CheckValidOpenSslHandle(x509Name); using (SafeBioHandle bioHandle = Interop.libcrypto.BIO_new(Interop.libcrypto.BIO_s_mem())) { Interop.libcrypto.CheckValidOpenSslHandle(bioHandle); OpenSslX09NameFormatFlags nativeFlags = ConvertFormatFlags(flag); int written = Interop.libcrypto.X509_NAME_print_ex( bioHandle, x509Name, 0, new UIntPtr((uint)nativeFlags)); // X509_NAME_print_ex returns how many bytes were written into the buffer. // BIO_gets wants to ensure that the response is NULL-terminated. // So add one to leave space for the NULL. StringBuilder builder = new StringBuilder(written + 1); int read = Interop.libcrypto.BIO_gets(bioHandle, builder, builder.Capacity); if (read < 0) { throw Interop.libcrypto.CreateOpenSslCryptographicException(); } return builder.ToString(); } } } public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag) { throw new NotImplementedException(); } public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine) { throw new NotImplementedException(); } public X509ContentType GetCertContentType(byte[] rawData) { throw new NotImplementedException(); } public X509ContentType GetCertContentType(string fileName) { throw new NotImplementedException(); } public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { throw new NotImplementedException(); } public unsafe void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { using (SafeAsn1BitStringHandle bitString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_BIT_STRING, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(bitString); byte[] decoded = Interop.NativeCrypto.GetAsn1StringBytes(bitString.DangerousGetHandle()); // Only 9 bits are defined. if (decoded.Length > 2) { throw new CryptographicException(); } // DER encodings of BIT_STRING values number the bits as // 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding. // // So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit // is set in this byte stream. // // BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which // is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore // 0x02 (length remaining) 0x01 (1 bit padding) 0x22. // // OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up // exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02) // // Once the decipherOnly (8) bit is added to the mix, the values become: // 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding) // { 0x03 0x07 0x22 0x80 } // And OpenSSL returns new byte[] { 0x22 0x80 } // // The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian // representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively // ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all // line up with the existing X509KeyUsageFlags. int value = 0; if (decoded.Length > 0) { value = decoded[0]; } if (decoded.Length > 1) { value |= decoded[1] << 8; } keyUsages = (X509KeyUsageFlags)value; } } public byte[] EncodeX509BasicConstraints2Extension( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { throw new NotImplementedException(); } public void DecodeX509BasicConstraintsExtension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { throw new NotImplementedException(); } public unsafe void DecodeX509BasicConstraints2Extension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { using (SafeBasicConstraintsHandle constraints = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_BASIC_CONSTRAINTS, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(constraints); Interop.libcrypto.BASIC_CONSTRAINTS* data = (Interop.libcrypto.BASIC_CONSTRAINTS*)constraints.DangerousGetHandle(); certificateAuthority = data->CA != 0; if (data->pathlen != IntPtr.Zero) { hasPathLengthConstraint = true; pathLengthConstraint = Interop.libcrypto.ASN1_INTEGER_get(data->pathlen).ToInt32(); } else { hasPathLengthConstraint = false; pathLengthConstraint = 0; } } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { throw new NotImplementedException(); } public unsafe void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection oids = new OidCollection(); using (SafeEkuExtensionHandle eku = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_EXTENDED_KEY_USAGE, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(eku); int count = Interop.NativeCrypto.GetX509EkuFieldCount(eku); for (int i = 0; i < count; i++) { IntPtr oidPtr = Interop.NativeCrypto.GetX509EkuField(eku, i); if (oidPtr == IntPtr.Zero) { throw Interop.libcrypto.CreateOpenSslCryptographicException(); } string oidValue = Interop.libcrypto.OBJ_obj2txt_helper(oidPtr); oids.Add(new Oid(oidValue)); } } usages = oids; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { throw new NotImplementedException(); } public unsafe void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { using (SafeAsn1OctetStringHandle octetString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_OCTET_STRING, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(octetString); subjectKeyIdentifier = Interop.NativeCrypto.GetAsn1StringBytes(octetString.DangerousGetHandle()); } } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { throw new NotImplementedException(); } private static OpenSslX09NameFormatFlags ConvertFormatFlags(X500DistinguishedNameFlags inFlags) { OpenSslX09NameFormatFlags outFlags = 0; if (inFlags.HasFlag(X500DistinguishedNameFlags.Reversed)) { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_DN_REV; } if (inFlags.HasFlag(X500DistinguishedNameFlags.UseSemicolons)) { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_SPLUS_SPC; } else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseNewLines)) { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_MULTILINE; } else { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_CPLUS_SPC; } if (inFlags.HasFlag(X500DistinguishedNameFlags.DoNotUseQuotes)) { // TODO: Handle this. } if (inFlags.HasFlag(X500DistinguishedNameFlags.ForceUTF8Encoding)) { // TODO: Handle this. } if (inFlags.HasFlag(X500DistinguishedNameFlags.UseUTF8Encoding)) { // TODO: Handle this. } else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseT61Encoding)) { // TODO: Handle this. } return outFlags; } private static unsafe RSA BuildRsaPublicKey(byte[] encodedData) { using (SafeRsaHandle rsaHandle = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_RSAPublicKey, encodedData)) { Interop.libcrypto.CheckValidOpenSslHandle(rsaHandle); RSAParameters rsaParameters = Interop.libcrypto.ExportRsaParameters(rsaHandle, false); RSA rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaParameters); return rsa; } } [Flags] private enum OpenSslX09NameFormatFlags : uint { XN_FLAG_SEP_MASK = (0xf << 16), // O=Apache HTTP Server, OU=Test Certificate, CN=localhost // Note that this is the only not-reversed value, since XN_FLAG_COMPAT | XN_FLAG_DN_REV produces nothing. XN_FLAG_COMPAT = 0, // CN=localhost,OU=Test Certificate,O=Apache HTTP Server XN_FLAG_SEP_COMMA_PLUS = (1 << 16), // CN=localhost, OU=Test Certificate, O=Apache HTTP Server XN_FLAG_SEP_CPLUS_SPC = (2 << 16), // CN=localhost; OU=Test Certificate; O=Apache HTTP Server XN_FLAG_SEP_SPLUS_SPC = (3 << 16), // CN=localhost // OU=Test Certificate // O=Apache HTTP Server XN_FLAG_SEP_MULTILINE = (4 << 16), XN_FLAG_DN_REV = (1 << 20), XN_FLAG_FN_MASK = (0x3 << 21), // CN=localhost, OU=Test Certificate, O=Apache HTTP Server XN_FLAG_FN_SN = 0, // commonName=localhost, organizationalUnitName=Test Certificate, organizationName=Apache HTTP Server XN_FLAG_FN_LN = (1 << 21), // 2.5.4.3=localhost, 2.5.4.11=Test Certificate, 2.5.4.10=Apache HTTP Server XN_FLAG_FN_OID = (2 << 21), // localhost, Test Certificate, Apache HTTP Server XN_FLAG_FN_NONE = (3 << 21), // CN = localhost, OU = Test Certificate, O = Apache HTTP Server XN_FLAG_SPC_EQ = (1 << 23), XN_FLAG_DUMP_UNKNOWN_FIELDS = (1 << 24), XN_FLAG_FN_ALIGN = (1 << 25), } } }
/* * 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.IO; using System.Collections.Generic; using System.Reflection; using log4net; using Tools; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.ScriptEngine.Shared.CodeTools { public class CSCodeGenerator : ICodeConverter { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private SYMBOL m_astRoot = null; private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap; private int m_indentWidth = 4; // for indentation private int m_braceCount; // for indentation private int m_CSharpLine; // the current line of generated C# code private int m_CSharpCol; // the current column of generated C# code private List<string> m_warnings = new List<string>(); private IScriptModuleComms m_comms = null; private bool m_insertCoopTerminationChecks; private static string m_coopTerminationCheck = "opensim_reserved_CheckForCoopTermination();"; /// <summary> /// Keep a record of the previous node when we do the parsing. /// </summary> /// <remarks> /// We do this here because the parser generated by CSTools does not retain a reference to its parent node. /// The previous node is required so we can correctly insert co-op termination checks when required. /// </remarks> // private SYMBOL m_previousNode; /// <summary> /// Creates an 'empty' CSCodeGenerator instance. /// </summary> public CSCodeGenerator() { m_comms = null; ResetCounters(); } public CSCodeGenerator(IScriptModuleComms comms, bool insertCoopTerminationChecks) { m_comms = comms; m_insertCoopTerminationChecks = insertCoopTerminationChecks; ResetCounters(); } /// <summary> /// Get the mapping between LSL and C# line/column number. /// </summary> /// <returns>Dictionary\<KeyValuePair\<int, int\>, KeyValuePair\<int, int\>\>.</returns> public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> PositionMap { get { return m_positionMap; } } /// <summary> /// Get the mapping between LSL and C# line/column number. /// </summary> /// <returns>SYMBOL pointing to root of the abstract syntax tree.</returns> public SYMBOL ASTRoot { get { return m_astRoot; } } /// <summary> /// Resets various counters and metadata. /// </summary> private void ResetCounters() { m_braceCount = 0; m_CSharpLine = 0; m_CSharpCol = 1; m_positionMap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); m_astRoot = null; } /// <summary> /// Generate the code from the AST we have. /// </summary> /// <param name="script">The LSL source as a string.</param> /// <returns>String containing the generated C# code.</returns> public string Convert(string script) { // m_log.DebugFormat("[CS CODE GENERATOR]: Converting to C#\n{0}", script); m_warnings.Clear(); ResetCounters(); Parser p = new LSLSyntax(new yyLSLSyntax(), new ErrorHandler(true)); LSL2CSCodeTransformer codeTransformer; try { codeTransformer = new LSL2CSCodeTransformer(p.Parse(script)); } catch (CSToolsException e) { string message; // LL start numbering lines at 0 - geeks! // Also need to subtract one line we prepend! // string emessage = e.Message; string slinfo = e.slInfo.ToString(); // Remove wrong line number info // if (emessage.StartsWith(slinfo+": ")) emessage = emessage.Substring(slinfo.Length+2); message = String.Format("({0},{1}) {2}", e.slInfo.lineNumber - 1, e.slInfo.charPosition - 1, emessage); throw new Exception(message); } m_astRoot = codeTransformer.Transform(); string retstr = String.Empty; // standard preamble //retstr = GenerateLine("using OpenSim.Region.ScriptEngine.Common;"); //retstr += GenerateLine("using System.Collections.Generic;"); //retstr += GenerateLine(""); //retstr += GenerateLine("namespace SecondLife"); //retstr += GenerateLine("{"); m_braceCount++; //retstr += GenerateIndentedLine("public class Script : OpenSim.Region.ScriptEngine.Common"); //retstr += GenerateIndentedLine("{"); m_braceCount++; // line number m_CSharpLine += 3; // here's the payload retstr += GenerateLine(); foreach (SYMBOL s in m_astRoot.kids) retstr += GenerateNode(m_astRoot, s); // close braces! m_braceCount--; //retstr += GenerateIndentedLine("}"); m_braceCount--; //retstr += GenerateLine("}"); // Removes all carriage return characters which may be generated in Windows platform. Is there // cleaner way of doing this? retstr = retstr.Replace("\r", ""); return retstr; } /// <summary> /// Get the set of warnings generated during compilation. /// </summary> /// <returns></returns> public string[] GetWarnings() { return m_warnings.ToArray(); } private void AddWarning(string warning) { if (!m_warnings.Contains(warning)) { m_warnings.Add(warning); } } /// <summary> /// Recursively called to generate each type of node. Will generate this /// node, then all it's children. /// </summary> /// <param name="previousSymbol">The parent node.</param> /// <param name="s">The current node to generate code for.</param> /// <returns>String containing C# code for SYMBOL s.</returns> private string GenerateNode(SYMBOL previousSymbol, SYMBOL s) { string retstr = String.Empty; // make sure to put type lower in the inheritance hierarchy first // ie: since IdentArgument and ExpressionArgument inherit from // Argument, put IdentArgument and ExpressionArgument before Argument if (s is GlobalFunctionDefinition) retstr += GenerateGlobalFunctionDefinition((GlobalFunctionDefinition) s); else if (s is GlobalVariableDeclaration) retstr += GenerateGlobalVariableDeclaration((GlobalVariableDeclaration) s); else if (s is State) retstr += GenerateState((State) s); else if (s is CompoundStatement) retstr += GenerateCompoundStatement(previousSymbol, (CompoundStatement) s); else if (s is Declaration) retstr += GenerateDeclaration((Declaration) s); else if (s is Statement) retstr += GenerateStatement(previousSymbol, (Statement) s); else if (s is ReturnStatement) retstr += GenerateReturnStatement((ReturnStatement) s); else if (s is JumpLabel) retstr += GenerateJumpLabel((JumpLabel) s); else if (s is JumpStatement) retstr += GenerateJumpStatement((JumpStatement) s); else if (s is StateChange) retstr += GenerateStateChange((StateChange) s); else if (s is IfStatement) retstr += GenerateIfStatement((IfStatement) s); else if (s is WhileStatement) retstr += GenerateWhileStatement((WhileStatement) s); else if (s is DoWhileStatement) retstr += GenerateDoWhileStatement((DoWhileStatement) s); else if (s is ForLoop) retstr += GenerateForLoop((ForLoop) s); else if (s is ArgumentList) retstr += GenerateArgumentList((ArgumentList) s); else if (s is Assignment) retstr += GenerateAssignment((Assignment) s); else if (s is BinaryExpression) retstr += GenerateBinaryExpression((BinaryExpression) s); else if (s is ParenthesisExpression) retstr += GenerateParenthesisExpression((ParenthesisExpression) s); else if (s is UnaryExpression) retstr += GenerateUnaryExpression((UnaryExpression) s); else if (s is IncrementDecrementExpression) retstr += GenerateIncrementDecrementExpression((IncrementDecrementExpression) s); else if (s is TypecastExpression) retstr += GenerateTypecastExpression((TypecastExpression) s); else if (s is FunctionCall) retstr += GenerateFunctionCall((FunctionCall) s); else if (s is VectorConstant) retstr += GenerateVectorConstant((VectorConstant) s); else if (s is RotationConstant) retstr += GenerateRotationConstant((RotationConstant) s); else if (s is ListConstant) retstr += GenerateListConstant((ListConstant) s); else if (s is Constant) retstr += GenerateConstant((Constant) s); else if (s is IdentDotExpression) retstr += Generate(CheckName(((IdentDotExpression) s).Name) + "." + ((IdentDotExpression) s).Member, s); else if (s is IdentExpression) retstr += GenerateIdentifier(((IdentExpression) s).Name, s); else if (s is IDENT) retstr += Generate(CheckName(((TOKEN) s).yytext), s); else { foreach (SYMBOL kid in s.kids) retstr += GenerateNode(s, kid); } return retstr; } /// <summary> /// Generates the code for a GlobalFunctionDefinition node. /// </summary> /// <param name="gf">The GlobalFunctionDefinition node.</param> /// <returns>String containing C# code for GlobalFunctionDefinition gf.</returns> private string GenerateGlobalFunctionDefinition(GlobalFunctionDefinition gf) { string retstr = String.Empty; // we need to separate the argument declaration list from other kids List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>(); List<SYMBOL> remainingKids = new List<SYMBOL>(); foreach (SYMBOL kid in gf.kids) if (kid is ArgumentDeclarationList) argumentDeclarationListKids.Add(kid); else remainingKids.Add(kid); retstr += GenerateIndented(String.Format("{0} {1}(", gf.ReturnType, CheckName(gf.Name)), gf); // print the state arguments, if any foreach (SYMBOL kid in argumentDeclarationListKids) retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList) kid); retstr += GenerateLine(")"); foreach (SYMBOL kid in remainingKids) retstr += GenerateNode(gf, kid); return retstr; } /// <summary> /// Generates the code for a GlobalVariableDeclaration node. /// </summary> /// <param name="gv">The GlobalVariableDeclaration node.</param> /// <returns>String containing C# code for GlobalVariableDeclaration gv.</returns> private string GenerateGlobalVariableDeclaration(GlobalVariableDeclaration gv) { string retstr = String.Empty; foreach (SYMBOL s in gv.kids) { retstr += Indent(); retstr += GenerateNode(gv, s); retstr += GenerateLine(";"); } return retstr; } /// <summary> /// Generates the code for a State node. /// </summary> /// <param name="s">The State node.</param> /// <returns>String containing C# code for State s.</returns> private string GenerateState(State s) { string retstr = String.Empty; foreach (SYMBOL kid in s.kids) if (kid is StateEvent) retstr += GenerateStateEvent((StateEvent) kid, s.Name); return retstr; } /// <summary> /// Generates the code for a StateEvent node. /// </summary> /// <param name="se">The StateEvent node.</param> /// <param name="parentStateName">The name of the parent state.</param> /// <returns>String containing C# code for StateEvent se.</returns> private string GenerateStateEvent(StateEvent se, string parentStateName) { string retstr = String.Empty; // we need to separate the argument declaration list from other kids List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>(); List<SYMBOL> remainingKids = new List<SYMBOL>(); foreach (SYMBOL kid in se.kids) if (kid is ArgumentDeclarationList) argumentDeclarationListKids.Add(kid); else remainingKids.Add(kid); // "state" (function) declaration retstr += GenerateIndented(String.Format("public void {0}_event_{1}(", parentStateName, se.Name), se); // print the state arguments, if any foreach (SYMBOL kid in argumentDeclarationListKids) retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList) kid); retstr += GenerateLine(")"); foreach (SYMBOL kid in remainingKids) retstr += GenerateNode(se, kid); return retstr; } /// <summary> /// Generates the code for an ArgumentDeclarationList node. /// </summary> /// <param name="adl">The ArgumentDeclarationList node.</param> /// <returns>String containing C# code for ArgumentDeclarationList adl.</returns> private string GenerateArgumentDeclarationList(ArgumentDeclarationList adl) { string retstr = String.Empty; int comma = adl.kids.Count - 1; // tells us whether to print a comma foreach (Declaration d in adl.kids) { retstr += Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for an ArgumentList node. /// </summary> /// <param name="al">The ArgumentList node.</param> /// <returns>String containing C# code for ArgumentList al.</returns> private string GenerateArgumentList(ArgumentList al) { string retstr = String.Empty; int comma = al.kids.Count - 1; // tells us whether to print a comma foreach (SYMBOL s in al.kids) { retstr += GenerateNode(al, s); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for a CompoundStatement node. /// </summary> /// <param name="cs">The CompoundStatement node.</param> /// <returns>String containing C# code for CompoundStatement cs.</returns> private string GenerateCompoundStatement(SYMBOL previousSymbol, CompoundStatement cs) { string retstr = String.Empty; // opening brace retstr += GenerateIndentedLine("{"); m_braceCount++; if (m_insertCoopTerminationChecks) { // We have to check in event functions as well because the user can manually call these. if (previousSymbol is GlobalFunctionDefinition || previousSymbol is WhileStatement || previousSymbol is DoWhileStatement || previousSymbol is ForLoop || previousSymbol is StateEvent) retstr += GenerateIndentedLine(m_coopTerminationCheck); } foreach (SYMBOL kid in cs.kids) retstr += GenerateNode(cs, kid); // closing brace m_braceCount--; retstr += GenerateIndentedLine("}"); return retstr; } /// <summary> /// Generates the code for a Declaration node. /// </summary> /// <param name="d">The Declaration node.</param> /// <returns>String containing C# code for Declaration d.</returns> private string GenerateDeclaration(Declaration d) { return Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d); } /// <summary> /// Generates the code for a Statement node. /// </summary> /// <param name="s">The Statement node.</param> /// <returns>String containing C# code for Statement s.</returns> private string GenerateStatement(SYMBOL previousSymbol, Statement s) { string retstr = String.Empty; bool printSemicolon = true; bool transformToBlock = false; if (m_insertCoopTerminationChecks) { // A non-braced single line do while structure cannot contain multiple statements. // So to insert the termination check we change this to a braced control structure instead. if (previousSymbol is WhileStatement || previousSymbol is DoWhileStatement || previousSymbol is ForLoop) { transformToBlock = true; // FIXME: This will be wrongly indented because the previous for/while/dowhile will have already indented. retstr += GenerateIndentedLine("{"); retstr += GenerateIndentedLine(m_coopTerminationCheck); } } retstr += Indent(); if (0 < s.kids.Count) { // Jump label prints its own colon, we don't need a semicolon. printSemicolon = !(s.kids.Top is JumpLabel); // If we encounter a lone Ident, we skip it, since that's a C# // (MONO) error. if (!(s.kids.Top is IdentExpression && 1 == s.kids.Count)) foreach (SYMBOL kid in s.kids) retstr += GenerateNode(s, kid); } if (printSemicolon) retstr += GenerateLine(";"); if (transformToBlock) { // FIXME: This will be wrongly indented because the for/while/dowhile is currently handling the unindent retstr += GenerateIndentedLine("}"); } return retstr; } /// <summary> /// Generates the code for an Assignment node. /// </summary> /// <param name="a">The Assignment node.</param> /// <returns>String containing C# code for Assignment a.</returns> private string GenerateAssignment(Assignment a) { string retstr = String.Empty; List<string> identifiers = new List<string>(); checkForMultipleAssignments(identifiers, a); retstr += GenerateNode(a, (SYMBOL) a.kids.Pop()); retstr += Generate(String.Format(" {0} ", a.AssignmentType), a); foreach (SYMBOL kid in a.kids) retstr += GenerateNode(a, kid); return retstr; } // This code checks for LSL of the following forms, and generates a // warning if it finds them. // // list l = [ "foo" ]; // l = (l=[]) + l + ["bar"]; // (produces l=["foo","bar"] in SL but l=["bar"] in OS) // // integer i; // integer j; // i = (j = 3) + (j = 4) + (j = 5); // (produces j=3 in SL but j=5 in OS) // // Without this check, that code passes compilation, but does not do what // the end user expects, because LSL in SL evaluates right to left instead // of left to right. // // The theory here is that producing an error and alerting the end user that // something needs to change is better than silently generating incorrect code. private void checkForMultipleAssignments(List<string> identifiers, SYMBOL s) { if (s is Assignment) { Assignment a = (Assignment)s; string newident = null; if (a.kids[0] is Declaration) { newident = ((Declaration)a.kids[0]).Id; } else if (a.kids[0] is IDENT) { newident = ((IDENT)a.kids[0]).yytext; } else if (a.kids[0] is IdentDotExpression) { newident = ((IdentDotExpression)a.kids[0]).Name; // +"." + ((IdentDotExpression)a.kids[0]).Member; } else { AddWarning(String.Format("Multiple assignments checker internal error '{0}' at line {1} column {2}.", a.kids[0].GetType(), ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position)); } if (identifiers.Contains(newident)) { AddWarning(String.Format("Multiple assignments to '{0}' at line {1} column {2}; results may differ between LSL and OSSL.", newident, ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position)); } identifiers.Add(newident); } int index; for (index = 0; index < s.kids.Count; index++) { checkForMultipleAssignments(identifiers, (SYMBOL) s.kids[index]); } } /// <summary> /// Generates the code for a ReturnStatement node. /// </summary> /// <param name="rs">The ReturnStatement node.</param> /// <returns>String containing C# code for ReturnStatement rs.</returns> private string GenerateReturnStatement(ReturnStatement rs) { string retstr = String.Empty; retstr += Generate("return ", rs); foreach (SYMBOL kid in rs.kids) retstr += GenerateNode(rs, kid); return retstr; } /// <summary> /// Generates the code for a JumpLabel node. /// </summary> /// <param name="jl">The JumpLabel node.</param> /// <returns>String containing C# code for JumpLabel jl.</returns> private string GenerateJumpLabel(JumpLabel jl) { string labelStatement; if (m_insertCoopTerminationChecks) labelStatement = m_coopTerminationCheck + "\n"; else labelStatement = "NoOp();\n"; return Generate(String.Format("{0}: ", CheckName(jl.LabelName)), jl) + labelStatement; } /// <summary> /// Generates the code for a JumpStatement node. /// </summary> /// <param name="js">The JumpStatement node.</param> /// <returns>String containing C# code for JumpStatement js.</returns> private string GenerateJumpStatement(JumpStatement js) { return Generate(String.Format("goto {0}", CheckName(js.TargetName)), js); } /// <summary> /// Generates the code for an IfStatement node. /// </summary> /// <param name="ifs">The IfStatement node.</param> /// <returns>String containing C# code for IfStatement ifs.</returns> private string GenerateIfStatement(IfStatement ifs) { string retstr = String.Empty; retstr += GenerateIndented("if (", ifs); retstr += GenerateNode(ifs, (SYMBOL) ifs.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = ifs.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(ifs, (SYMBOL) ifs.kids.Pop()); if (indentHere) m_braceCount--; if (0 < ifs.kids.Count) // do it again for an else { retstr += GenerateIndentedLine("else", ifs); indentHere = ifs.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(ifs, (SYMBOL) ifs.kids.Pop()); if (indentHere) m_braceCount--; } return retstr; } /// <summary> /// Generates the code for a StateChange node. /// </summary> /// <param name="sc">The StateChange node.</param> /// <returns>String containing C# code for StateChange sc.</returns> private string GenerateStateChange(StateChange sc) { return Generate(String.Format("state(\"{0}\")", sc.NewState), sc); } /// <summary> /// Generates the code for a WhileStatement node. /// </summary> /// <param name="ws">The WhileStatement node.</param> /// <returns>String containing C# code for WhileStatement ws.</returns> private string GenerateWhileStatement(WhileStatement ws) { string retstr = String.Empty; retstr += GenerateIndented("while (", ws); retstr += GenerateNode(ws, (SYMBOL) ws.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = ws.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(ws, (SYMBOL) ws.kids.Pop()); if (indentHere) m_braceCount--; return retstr; } /// <summary> /// Generates the code for a DoWhileStatement node. /// </summary> /// <param name="dws">The DoWhileStatement node.</param> /// <returns>String containing C# code for DoWhileStatement dws.</returns> private string GenerateDoWhileStatement(DoWhileStatement dws) { string retstr = String.Empty; retstr += GenerateIndentedLine("do", dws); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = dws.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(dws, (SYMBOL) dws.kids.Pop()); if (indentHere) m_braceCount--; retstr += GenerateIndented("while (", dws); retstr += GenerateNode(dws, (SYMBOL) dws.kids.Pop()); retstr += GenerateLine(");"); return retstr; } /// <summary> /// Generates the code for a ForLoop node. /// </summary> /// <param name="fl">The ForLoop node.</param> /// <returns>String containing C# code for ForLoop fl.</returns> private string GenerateForLoop(ForLoop fl) { string retstr = String.Empty; retstr += GenerateIndented("for (", fl); // It's possible that we don't have an assignment, in which case // the child will be null and we only print the semicolon. // for (x = 0; x < 10; x++) // ^^^^^ ForLoopStatement s = (ForLoopStatement) fl.kids.Pop(); if (null != s) { retstr += GenerateForLoopStatement(s); } retstr += Generate("; "); // for (x = 0; x < 10; x++) // ^^^^^^ retstr += GenerateNode(fl, (SYMBOL) fl.kids.Pop()); retstr += Generate("; "); // for (x = 0; x < 10; x++) // ^^^ retstr += GenerateForLoopStatement((ForLoopStatement) fl.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = fl.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(fl, (SYMBOL) fl.kids.Pop()); if (indentHere) m_braceCount--; return retstr; } /// <summary> /// Generates the code for a ForLoopStatement node. /// </summary> /// <param name="fls">The ForLoopStatement node.</param> /// <returns>String containing C# code for ForLoopStatement fls.</returns> private string GenerateForLoopStatement(ForLoopStatement fls) { string retstr = String.Empty; int comma = fls.kids.Count - 1; // tells us whether to print a comma // It's possible that all we have is an empty Ident, for example: // // for (x; x < 10; x++) { ... } // // Which is illegal in C# (MONO). We'll skip it. if (fls.kids.Top is IdentExpression && 1 == fls.kids.Count) return retstr; for (int i = 0; i < fls.kids.Count; i++) { SYMBOL s = (SYMBOL)fls.kids[i]; // Statements surrounded by parentheses in for loops // // e.g. for ((i = 0), (j = 7); (i < 10); (++i)) // // are legal in LSL but not in C# so we need to discard the parentheses // // The following, however, does not appear to be legal in LLS // // for ((i = 0, j = 7); (i < 10); (++i)) // // As of Friday 20th November 2009, the Linden Lab simulators appear simply never to compile or run this // script but with no debug or warnings at all! Therefore, we won't deal with this yet (which looks // like it would be considerably more complicated to handle). while (s is ParenthesisExpression) s = (SYMBOL)s.kids.Pop(); retstr += GenerateNode(fls, s); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for a BinaryExpression node. /// </summary> /// <param name="be">The BinaryExpression node.</param> /// <returns>String containing C# code for BinaryExpression be.</returns> private string GenerateBinaryExpression(BinaryExpression be) { string retstr = String.Empty; if (be.ExpressionSymbol.Equals("&&") || be.ExpressionSymbol.Equals("||")) { // special case handling for logical and/or, see Mantis 3174 retstr += "((bool)("; retstr += GenerateNode(be, (SYMBOL)be.kids.Pop()); retstr += "))"; retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol.Substring(0,1)), be); retstr += "((bool)("; foreach (SYMBOL kid in be.kids) retstr += GenerateNode(be, kid); retstr += "))"; } else { retstr += GenerateNode(be, (SYMBOL)be.kids.Pop()); retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol), be); foreach (SYMBOL kid in be.kids) retstr += GenerateNode(be, kid); } return retstr; } /// <summary> /// Generates the code for a UnaryExpression node. /// </summary> /// <param name="ue">The UnaryExpression node.</param> /// <returns>String containing C# code for UnaryExpression ue.</returns> private string GenerateUnaryExpression(UnaryExpression ue) { string retstr = String.Empty; retstr += Generate(ue.UnarySymbol, ue); retstr += GenerateNode(ue, (SYMBOL) ue.kids.Pop()); return retstr; } /// <summary> /// Generates the code for a ParenthesisExpression node. /// </summary> /// <param name="pe">The ParenthesisExpression node.</param> /// <returns>String containing C# code for ParenthesisExpression pe.</returns> private string GenerateParenthesisExpression(ParenthesisExpression pe) { string retstr = String.Empty; retstr += Generate("("); foreach (SYMBOL kid in pe.kids) retstr += GenerateNode(pe, kid); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a IncrementDecrementExpression node. /// </summary> /// <param name="ide">The IncrementDecrementExpression node.</param> /// <returns>String containing C# code for IncrementDecrementExpression ide.</returns> private string GenerateIncrementDecrementExpression(IncrementDecrementExpression ide) { string retstr = String.Empty; if (0 < ide.kids.Count) { IdentDotExpression dot = (IdentDotExpression) ide.kids.Top; retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(dot.Name) + "." + dot.Member + ide.Operation : ide.Operation + CheckName(dot.Name) + "." + dot.Member), ide); } else retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(ide.Name) + ide.Operation : ide.Operation + CheckName(ide.Name)), ide); return retstr; } /// <summary> /// Generates the code for a TypecastExpression node. /// </summary> /// <param name="te">The TypecastExpression node.</param> /// <returns>String containing C# code for TypecastExpression te.</returns> private string GenerateTypecastExpression(TypecastExpression te) { string retstr = String.Empty; // we wrap all typecasted statements in parentheses retstr += Generate(String.Format("({0}) (", te.TypecastType), te); retstr += GenerateNode(te, (SYMBOL) te.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for an identifier /// </summary> /// <param name="id">The symbol name</param> /// <param name="s">The Symbol node.</param> /// <returns>String containing C# code for identifier reference.</returns> private string GenerateIdentifier(string id, SYMBOL s) { if (m_comms != null) { object value = m_comms.LookupModConstant(id); if (value != null) { string retval = null; if (value is int) retval = ((int)value).ToString(); else if (value is float) retval = String.Format("new LSL_Types.LSLFloat({0})",((float)value).ToString()); else if (value is string) retval = String.Format("new LSL_Types.LSLString(\"{0}\")",((string)value)); else if (value is OpenMetaverse.UUID) retval = String.Format("new LSL_Types.key(\"{0}\")",((OpenMetaverse.UUID)value).ToString()); else if (value is OpenMetaverse.Vector3) retval = String.Format("new LSL_Types.Vector3(\"{0}\")",((OpenMetaverse.Vector3)value).ToString()); else if (value is OpenMetaverse.Quaternion) retval = String.Format("new LSL_Types.Quaternion(\"{0}\")",((OpenMetaverse.Quaternion)value).ToString()); else retval = id; return Generate(retval, s); } } return Generate(CheckName(id), s); } /// <summary> /// Generates the code for a FunctionCall node. /// </summary> /// <param name="fc">The FunctionCall node.</param> /// <returns>String containing C# code for FunctionCall fc.</returns> private string GenerateFunctionCall(FunctionCall fc) { string retstr = String.Empty; string modinvoke = null; if (m_comms != null) modinvoke = m_comms.LookupModInvocation(fc.Id); if (modinvoke != null) { if (fc.kids[0] is ArgumentList) { if ((fc.kids[0] as ArgumentList).kids.Count == 0) retstr += Generate(String.Format("{0}(\"{1}\"",modinvoke,fc.Id), fc); else retstr += Generate(String.Format("{0}(\"{1}\",",modinvoke,fc.Id), fc); } } else { retstr += Generate(String.Format("{0}(", CheckName(fc.Id)), fc); } foreach (SYMBOL kid in fc.kids) retstr += GenerateNode(fc, kid); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a Constant node. /// </summary> /// <param name="c">The Constant node.</param> /// <returns>String containing C# code for Constant c.</returns> private string GenerateConstant(Constant c) { string retstr = String.Empty; // Supprt LSL's weird acceptance of floats with no trailing digits // after the period. Turn float x = 10.; into float x = 10.0; if ("LSL_Types.LSLFloat" == c.Type) { int dotIndex = c.Value.IndexOf('.') + 1; if (0 < dotIndex && (dotIndex == c.Value.Length || !Char.IsDigit(c.Value[dotIndex]))) c.Value = c.Value.Insert(dotIndex, "0"); c.Value = "new LSL_Types.LSLFloat("+c.Value+")"; } else if ("LSL_Types.LSLInteger" == c.Type) { c.Value = "new LSL_Types.LSLInteger("+c.Value+")"; } else if ("LSL_Types.LSLString" == c.Type) { c.Value = "new LSL_Types.LSLString(\""+c.Value+"\")"; } retstr += Generate(c.Value, c); return retstr; } /// <summary> /// Generates the code for a VectorConstant node. /// </summary> /// <param name="vc">The VectorConstant node.</param> /// <returns>String containing C# code for VectorConstant vc.</returns> private string GenerateVectorConstant(VectorConstant vc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", vc.Type), vc); retstr += GenerateNode(vc, (SYMBOL) vc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(vc, (SYMBOL) vc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(vc, (SYMBOL) vc.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a RotationConstant node. /// </summary> /// <param name="rc">The RotationConstant node.</param> /// <returns>String containing C# code for RotationConstant rc.</returns> private string GenerateRotationConstant(RotationConstant rc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", rc.Type), rc); retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a ListConstant node. /// </summary> /// <param name="lc">The ListConstant node.</param> /// <returns>String containing C# code for ListConstant lc.</returns> private string GenerateListConstant(ListConstant lc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", lc.Type), lc); foreach (SYMBOL kid in lc.kids) retstr += GenerateNode(lc, kid); retstr += Generate(")"); return retstr; } /// <summary> /// Prints a newline. /// </summary> /// <returns>A newline.</returns> private string GenerateLine() { return GenerateLine(""); } /// <summary> /// Prints text, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>String s followed by newline.</returns> private string GenerateLine(string s) { return GenerateLine(s, null); } /// <summary> /// Prints text, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>String s followed by newline.</returns> private string GenerateLine(string s, SYMBOL sym) { string retstr = Generate(s, sym) + "\n"; m_CSharpLine++; m_CSharpCol = 1; return retstr; } /// <summary> /// Prints text. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>String s.</returns> private string Generate(string s) { return Generate(s, null); } /// <summary> /// Prints text. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>String s.</returns> private string Generate(string s, SYMBOL sym) { if (null != sym) m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position)); m_CSharpCol += s.Length; return s; } /// <summary> /// Prints text correctly indented, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>Properly indented string s followed by newline.</returns> private string GenerateIndentedLine(string s) { return GenerateIndentedLine(s, null); } /// <summary> /// Prints text correctly indented, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>Properly indented string s followed by newline.</returns> private string GenerateIndentedLine(string s, SYMBOL sym) { string retstr = GenerateIndented(s, sym) + "\n"; m_CSharpLine++; m_CSharpCol = 1; return retstr; } /// <summary> /// Prints text correctly indented. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>Properly indented string s.</returns> //private string GenerateIndented(string s) //{ // return GenerateIndented(s, null); //} // THIS FUNCTION IS COMMENTED OUT TO SUPPRESS WARNINGS /// <summary> /// Prints text correctly indented. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>Properly indented string s.</returns> private string GenerateIndented(string s, SYMBOL sym) { string retstr = Indent() + s; if (null != sym) m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position)); m_CSharpCol += s.Length; return retstr; } /// <summary> /// Prints correct indentation. /// </summary> /// <returns>Indentation based on brace count.</returns> private string Indent() { string retstr = String.Empty; for (int i = 0; i < m_braceCount; i++) for (int j = 0; j < m_indentWidth; j++) { retstr += " "; m_CSharpCol++; } return retstr; } /// <summary> /// Returns the passed name with an underscore prepended if that name is a reserved word in C# /// and not resevered in LSL otherwise it just returns the passed name. /// /// This makes no attempt to cache the results to minimise future lookups. For a non trivial /// scripts the number of unique identifiers could easily grow to the size of the reserved word /// list so maintaining a list or dictionary and doing the lookup there firstwould probably not /// give any real speed advantage. /// /// I believe there is a class Microsoft.CSharp.CSharpCodeProvider that has a function /// CreateValidIdentifier(str) that will return either the value of str if it is not a C# /// key word or "_"+str if it is. But availability under Mono? /// </summary> private string CheckName(string s) { if (CSReservedWords.IsReservedWord(s)) return "@" + s; else return s; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Runtime.Diagnostics; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public abstract class TransportDuplexSessionChannel : TransportOutputChannel, IDuplexSessionChannel { private BufferManager _bufferManager; private IDuplexSession _duplexSession; private bool _isInputSessionClosed; private bool _isOutputSessionClosed; private MessageEncoder _messageEncoder; private SynchronizedMessageSource _messageSource; private SecurityMessageProperty _remoteSecurity; private EndpointAddress _localAddress; private SemaphoreSlim _sendLock; private Uri _localVia; private static Action<object> s_onWriteComplete = new Action<object>(OnWriteComplete); protected TransportDuplexSessionChannel( ChannelManagerBase manager, ITransportFactorySettings settings, EndpointAddress localAddress, Uri localVia, EndpointAddress remoteAddress, Uri via) : base(manager, remoteAddress, via, settings.ManualAddressing, settings.MessageVersion) { _localAddress = localAddress; _localVia = localVia; _bufferManager = settings.BufferManager; _sendLock = new SemaphoreSlim(1); _messageEncoder = settings.MessageEncoderFactory.CreateSessionEncoder(); this.Session = new ConnectionDuplexSession(this); } public EndpointAddress LocalAddress { get { return _localAddress; } } public SecurityMessageProperty RemoteSecurity { get { return _remoteSecurity; } protected set { _remoteSecurity = value; } } public IDuplexSession Session { get { return _duplexSession; } protected set { _duplexSession = value; } } protected SemaphoreSlim SendLock { get { return _sendLock; } } protected BufferManager BufferManager { get { return _bufferManager; } } protected MessageEncoder MessageEncoder { get { return _messageEncoder; } set { _messageEncoder = value; } } internal SynchronizedMessageSource MessageSource { get { return _messageSource; } } protected abstract bool IsStreamedOutput { get; } public Message Receive() { return this.Receive(this.DefaultReceiveTimeout); } public Message Receive(TimeSpan timeout) { Message message = null; if (DoneReceivingInCurrentState()) { return null; } bool shouldFault = true; try { message = _messageSource.Receive(timeout); this.OnReceiveMessage(message); shouldFault = false; return message; } finally { if (shouldFault) { if (message != null) { message.Close(); message = null; } this.Fault(); } } } public async Task<Message> ReceiveAsync(TimeSpan timeout) { Message message = null; if (DoneReceivingInCurrentState()) { return null; } bool shouldFault = true; try { message = await _messageSource.ReceiveAsync(timeout); this.OnReceiveMessage(message); shouldFault = false; return message; } finally { if (shouldFault) { if (message != null) { message.Close(); message = null; } this.Fault(); } } } public IAsyncResult BeginReceive(AsyncCallback callback, object state) { return this.BeginReceive(this.DefaultReceiveTimeout, callback, state); } public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state) { return this.ReceiveAsync(timeout).ToApm(callback, state); } public Message EndReceive(IAsyncResult result) { return result.ToApmEnd<Message>(); } public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state) { return this.ReceiveAsync(timeout).ToApm(callback, state); } public bool EndTryReceive(IAsyncResult result, out Message message) { try { message = result.ToApmEnd<Message>(); return true; } catch (TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } message = null; return false; } } public bool TryReceive(TimeSpan timeout, out Message message) { try { message = this.Receive(timeout); return true; } catch (TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } message = null; return false; } } public async Task<bool> WaitForMessageAsync(TimeSpan timeout) { if (DoneReceivingInCurrentState()) { return true; } bool shouldFault = true; try { bool success = await _messageSource.WaitForMessageAsync(timeout); shouldFault = !success; // need to fault if we've timed out because we're now toast return success; } finally { if (shouldFault) { this.Fault(); } } } public bool WaitForMessage(TimeSpan timeout) { if (DoneReceivingInCurrentState()) { return true; } bool shouldFault = true; try { bool success = _messageSource.WaitForMessage(timeout); shouldFault = !success; // need to fault if we've timed out because we're now toast return success; } finally { if (shouldFault) { this.Fault(); } } } public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state) { return this.WaitForMessageAsync(timeout).ToApm(callback, state); } public bool EndWaitForMessage(IAsyncResult result) { return result.ToApmEnd<bool>(); } protected void SetMessageSource(IMessageSource messageSource) { _messageSource = new SynchronizedMessageSource(messageSource); } protected abstract Task CloseOutputSessionCoreAsync(TimeSpan timeout); protected abstract void CloseOutputSessionCore(TimeSpan timeout); protected async Task CloseOutputSessionAsync(TimeSpan timeout) { ThrowIfNotOpened(); ThrowIfFaulted(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!await _sendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout))) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(SR.Format(SR.CloseTimedOut, timeout)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.CloseTimedOut, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } try { // check again in case the previous send faulted while we were waiting for the lock ThrowIfFaulted(); // we're synchronized by sendLock here if (_isOutputSessionClosed) { return; } _isOutputSessionClosed = true; bool shouldFault = true; try { await this.CloseOutputSessionCoreAsync(timeout); this.OnOutputSessionClosed(ref timeoutHelper); shouldFault = false; } finally { if (shouldFault) { this.Fault(); } } } finally { _sendLock.Release(); } } protected void CloseOutputSession(TimeSpan timeout) { ThrowIfNotOpened(); ThrowIfFaulted(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!_sendLock.Wait(TimeoutHelper.ToMilliseconds(timeout))) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(SR.Format(SR.CloseTimedOut, timeout)); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.CloseTimedOut, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } try { // check again in case the previous send faulted while we were waiting for the lock ThrowIfFaulted(); // we're synchronized by sendLock here if (_isOutputSessionClosed) { return; } _isOutputSessionClosed = true; bool shouldFault = true; try { this.CloseOutputSessionCore(timeout); this.OnOutputSessionClosed(ref timeoutHelper); shouldFault = false; } finally { if (shouldFault) { this.Fault(); } } } finally { _sendLock.Release(); } } // used to return cached connection to the pool/reader pool protected abstract void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout); protected override void OnAbort() { this.ReturnConnectionIfNecessary(true, TimeSpan.Zero); } protected override void OnFaulted() { base.OnFaulted(); this.ReturnConnectionIfNecessary(true, TimeSpan.Zero); } protected internal override async Task OnCloseAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await this.CloseOutputSessionAsync(timeoutHelper.RemainingTime()); // close input session if necessary if (!_isInputSessionClosed) { await this.EnsureInputClosedAsync(timeoutHelper.RemainingTime()); this.OnInputSessionClosed(); } this.CompleteClose(timeoutHelper.RemainingTime()); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.CloseOutputSession(timeoutHelper.RemainingTime()); // close input session if necessary if (!_isInputSessionClosed) { this.EnsureInputClosed(timeoutHelper.RemainingTime()); this.OnInputSessionClosed(); } this.CompleteClose(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return OnCloseAsync(timeout).ToApm(callback, state); } protected override void OnEndClose(IAsyncResult result) { result.ToApmEnd(); } protected override void OnClosed() { base.OnClosed(); // clean up the CBT after transitioning to the closed state //ChannelBindingUtility.Dispose(ref this.channelBindingToken); } protected virtual void OnReceiveMessage(Message message) { if (message == null) { this.OnInputSessionClosed(); } else { this.PrepareMessage(message); } } protected void ApplyChannelBinding(Message message) { //ChannelBindingUtility.TryAddToMessage(this.channelBindingToken, message, false); } protected virtual void PrepareMessage(Message message) { message.Properties.Via = _localVia; this.ApplyChannelBinding(message); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); Guid relatedActivityId = EventTraceActivity.GetActivityIdFromThread(); if (eventTraceActivity == null) { eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); EventTraceActivityHelper.TryAttachActivity(message, eventTraceActivity); } if (WcfEventSource.Instance.MessageReceivedByTransportIsEnabled()) { WcfEventSource.Instance.MessageReceivedByTransport( eventTraceActivity, this.LocalAddress != null && this.LocalAddress.Uri != null ? this.LocalAddress.Uri.AbsoluteUri : string.Empty, relatedActivityId); } } } protected abstract AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment<byte> messageData, bool allowOutputBatching, TimeSpan timeout, Action<object> callback, object state); protected abstract AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, Action<object> callback, object state); protected virtual void FinishWritingMessage() { } protected abstract ArraySegment<byte> EncodeMessage(Message message); protected abstract void OnSendCore(Message message, TimeSpan timeout); protected abstract AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, Action<object> callback, object state); protected override async Task OnSendAsync(Message message, TimeSpan timeout) { this.ThrowIfDisposedOrNotOpen(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!await _sendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SendToViaTimedOut, Via, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } byte[] buffer = null; try { // check again in case the previous send faulted while we were waiting for the lock this.ThrowIfDisposedOrNotOpen(); this.ThrowIfOutputSessionClosed(); bool success = false; try { this.ApplyChannelBinding(message); var tcs = new TaskCompletionSource<bool>(this); AsyncCompletionResult completionResult; if (this.IsStreamedOutput) { completionResult = this.StartWritingStreamedMessage(message, timeoutHelper.RemainingTime(), s_onWriteComplete, tcs); } else { bool allowOutputBatching; ArraySegment<byte> messageData; allowOutputBatching = message.Properties.AllowOutputBatching; messageData = this.EncodeMessage(message); buffer = messageData.Array; completionResult = this.StartWritingBufferedMessage( message, messageData, allowOutputBatching, timeoutHelper.RemainingTime(), s_onWriteComplete, tcs); } if (completionResult == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; this.FinishWritingMessage(); success = true; if (WcfEventSource.Instance.MessageSentByTransportIsEnabled()) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); WcfEventSource.Instance.MessageSentByTransport(eventTraceActivity, this.RemoteAddress.Uri.AbsoluteUri); } } finally { if (!success) { this.Fault(); } } } finally { _sendLock.Release(); } if (buffer != null) { _bufferManager.ReturnBuffer(buffer); } } private static void OnWriteComplete(object state) { if (state == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state"); } var tcs = state as TaskCompletionSource<bool>; if (tcs == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult); } tcs.TrySetResult(true); } protected override void OnSend(Message message, TimeSpan timeout) { this.ThrowIfDisposedOrNotOpen(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue. // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue // and would result in the value Int32.MaxValue so we must use the original timeout specified. if (!_sendLock.Wait(TimeoutHelper.ToMilliseconds(timeout))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SendToViaTimedOut, Via, timeout), TimeoutHelper.CreateEnterTimedOutException(timeout))); } try { // check again in case the previous send faulted while we were waiting for the lock this.ThrowIfDisposedOrNotOpen(); this.ThrowIfOutputSessionClosed(); bool success = false; try { this.ApplyChannelBinding(message); this.OnSendCore(message, timeoutHelper.RemainingTime()); success = true; if (WcfEventSource.Instance.MessageSentByTransportIsEnabled()) { EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); WcfEventSource.Instance.MessageSentByTransport(eventTraceActivity, this.RemoteAddress.Uri.AbsoluteUri); } } finally { if (!success) { this.Fault(); } } } finally { _sendLock.Release(); } } // cleanup after the framing handshake has completed protected abstract void CompleteClose(TimeSpan timeout); // must be called under sendLock private void ThrowIfOutputSessionClosed() { if (_isOutputSessionClosed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SendCannotBeCalledAfterCloseOutputSession)); } } private async Task EnsureInputClosedAsync(TimeSpan timeout) { Message message = await this.MessageSource.ReceiveAsync(timeout); if (message != null) { using (message) { ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message); throw TraceUtility.ThrowHelperError(error, message); } } } private void EnsureInputClosed(TimeSpan timeout) { Message message = this.MessageSource.Receive(timeout); if (message != null) { using (message) { ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message); throw TraceUtility.ThrowHelperError(error, message); } } } private void OnInputSessionClosed() { lock (ThisLock) { if (_isInputSessionClosed) { return; } _isInputSessionClosed = true; } } private void OnOutputSessionClosed(ref TimeoutHelper timeoutHelper) { bool releaseConnection = false; lock (ThisLock) { if (_isInputSessionClosed) { // we're all done, release the connection releaseConnection = true; } } if (releaseConnection) { this.ReturnConnectionIfNecessary(false, timeoutHelper.RemainingTime()); } } public class ConnectionDuplexSession : IDuplexSession { private static UriGenerator s_uriGenerator; private TransportDuplexSessionChannel _channel; private string _id; public ConnectionDuplexSession(TransportDuplexSessionChannel channel) : base() { _channel = channel; } public string Id { get { if (_id == null) { lock (_channel) { if (_id == null) { _id = UriGenerator.Next(); } } } return _id; } } public TransportDuplexSessionChannel Channel { get { return _channel; } } private static UriGenerator UriGenerator { get { if (s_uriGenerator == null) { s_uriGenerator = new UriGenerator(); } return s_uriGenerator; } } public IAsyncResult BeginCloseOutputSession(AsyncCallback callback, object state) { return this.BeginCloseOutputSession(_channel.DefaultCloseTimeout, callback, state); } public IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state) { return _channel.CloseOutputSessionAsync(timeout).ToApm(callback, state); } public void EndCloseOutputSession(IAsyncResult result) { result.ToApmEnd(); } public void CloseOutputSession() { this.CloseOutputSession(_channel.DefaultCloseTimeout); } public void CloseOutputSession(TimeSpan timeout) { _channel.CloseOutputSession(timeout); } } } }
/* * 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.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using CSJ2K; using Nini.Config; using log4net; using Rednettle.Warp3D; using Mono.Addins; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.Imaging; using OpenMetaverse.Rendering; using OpenMetaverse.StructuredData; using WarpRenderer = global::Warp3D.Warp3D; namespace OpenSim.Region.CoreModules.World.Warp3DMap { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")] public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule { private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3"); private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static string LogHeader = "[WARP 3D IMAGE MODULE]"; #pragma warning restore 414 private Scene m_scene; private IRendering m_primMesher; private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>(); private IConfigSource m_config; private bool m_drawPrimVolume = true; // true if should render the prims on the tile private bool m_textureTerrain = true; // true if to create terrain splatting texture private bool m_texturePrims = true; // true if should texture the rendered prims private float m_texturePrimSize = 48f; // size of prim before we consider texturing it private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes private bool m_useAntiAliasing = false; // true if to anti-alias the rendered image private bool m_Enabled = false; private Bitmap lastImage = null; private DateTime lastImageTime = DateTime.MinValue; #region Region Module interface public void Initialise(IConfigSource source) { m_config = source; string[] configSections = new string[] { "Map", "Startup" }; if (Util.GetConfigVarFromSections<string>( m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule") return; m_Enabled = true; m_drawPrimVolume = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume); m_textureTerrain = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain); m_texturePrims = Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims); m_texturePrimSize = Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize); m_renderMeshes = Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes); m_useAntiAliasing = Util.GetConfigVarFromSections<bool>(m_config, "UseAntiAliasing", configSections, m_useAntiAliasing); } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_scene = scene; List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); if (renderers.Count > 0) m_log.Info("[MAPTILE]: Loaded prim mesher " + renderers[0]); else m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled"); m_scene.RegisterModuleInterface<IMapImageGenerator>(this); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "Warp3DImageModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region IMapImageGenerator Members public Bitmap CreateMapTile() { /* this must be on all map, not just its image if ((DateTime.Now - lastImageTime).TotalSeconds < 3600) { return (Bitmap)lastImage.Clone(); } */ List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); if (renderers.Count > 0) { m_primMesher = RenderingLoader.LoadRenderer(renderers[0]); } Vector3 camPos = new Vector3( m_scene.RegionInfo.RegionSizeX / 2 - 0.5f, m_scene.RegionInfo.RegionSizeY / 2 - 0.5f, 221.7025033688163f); // Viewport viewing down onto the region Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY, (float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY); Bitmap tile = CreateMapTile(viewport, false); m_primMesher = null; return tile; /* lastImage = tile; lastImageTime = DateTime.Now; return (Bitmap)lastImage.Clone(); */ } public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures) { Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height); return CreateMapTile(viewport, useTextures); } public Bitmap CreateMapTile(Viewport viewport, bool useTextures) { m_colors.Clear(); int width = viewport.Width; int height = viewport.Height; if (m_useAntiAliasing) { width *= 2; height *= 2; } WarpRenderer renderer = new WarpRenderer(); renderer.CreateScene(width, height); renderer.Scene.autoCalcNormals = false; #region Camera warp_Vector pos = ConvertVector(viewport.Position); pos.z -= 0.001f; // Works around an issue with the Warp3D camera warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection)); renderer.Scene.defaultCamera.setPos(pos); renderer.Scene.defaultCamera.lookAt(lookat); if (viewport.Orthographic) { renderer.Scene.defaultCamera.isOrthographic = true; renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth; renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight; } else { float fov = viewport.FieldOfView; fov *= 1.75f; // FIXME: ??? renderer.Scene.defaultCamera.setFov(fov); } #endregion Camera renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40)); renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40)); CreateWater(renderer); CreateTerrain(renderer, m_textureTerrain); if (m_drawPrimVolume) CreateAllPrims(renderer, useTextures); renderer.Render(); Bitmap bitmap = renderer.Scene.getImage(); if (m_useAntiAliasing) { using (Bitmap origBitmap = bitmap) bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height); } // XXX: It shouldn't really be necesary to force a GC here as one should occur anyway pretty shortly // afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory // then this may be some issue with the Warp3D code itself, though it's also quite possible that generating // this map tile simply takes a lot of memory. foreach (var o in renderer.Scene.objectData.Values) { warp_Object obj = (warp_Object)o; obj.vertexData = null; obj.triangleData = null; } renderer.Scene.removeAllObjects(); renderer = null; viewport = null; m_colors.Clear(); GC.Collect(); m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()"); return bitmap; } public byte[] WriteJpeg2000Image() { try { using (Bitmap mapbmp = CreateMapTile()) return OpenJPEG.EncodeFromImage(mapbmp, true); } catch (Exception e) { // JPEG2000 encoder failed m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e); } return null; } #endregion #region Rendering Methods // Add a water plane to the renderer. private void CreateWater(WarpRenderer renderer) { float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f); renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX / 2 - 0.5f, waterHeight, m_scene.RegionInfo.RegionSizeY / 2 - 0.5f); warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR)); waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f)); renderer.Scene.addMaterial("WaterColor", waterColorMaterial); renderer.SetObjectMaterial("Water", "WaterColor"); } // Add a terrain to the renderer. // Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for // full resolution. This saves a lot of memory especially for very large regions. private void CreateTerrain(WarpRenderer renderer, bool textureTerrain) { ITerrainChannel terrain = m_scene.Heightmap; // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding float diff = (float)m_scene.RegionInfo.RegionSizeX / 256f; warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2); // Create all the vertices for the terrain for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff) { for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff) { warp_Vector pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]); obj.addVertex(new warp_Vertex(pos, x / (float)m_scene.RegionInfo.RegionSizeX, (((float)m_scene.RegionInfo.RegionSizeY) - y) / m_scene.RegionInfo.RegionSizeY)); } } // Now that we have all the vertices, make another pass and create // the normals for each of the surface triangles and // create the list of triangle indices. for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff) { for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff) { float newX = x / diff; float newY = y / diff; if (newX < 255 && newY < 255) { int v = (int)newY * 256 + (int)newX; // Normal for a triangle made up of three adjacent vertices Vector3 v1 = new Vector3(newX, newY, (float)terrain[(int)x, (int)y]); Vector3 v2 = new Vector3(newX + 1, newY, (float)terrain[(int)(x + 1), (int)y]); Vector3 v3 = new Vector3(newX, newY + 1, (float)terrain[(int)x, ((int)(y + 1))]); warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3)); norm = norm.reverse(); obj.vertex(v).n = norm; // Make two triangles for each of the squares in the grid of vertices obj.addTriangle( v, v + 1, v + 256); obj.addTriangle( v + 256 + 1, v + 256, v + 1); } } } renderer.Scene.addObject("Terrain", obj); UUID[] textureIDs = new UUID[4]; float[] startHeights = new float[4]; float[] heightRanges = new float[4]; OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings; textureIDs[0] = regionInfo.TerrainTexture1; textureIDs[1] = regionInfo.TerrainTexture2; textureIDs[2] = regionInfo.TerrainTexture3; textureIDs[3] = regionInfo.TerrainTexture4; startHeights[0] = (float)regionInfo.Elevation1SW; startHeights[1] = (float)regionInfo.Elevation1NW; startHeights[2] = (float)regionInfo.Elevation1SE; startHeights[3] = (float)regionInfo.Elevation1NE; heightRanges[0] = (float)regionInfo.Elevation2SW; heightRanges[1] = (float)regionInfo.Elevation2NW; heightRanges[2] = (float)regionInfo.Elevation2SE; heightRanges[3] = (float)regionInfo.Elevation2NE; uint globalX, globalY; Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY); warp_Texture texture; using ( Bitmap image = TerrainSplat.Splat( terrain, textureIDs, startHeights, heightRanges, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain)) { texture = new warp_Texture(image); } warp_Material material = new warp_Material(texture); material.setReflectivity(50); renderer.Scene.addMaterial("TerrainColor", material); renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif renderer.SetObjectMaterial("Terrain", "TerrainColor"); } private void CreateAllPrims(WarpRenderer renderer, bool useTextures) { if (m_primMesher == null) return; m_scene.ForEachSOG( delegate(SceneObjectGroup group) { foreach (SceneObjectPart child in group.Parts) CreatePrim(renderer, child, useTextures); } ); } private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim, bool useTextures) { const float MIN_SIZE = 2f; if ((PCode)prim.Shape.PCode != PCode.Prim) return; if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE) return; FacetedMesh renderMesh = null; Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset); if (m_renderMeshes) { if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero) { // Try fetchinng the asset byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString()); if (sculptAsset != null) { // Is it a mesh? if (omvPrim.Sculpt.Type == SculptType.Mesh) { AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset); FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh); meshAsset = null; } else // It's sculptie { IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>(); if (imgDecoder != null) { Image sculpt = imgDecoder.DecodeToImage(sculptAsset); if (sculpt != null) { renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, DetailLevel.Medium); sculpt.Dispose(); } } } } } } // If not a mesh or sculptie, try the regular mesher if (renderMesh == null) { renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium); } if (renderMesh == null) return; warp_Vector primPos = ConvertVector(prim.GetWorldPosition()); warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset); warp_Matrix m = warp_Matrix.quaternionMatrix(primRot); if (prim.ParentID != 0) { SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId); if (group != null) m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset))); } warp_Vector primScale = ConvertVector(prim.Scale); string primID = prim.UUID.ToString(); // Create the prim faces // TODO: Implement the useTextures flag behavior for (int i = 0; i < renderMesh.Faces.Count; i++) { Face face = renderMesh.Faces[i]; string meshName = primID + "-Face-" + i.ToString(); // Avoid adding duplicate meshes to the scene if (renderer.Scene.objectData.ContainsKey(meshName)) { continue; } warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3); for (int j = 0; j < face.Vertices.Count; j++) { Vertex v = face.Vertices[j]; warp_Vector pos = ConvertVector(v.Position); warp_Vector norm = ConvertVector(v.Normal); if (prim.Shape.SculptTexture == UUID.Zero) norm = norm.reverse(); warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y); faceObj.addVertex(vert); } for (int j = 0; j < face.Indices.Count; j += 3) { faceObj.addTriangle( face.Indices[j + 0], face.Indices[j + 1], face.Indices[j + 2]); } Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i); Color4 faceColor = GetFaceColor(teFace); string materialName = String.Empty; if (m_texturePrims && prim.Scale.LengthSquared() > m_texturePrimSize*m_texturePrimSize) materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID); else materialName = GetOrCreateMaterial(renderer, faceColor); faceObj.transform(m); faceObj.setPos(primPos); faceObj.scaleSelf(primScale.x, primScale.y, primScale.z); renderer.Scene.addObject(meshName, faceObj); renderer.SetObjectMaterial(meshName, materialName); } } private Color4 GetFaceColor(Primitive.TextureEntryFace face) { Color4 color; if (face.TextureID == UUID.Zero) return face.RGBA; if (!m_colors.TryGetValue(face.TextureID, out color)) { bool fetched = false; // Attempt to fetch the texture metadata UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC); AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString()); if (metadata != null) { OSDMap map = null; try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { } if (map != null) { color = map["X-JPEG2000-RGBA"].AsColor4(); fetched = true; } } if (!fetched) { // Fetch the texture, decode and get the average color, // then save it to a temporary metadata asset AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString()); if (textureAsset != null) { int width, height; color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } }; metadata = new AssetBase { Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(), Flags = AssetFlags.Collectable, FullID = metadataID, ID = metadataID.ToString(), Local = true, Temporary = true, Name = String.Empty, Type = (sbyte)AssetType.Unknown }; m_scene.AssetService.Store(metadata); } else { color = new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } m_colors[face.TextureID] = color; } return color * face.RGBA; } private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color) { string name = color.ToString(); warp_Material material = renderer.Scene.material(name); if (material != null) return name; renderer.AddMaterial(name, ConvertColor(color)); if (color.A < 1f) renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f)); return name; } public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID) { string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString(); if (renderer.Scene.material(materialName) == null) { renderer.AddMaterial(materialName, ConvertColor(faceColor)); if (faceColor.A < 1f) { renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f)); } warp_Texture texture = GetTexture(textureID); if (texture != null) renderer.Scene.material(materialName).setTexture(texture); } return materialName; } private warp_Texture GetTexture(UUID id) { warp_Texture ret = null; byte[] asset = m_scene.AssetService.GetData(id.ToString()); if (asset != null) { IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>(); try { using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset)) ret = new warp_Texture(img); } catch (Exception e) { m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e); } } return ret; } #endregion Rendering Methods #region Static Helpers // Note: axis change. private static warp_Vector ConvertVector(float x, float y, float z) { return new warp_Vector(x, z, y); } private static warp_Vector ConvertVector(Vector3 vector) { return new warp_Vector(vector.X, vector.Z, vector.Y); } private static warp_Quaternion ConvertQuaternion(Quaternion quat) { return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W); } private static int ConvertColor(Color4 color) { int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f)); if (color.A < 1f) c |= (byte)(color.A * 255f) << 24; return c; } private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3) { Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z); Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z); Vector3 normal = Vector3.Cross(edge1, edge2); normal.Normalize(); return normal; } public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height) { ulong r = 0; ulong g = 0; ulong b = 0; ulong a = 0; using (MemoryStream stream = new MemoryStream(j2kData)) { try { int pixelBytes; using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream)) { width = bitmap.Width; height = bitmap.Height; BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat); pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4; // Sum up the individual channels unsafe { if (pixelBytes == 4) { for (int y = 0; y < height; y++) { byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < width; x++) { b += row[x * pixelBytes + 0]; g += row[x * pixelBytes + 1]; r += row[x * pixelBytes + 2]; a += row[x * pixelBytes + 3]; } } } else { for (int y = 0; y < height; y++) { byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < width; x++) { b += row[x * pixelBytes + 0]; g += row[x * pixelBytes + 1]; r += row[x * pixelBytes + 2]; } } } } } // Get the averages for each channel const decimal OO_255 = 1m / 255m; decimal totalPixels = (decimal)(width * height); decimal rm = ((decimal)r / totalPixels) * OO_255; decimal gm = ((decimal)g / totalPixels) * OO_255; decimal bm = ((decimal)b / totalPixels) * OO_255; decimal am = ((decimal)a / totalPixels) * OO_255; if (pixelBytes == 3) am = 1m; return new Color4((float)rm, (float)gm, (float)bm, (float)am); } catch (Exception ex) { m_log.WarnFormat( "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", textureID, j2kData.Length, ex.Message); width = 0; height = 0; return new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } } #endregion Static Helpers } public static class ImageUtils { /// <summary> /// Performs bilinear interpolation between four values /// </summary> /// <param name="v00">First, or top left value</param> /// <param name="v01">Second, or top right value</param> /// <param name="v10">Third, or bottom left value</param> /// <param name="v11">Fourth, or bottom right value</param> /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param> /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param> /// <returns>The bilinearly interpolated result</returns> public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent) { return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent); } /// <summary> /// Performs a high quality image resize /// </summary> /// <param name="image">Image to resize</param> /// <param name="width">New width</param> /// <param name="height">New height</param> /// <returns>Resized image</returns> public static Bitmap ResizeImage(Image image, int width, int height) { Bitmap result = new Bitmap(width, height); using (Graphics graphics = Graphics.FromImage(result)) { graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphics.DrawImage(image, 0, 0, result.Width, result.Height); } return result; } } }
// 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.Globalization; using System.Runtime.Serialization; namespace System.Data { public class InvalidExpressionException : DataException { protected InvalidExpressionException(SerializationInfo info, StreamingContext context) : base(info, context) { } public InvalidExpressionException() : base() { } public InvalidExpressionException(string s) : base(s) { } public InvalidExpressionException(string message, Exception innerException) : base(message, innerException) { } } public class EvaluateException : InvalidExpressionException { protected EvaluateException(SerializationInfo info, StreamingContext context) : base(info, context) { } public EvaluateException() : base() { } public EvaluateException(string s) : base(s) { } public EvaluateException(string message, Exception innerException) : base(message, innerException) { } } public class SyntaxErrorException : InvalidExpressionException { protected SyntaxErrorException(SerializationInfo info, StreamingContext context) : base(info, context) { } public SyntaxErrorException() : base() { } public SyntaxErrorException(string s) : base(s) { } public SyntaxErrorException(string message, Exception innerException) : base(message, innerException) { } } internal sealed class ExprException { private ExprException() { /* prevent utility class from being insantiated*/ } private static OverflowException _Overflow(string error) { OverflowException e = new OverflowException(error); ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } private static InvalidExpressionException _Expr(string error) { InvalidExpressionException e = new InvalidExpressionException(error); ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } private static SyntaxErrorException _Syntax(string error) { SyntaxErrorException e = new SyntaxErrorException(error); ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } private static EvaluateException _Eval(string error) { EvaluateException e = new EvaluateException(error); ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } private static EvaluateException _Eval(string error, Exception innerException) { EvaluateException e = new EvaluateException(error/*, innerException*/); ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } public static Exception InvokeArgument() { return ExceptionBuilder._Argument(SR.Expr_InvokeArgument); } public static Exception NYI(string moreinfo) { string err = SR.Format(SR.Expr_NYI, moreinfo); Debug.Fail(err); return _Expr(err); } public static Exception MissingOperand(OperatorInfo before) { return _Syntax(SR.Format(SR.Expr_MissingOperand, Operators.ToString(before._op))); } public static Exception MissingOperator(string token) { return _Syntax(SR.Format(SR.Expr_MissingOperand, token)); } public static Exception TypeMismatch(string expr) { return _Eval(SR.Format(SR.Expr_TypeMismatch, expr)); } public static Exception FunctionArgumentOutOfRange(string arg, string func) { return ExceptionBuilder._ArgumentOutOfRange(arg, SR.Format(SR.Expr_ArgumentOutofRange, func)); } public static Exception ExpressionTooComplex() { return _Eval(SR.Expr_ExpressionTooComplex); } public static Exception UnboundName(string name) { return _Eval(SR.Format(SR.Expr_UnboundName, name)); } public static Exception InvalidString(string str) { return _Syntax(SR.Format(SR.Expr_InvalidString, str)); } public static Exception UndefinedFunction(string name) { return _Eval(SR.Format(SR.Expr_UndefinedFunction, name)); } public static Exception SyntaxError() { return _Syntax(SR.Expr_Syntax); } public static Exception FunctionArgumentCount(string name) { return _Eval(SR.Format(SR.Expr_FunctionArgumentCount, name)); } public static Exception MissingRightParen() { return _Syntax(SR.Expr_MissingRightParen); } public static Exception UnknownToken(string token, int position) { return _Syntax(SR.Format(SR.Expr_UnknownToken, token, position.ToString(CultureInfo.InvariantCulture))); } public static Exception UnknownToken(Tokens tokExpected, Tokens tokCurr, int position) { return _Syntax(SR.Format(SR.Expr_UnknownToken1, tokExpected.ToString(), tokCurr.ToString(), position.ToString(CultureInfo.InvariantCulture))); } public static Exception DatatypeConvertion(Type type1, Type type2) { return _Eval(SR.Format(SR.Expr_DatatypeConvertion, type1.ToString(), type2.ToString())); } public static Exception DatavalueConvertion(object value, Type type, Exception innerException) { return _Eval(SR.Format(SR.Expr_DatavalueConvertion, value.ToString(), type.ToString()), innerException); } public static Exception InvalidName(string name) { return _Syntax(SR.Format(SR.Expr_InvalidName, name)); } public static Exception InvalidDate(string date) { return _Syntax(SR.Format(SR.Expr_InvalidDate, date)); } public static Exception NonConstantArgument() { return _Eval(SR.Expr_NonConstantArgument); } public static Exception InvalidPattern(string pat) { return _Eval(SR.Format(SR.Expr_InvalidPattern, pat)); } public static Exception InWithoutParentheses() { return _Syntax(SR.Expr_InWithoutParentheses); } public static Exception InWithoutList() { return _Syntax(SR.Expr_InWithoutList); } public static Exception InvalidIsSyntax() { return _Syntax(SR.Expr_IsSyntax); } public static Exception Overflow(Type type) { return _Overflow(SR.Format(SR.Expr_Overflow, type.Name)); } public static Exception ArgumentType(string function, int arg, Type type) { return _Eval(SR.Format(SR.Expr_ArgumentType, function, arg.ToString(CultureInfo.InvariantCulture), type.ToString())); } public static Exception ArgumentTypeInteger(string function, int arg) { return _Eval(SR.Format(SR.Expr_ArgumentTypeInteger, function, arg.ToString(CultureInfo.InvariantCulture))); } public static Exception TypeMismatchInBinop(int op, Type type1, Type type2) { return _Eval(SR.Format(SR.Expr_TypeMismatchInBinop, Operators.ToString(op), type1.ToString(), type2.ToString())); } public static Exception AmbiguousBinop(int op, Type type1, Type type2) { return _Eval(SR.Format(SR.Expr_AmbiguousBinop, Operators.ToString(op), type1.ToString(), type2.ToString())); } public static Exception UnsupportedOperator(int op) { return _Eval(SR.Format(SR.Expr_UnsupportedOperator, Operators.ToString(op))); } public static Exception InvalidNameBracketing(string name) { return _Syntax(SR.Format(SR.Expr_InvalidNameBracketing, name)); } public static Exception MissingOperandBefore(string op) { return _Syntax(SR.Format(SR.Expr_MissingOperandBefore, op)); } public static Exception TooManyRightParentheses() { return _Syntax(SR.Expr_TooManyRightParentheses); } public static Exception UnresolvedRelation(string name, string expr) { return _Eval(SR.Format(SR.Expr_UnresolvedRelation, name, expr)); } internal static EvaluateException BindFailure(string relationName) { return _Eval(SR.Format(SR.Expr_BindFailure, relationName)); } public static Exception AggregateArgument() { return _Syntax(SR.Expr_AggregateArgument); } public static Exception AggregateUnbound(string expr) { return _Eval(SR.Format(SR.Expr_AggregateUnbound, expr)); } public static Exception EvalNoContext() { return _Eval(SR.Expr_EvalNoContext); } public static Exception ExpressionUnbound(string expr) { return _Eval(SR.Format(SR.Expr_ExpressionUnbound, expr)); } public static Exception ComputeNotAggregate(string expr) { return _Eval(SR.Format(SR.Expr_ComputeNotAggregate, expr)); } public static Exception FilterConvertion(string expr) { return _Eval(SR.Format(SR.Expr_FilterConvertion, expr)); } public static Exception LookupArgument() { return _Syntax(SR.Expr_LookupArgument); } public static Exception InvalidType(string typeName) { return _Eval(SR.Format(SR.Expr_InvalidType, typeName)); } public static Exception InvalidHoursArgument() { return _Eval(SR.Expr_InvalidHoursArgument); } public static Exception InvalidMinutesArgument() { return _Eval(SR.Expr_InvalidMinutesArgument); } public static Exception InvalidTimeZoneRange() { return _Eval(SR.Expr_InvalidTimeZoneRange); } public static Exception MismatchKindandTimeSpan() { return _Eval(SR.Expr_MismatchKindandTimeSpan); } public static Exception UnsupportedDataType(Type type) { return ExceptionBuilder._Argument(SR.Format(SR.Expr_UnsupportedType, type.FullName)); } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests.Testing { using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using MassTransit.Testing; using Shouldly; [TestFixture] public class When_a_consumer_is_being_tested { InMemoryTestHarness _harness; ConsumerTestHarness<Testsumer> _consumer; [OneTimeSetUp] public async Task A_consumer_is_being_tested() { _harness = new InMemoryTestHarness(); _consumer = _harness.Consumer<Testsumer>(); await _harness.Start(); await _harness.InputQueueSendEndpoint.Send(new A()); } [OneTimeTearDown] public async Task Teardown() { await _harness.Stop(); } [Test] public void Should_send_the_initial_message_to_the_consumer() { _harness.Sent.Select<A>().Any().ShouldBe(true); } [Test] public void Should_have_sent_the_response_from_the_consumer() { _harness.Published.Select<B>().Any().ShouldBe(true); } [Test] public void Should_receive_the_message_type_a() { _harness.Consumed.Select<A>().Any().ShouldBe(true); } [Test] public void Should_have_called_the_consumer_method() { _consumer.Consumed.Select<A>().Any().ShouldBe(true); } class Testsumer : IConsumer<A> { public async Task Consume(ConsumeContext<A> context) { await context.RespondAsync(new B()); } } class A { } class B { } } [TestFixture] public class When_a_consumer_of_interfaces_is_being_tested { InMemoryTestHarness _harness; ConsumerTestHarness<TestInterfaceConsumer> _consumer; [OneTimeSetUp] public async Task A_consumer_is_being_tested() { _harness = new InMemoryTestHarness(); _consumer = _harness.Consumer<TestInterfaceConsumer>(); await _harness.Start(); await _harness.InputQueueSendEndpoint.Send(new A()); } [OneTimeTearDown] public async Task Teardown() { await _harness.Stop(); } [Test] public void Should_send_the_initial_message_to_the_consumer() { _harness.Sent.Select<A>().Any().ShouldBe(true); _harness.Sent.Select<IA>().Any().ShouldBe(true); } [Test] public void Should_have_sent_the_response_from_the_consumer() { _harness.Published.Select<B>().Any().ShouldBe(true); _harness.Published.Select<IB>().Any().ShouldBe(true); } [Test] public void Should_receive_the_message_type_a() { _harness.Consumed.Select<IA>().Any().ShouldBe(true); } [Test] public void Should_have_called_the_consumer_method() { _consumer.Consumed.Select<IA>().Any().ShouldBe(true); } class TestInterfaceConsumer : IConsumer<IA> { public async Task Consume(ConsumeContext<IA> context) { await context.RespondAsync(new B()); } } public interface IA { } class A : IA { } public interface IB { } class B : IB { } } public class When_a_context_consumer_is_being_tested { InMemoryTestHarness _harness; ConsumerTestHarness<Testsumer> _consumer; [OneTimeSetUp] public async Task A_consumer_is_being_tested() { _harness = new InMemoryTestHarness(); _consumer = _harness.Consumer<Testsumer>(); await _harness.Start(); await _harness.InputQueueSendEndpoint.Send(new A(), context => context.ResponseAddress = _harness.BusAddress); } [OneTimeTearDown] public async Task Teardown() { await _harness.Stop(); } [Test] public void Should_send_the_initial_message_to_the_consumer() { _harness.Sent.Select<A>().Any().ShouldBe(true); } [Test] public void Should_have_sent_the_response_from_the_consumer() { _harness.Sent.Select<B>().Any().ShouldBe(true); } [Test] public void Should_receive_the_message_type_a() { _harness.Consumed.Select<A>().Any().ShouldBe(true); } [Test] public void Should_have_called_the_consumer_method() { _consumer.Consumed.Select<A>().Any().ShouldBe(true); } class Testsumer : IConsumer<A> { public Task Consume(ConsumeContext<A> context) { return context.RespondAsync(new B()); } } class A { } class B { } } }
//--------------------------------------------------------------------- // <copyright file="StorageMappingItemCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Common.Utils; using System.Data.Entity; using System.Data.Mapping.Update.Internal; using System.Data.Mapping.ViewGeneration; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using System.Runtime.Versioning; using System.Xml; using som = System.Data.EntityModel.SchemaObjectModel; namespace System.Data.Mapping { using OfTypeQVCacheKey = Pair<EntitySetBase, Pair<EntityTypeBase, bool>>; /// <summary> /// Class for representing a collection of items in Storage Mapping( CS Mapping) space. /// </summary> [CLSCompliant(false)] public partial class StorageMappingItemCollection : MappingItemCollection { #region Fields //EdmItemCollection that is associated with the MSL Loader. private EdmItemCollection m_edmCollection; //StoreItemCollection that is associated with the MSL Loader. private StoreItemCollection m_storeItemCollection; private ViewDictionary m_viewDictionary; private double m_mappingVersion = XmlConstants.UndefinedVersion; private MetadataWorkspace m_workspace; // In this version, we won't allow same types in CSpace to map to different types in store. If the same type // need to be reused, the store type must be the same. To keep track of this, we need to keep track of the member // mapping across maps to make sure they are mapped to the same store side. // The first TypeUsage in the KeyValuePair stores the store equivalent type for the cspace member type and the second // one store the actual store type to which the member is mapped to. // For e.g. If the CSpace member of type Edm.Int32 maps to a sspace member of type SqlServer.bigint, then the KeyValuePair // for the cspace member will contain SqlServer.int (store equivalent for Edm.Int32) and SqlServer.bigint (Actual store type // to which the member was mapped to) private Dictionary<EdmMember, KeyValuePair<TypeUsage, TypeUsage>> m_memberMappings = new Dictionary<EdmMember, KeyValuePair<TypeUsage, TypeUsage>>(); private ViewLoader _viewLoader; internal enum InterestingMembersKind { RequiredOriginalValueMembers, // legacy - used by the obsolete GetRequiredOriginalValueMembers FullUpdate, // Interesting members in case of full update scenario PartialUpdate // Interesting members in case of partial update scenario }; private ConcurrentDictionary<Tuple<EntitySetBase, EntityTypeBase, InterestingMembersKind>, ReadOnlyCollection<EdmMember>> _cachedInterestingMembers = new ConcurrentDictionary<Tuple<EntitySetBase, EntityTypeBase, InterestingMembersKind>, ReadOnlyCollection<EdmMember>>(); #endregion #region Constructors /// <summary> /// constructor that takes in a list of folder or files or a mix of both and /// creates metadata for mapping in all the files. /// </summary> /// <param name="edmCollection"></param> /// <param name="storeCollection"></param> /// <param name="filePaths"></param> [ResourceExposure(ResourceScope.Machine)] //Exposes the file path names which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.CreateCompositeFromFilePaths method call but we do not create the file paths in this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "edm")] public StorageMappingItemCollection(EdmItemCollection edmCollection, StoreItemCollection storeCollection, params string[] filePaths) : base(DataSpace.CSSpace) { EntityUtil.CheckArgumentNull(edmCollection, "edmCollection"); EntityUtil.CheckArgumentNull(storeCollection, "storeCollection"); EntityUtil.CheckArgumentNull(filePaths, "filePaths"); this.m_edmCollection = edmCollection; this.m_storeItemCollection = storeCollection; // Wrap the file paths in instances of the MetadataArtifactLoader class, which provides // an abstraction and a uniform interface over a diverse set of metadata artifacts. // MetadataArtifactLoader composite = null; List<XmlReader> readers = null; try { composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(filePaths, XmlConstants.CSSpaceSchemaExtension); readers = composite.CreateReaders(DataSpace.CSSpace); this.Init(edmCollection, storeCollection, readers, composite.GetPaths(DataSpace.CSSpace), true /*throwOnError*/); } finally { if (readers != null) { Helper.DisposeXmlReaders(readers); } } } /// <summary> /// constructor that takes in a list of XmlReaders and creates metadata for mapping /// in all the files. /// </summary> /// <param name="edmCollection">The edm metadata collection that this mapping is to use</param> /// <param name="storeCollection">The store metadata collection that this mapping is to use</param> /// <param name="xmlReaders">The XmlReaders to load mapping from</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "edm")] public StorageMappingItemCollection(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable<XmlReader> xmlReaders) : base(DataSpace.CSSpace) { EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders"); MetadataArtifactLoader composite = MetadataArtifactLoader.CreateCompositeFromXmlReaders(xmlReaders); this.Init(edmCollection, storeCollection, composite.GetReaders(), // filter out duplicates composite.GetPaths(), true /* throwOnError*/); } /// <summary> /// constructor that takes in a list of XmlReaders and creates metadata for mapping /// in all the files. /// </summary> /// <param name="edmCollection">The edm metadata collection that this mapping is to use</param> /// <param name="storeCollection">The store metadata collection that this mapping is to use</param> /// <param name="filePaths">Mapping URIs</param> /// <param name="xmlReaders">The XmlReaders to load mapping from</param> /// <param name="errors">a list of errors for each file loaded</param> // referenced by System.Data.Entity.Design.dll [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] internal StorageMappingItemCollection(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable<XmlReader> xmlReaders, List<string> filePaths, out IList<EdmSchemaError> errors) : base(DataSpace.CSSpace) { // we will check the parameters for this internal ctor becuase // it is pretty much publicly exposed through the MetadataItemCollectionFactory // in System.Data.Entity.Design EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders"); EntityUtil.CheckArgumentContainsNull(ref xmlReaders, "xmlReaders"); // filePaths is allowed to be null errors = this.Init(edmCollection, storeCollection, xmlReaders, filePaths, false /*throwOnError*/); } /// <summary> /// constructor that takes in a list of XmlReaders and creates metadata for mapping /// in all the files. /// </summary> /// <param name="edmCollection">The edm metadata collection that this mapping is to use</param> /// <param name="storeCollection">The store metadata collection that this mapping is to use</param> /// <param name="filePaths">Mapping URIs</param> /// <param name="xmlReaders">The XmlReaders to load mapping from</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] internal StorageMappingItemCollection(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable<XmlReader> xmlReaders, List<string> filePaths) : base(DataSpace.CSSpace) { this.Init(edmCollection, storeCollection, xmlReaders, filePaths, true /*throwOnError*/); } /// <summary> /// Initializer that takes in a list of XmlReaders and creates metadata for mapping /// in all the files. /// </summary> /// <param name="edmCollection">The edm metadata collection that this mapping is to use</param> /// <param name="storeCollection">The store metadata collection that this mapping is to use</param> /// <param name="filePaths">Mapping URIs</param> /// <param name="xmlReaders">The XmlReaders to load mapping from</param> /// <param name="errors">a list of errors for each file loaded</param> private IList<EdmSchemaError> Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable<XmlReader> xmlReaders, List<string> filePaths, bool throwOnError) { EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders"); EntityUtil.CheckArgumentNull(edmCollection, "edmCollection"); EntityUtil.CheckArgumentNull(storeCollection, "storeCollection"); this.m_edmCollection = edmCollection; this.m_storeItemCollection = storeCollection; Dictionary<EntitySetBase, GeneratedView> userDefinedQueryViewsDict; Dictionary<OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict; this.m_viewDictionary = new ViewDictionary(this, out userDefinedQueryViewsDict, out userDefinedQueryViewsOfTypeDict); List<EdmSchemaError> errors = new List<EdmSchemaError>(); if(this.m_edmCollection.EdmVersion != XmlConstants.UndefinedVersion && this.m_storeItemCollection.StoreSchemaVersion != XmlConstants.UndefinedVersion && this.m_edmCollection.EdmVersion != this.m_storeItemCollection.StoreSchemaVersion) { errors.Add( new EdmSchemaError( Strings.Mapping_DifferentEdmStoreVersion, (int)StorageMappingErrorCode.MappingDifferentEdmStoreVersion, EdmSchemaErrorSeverity.Error)); } else { double expectedVersion = this.m_edmCollection.EdmVersion != XmlConstants.UndefinedVersion ? this.m_edmCollection.EdmVersion : this.m_storeItemCollection.StoreSchemaVersion; errors.AddRange(LoadItems(xmlReaders, filePaths, userDefinedQueryViewsDict, userDefinedQueryViewsOfTypeDict, expectedVersion)); } Debug.Assert(errors != null); if (errors.Count > 0 && throwOnError) { if (!System.Data.Common.Utils.MetadataHelper.CheckIfAllErrorsAreWarnings(errors)) { // NOTE: not using Strings.InvalidSchemaEncountered because it will truncate the errors list. throw new MappingException( String.Format(System.Globalization.CultureInfo.CurrentCulture, EntityRes.GetString(EntityRes.InvalidSchemaEncountered), Helper.CombineErrorMessage(errors))); } } return errors; } #endregion Constructors internal MetadataWorkspace Workspace { get { if (m_workspace == null) { m_workspace = new MetadataWorkspace(); m_workspace.RegisterItemCollection(m_edmCollection); m_workspace.RegisterItemCollection(m_storeItemCollection); m_workspace.RegisterItemCollection(this); } return m_workspace; } } /// <summary> /// Return the EdmItemCollection associated with the Mapping Collection /// </summary> internal EdmItemCollection EdmItemCollection { get { return this.m_edmCollection; } } /// <summary> /// Version of this StorageMappingItemCollection represents. /// </summary> public double MappingVersion { get { return this.m_mappingVersion; } } /// <summary> /// Return the StoreItemCollection associated with the Mapping Collection /// </summary> internal StoreItemCollection StoreItemCollection { get { return this.m_storeItemCollection; } } /// <summary> /// Search for a Mapping metadata with the specified type key. /// </summary> /// <param name="identity">identity of the type</param> /// <param name="typeSpace">The dataspace that the type for which map needs to be returned belongs to</param> /// <param name="ignoreCase">true for case-insensitive lookup</param> /// <exception cref="ArgumentException"> Thrown if mapping space is not valid</exception> internal override Map GetMap(string identity, DataSpace typeSpace, bool ignoreCase) { EntityUtil.CheckArgumentNull(identity, "identity"); if (typeSpace != DataSpace.CSpace) { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.Mapping_Storage_InvalidSpace(typeSpace)); } return GetItem<Map>(identity, ignoreCase); } /// <summary> /// Search for a Mapping metadata with the specified type key. /// </summary> /// <param name="identity">identity of the type</param> /// <param name="typeSpace">The dataspace that the type for which map needs to be returned belongs to</param> /// <param name="ignoreCase">true for case-insensitive lookup</param> /// <param name="map"></param> /// <returns>Returns false if no match found.</returns> internal override bool TryGetMap(string identity, DataSpace typeSpace, bool ignoreCase, out Map map) { if (typeSpace != DataSpace.CSpace) { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.Mapping_Storage_InvalidSpace(typeSpace)); } return TryGetItem<Map>(identity, ignoreCase, out map); } /// <summary> /// Search for a Mapping metadata with the specified type key. /// </summary> /// <param name="identity">identity of the type</param> /// <param name="typeSpace">The dataspace that the type for which map needs to be returned belongs to</param> /// <exception cref="ArgumentException"> Thrown if mapping space is not valid</exception> internal override Map GetMap(string identity, DataSpace typeSpace) { return this.GetMap(identity, typeSpace, false /*ignoreCase*/); } /// <summary> /// Search for a Mapping metadata with the specified type key. /// </summary> /// <param name="identity">identity of the type</param> /// <param name="typeSpace">The dataspace that the type for which map needs to be returned belongs to</param> /// <param name="map"></param> /// <returns>Returns false if no match found.</returns> internal override bool TryGetMap(string identity, DataSpace typeSpace, out Map map) { return this.TryGetMap(identity, typeSpace, false /*ignoreCase*/, out map); } /// <summary> /// Search for a Mapping metadata with the specified type key. /// </summary> /// <param name="item"></param> internal override Map GetMap(GlobalItem item) { EntityUtil.CheckArgumentNull(item, "item"); DataSpace typeSpace = item.DataSpace; if (typeSpace != DataSpace.CSpace) { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.Mapping_Storage_InvalidSpace(typeSpace)); } return this.GetMap(item.Identity, typeSpace); } /// <summary> /// Search for a Mapping metadata with the specified type key. /// </summary> /// <param name="item"></param> /// <param name="map"></param> /// <returns>Returns false if no match found.</returns> internal override bool TryGetMap(GlobalItem item, out Map map) { if (item == null) { map = null; return false; } DataSpace typeSpace = item.DataSpace; if (typeSpace != DataSpace.CSpace) { map = null; return false; } return this.TryGetMap(item.Identity, typeSpace, out map); } /// <summary> /// This method /// - generates views from the mapping elements in the collection; /// - does not process user defined views - these are processed during mapping collection loading; /// - does not cache generated views in the mapping collection. /// The main purpose is design-time view validation and generation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // referenced by System.Data.Entity.Design.dll internal Dictionary<EntitySetBase, string> GenerateEntitySetViews(out IList<EdmSchemaError> errors) { Dictionary<EntitySetBase, string> esqlViews = new Dictionary<EntitySetBase, string>(); errors = new List<EdmSchemaError>(); foreach (var mapping in GetItems<Map>()) { var entityContainerMapping = mapping as StorageEntityContainerMapping; if (entityContainerMapping != null) { // If there are no entity set maps, don't call the view generation process. if (!entityContainerMapping.HasViews) { return esqlViews; } // If entityContainerMapping contains only query views, then add a warning to the errors and continue to next mapping. if (!entityContainerMapping.HasMappingFragments()) { Debug.Assert(2088 == (int)StorageMappingErrorCode.MappingAllQueryViewAtCompileTime, "Please change the ERRORCODE_MAPPINGALLQUERYVIEWATCOMPILETIME value as well"); errors.Add(new EdmSchemaError( Strings.Mapping_AllQueryViewAtCompileTime(entityContainerMapping.Identity), (int)StorageMappingErrorCode.MappingAllQueryViewAtCompileTime, EdmSchemaErrorSeverity.Warning)); } else { ViewGenResults viewGenResults = ViewgenGatekeeper.GenerateViewsFromMapping(entityContainerMapping, new ConfigViewGenerator() { GenerateEsql = true }); if (viewGenResults.HasErrors) { ((List<EdmSchemaError>)errors).AddRange(viewGenResults.Errors); } KeyToListMap<EntitySetBase, GeneratedView> extentMappingViews = viewGenResults.Views; foreach (KeyValuePair<EntitySetBase, List<GeneratedView>> extentViewPair in extentMappingViews.KeyValuePairs) { List<GeneratedView> generatedViews = extentViewPair.Value; // Multiple Views are returned for an extent but the first view // is the only one that we will use for now. In the future, // we might start using the other views which are per type within an extent. esqlViews.Add(extentViewPair.Key, generatedViews[0].eSQL); } } } } return esqlViews; } #region Get interesting members /// <summary> /// Return members for MetdataWorkspace.GetRequiredOriginalValueMembers() and MetdataWorkspace.GetRelevantMembersForUpdate() methods. /// </summary> /// <param name="entitySet">An EntitySet belonging to the C-Space. Must not be null.</param> /// <param name="entityType">An EntityType that participates in the given EntitySet. Must not be null.</param> /// <param name="interestingMembersKind">Scenario the members should be returned for.</param> /// <returns>ReadOnlyCollection of interesting members for the requested scenario (<paramref name="interestingMembersKind"/>).</returns> internal ReadOnlyCollection<EdmMember> GetInterestingMembers(EntitySetBase entitySet, EntityTypeBase entityType, InterestingMembersKind interestingMembersKind) { Debug.Assert(entitySet != null, "entitySet != null"); Debug.Assert(entityType != null, "entityType != null"); var key = new Tuple<EntitySetBase, EntityTypeBase, InterestingMembersKind>(entitySet, entityType, interestingMembersKind); return _cachedInterestingMembers.GetOrAdd(key, FindInterestingMembers(entitySet, entityType, interestingMembersKind)); } /// <summary> /// Finds interesting members for MetdataWorkspace.GetRequiredOriginalValueMembers() and MetdataWorkspace.GetRelevantMembersForUpdate() methods /// for the given <paramref name="entitySet"/> and <paramref name="entityType"/>. /// </summary> /// <param name="entitySet">An EntitySet belonging to the C-Space. Must not be null.</param> /// <param name="entityType">An EntityType that participates in the given EntitySet. Must not be null.</param> /// <param name="interestingMembersKind">Scenario the members should be returned for.</param> /// <returns>ReadOnlyCollection of interesting members for the requested scenario (<paramref name="interestingMembersKind"/>).</returns> private ReadOnlyCollection<EdmMember> FindInterestingMembers(EntitySetBase entitySet, EntityTypeBase entityType, InterestingMembersKind interestingMembersKind) { Debug.Assert(entitySet != null, "entitySet != null"); Debug.Assert(entityType != null, "entityType != null"); var interestingMembers = new List<EdmMember>(); foreach (var storageTypeMapping in MappingMetadataHelper.GetMappingsForEntitySetAndSuperTypes(this, entitySet.EntityContainer, entitySet, entityType)) { StorageAssociationTypeMapping associationTypeMapping = storageTypeMapping as StorageAssociationTypeMapping; if (associationTypeMapping != null) { FindInterestingAssociationMappingMembers(associationTypeMapping, interestingMembers); } else { Debug.Assert(storageTypeMapping is StorageEntityTypeMapping, "StorageEntityTypeMapping expected."); FindInterestingEntityMappingMembers((StorageEntityTypeMapping)storageTypeMapping, interestingMembersKind, interestingMembers); } } // For backwards compatibility we don't return foreign keys from the obsolete MetadataWorkspace.GetRequiredOriginalValueMembers() method if (interestingMembersKind != InterestingMembersKind.RequiredOriginalValueMembers) { FindForeignKeyProperties(entitySet, entityType, interestingMembers); } foreach (var functionMappings in MappingMetadataHelper .GetModificationFunctionMappingsForEntitySetAndType(this, entitySet.EntityContainer, entitySet, entityType) .Where(functionMappings => functionMappings.UpdateFunctionMapping != null)) { FindInterestingFunctionMappingMembers(functionMappings, interestingMembersKind, ref interestingMembers); } Debug.Assert(interestingMembers != null, "interestingMembers must never be null."); return new ReadOnlyCollection<EdmMember>(interestingMembers.Distinct().ToList()); } /// <summary> /// Finds members participating in the assocciation and adds them to the <paramref name="interestingMembers"/>. /// </summary> /// <param name="associationTypeMapping">Association type mapping. Must not be null.</param> /// <param name="interestingMembers">The list the interesting members (if any) will be added to. Must not be null.</param> private static void FindInterestingAssociationMappingMembers(StorageAssociationTypeMapping associationTypeMapping, List<EdmMember> interestingMembers) { Debug.Assert(associationTypeMapping != null, "entityTypeMapping != null"); Debug.Assert(interestingMembers != null, "interestingMembers != null"); //(2) Ends participating in association are "interesting" interestingMembers.AddRange( associationTypeMapping .MappingFragments .SelectMany(m => m.AllProperties) .OfType<StorageEndPropertyMapping>() .Select(epm => epm.EndMember)); } /// <summary> /// Finds interesting entity properties - primary keys (if requested), properties (including complex properties and nested properties) /// with concurrency mode set to fixed and C-Side condition members and adds them to the <paramref name="interestingMembers"/>. /// </summary> /// <param name="entityTypeMapping">Entity type mapping. Must not be null.</param> /// <param name="interestingMembersKind">Scenario the members should be returned for.</param> /// <param name="interestingMembers">The list the interesting members (if any) will be added to. Must not be null.</param> private static void FindInterestingEntityMappingMembers(StorageEntityTypeMapping entityTypeMapping, InterestingMembersKind interestingMembersKind, List<EdmMember> interestingMembers) { Debug.Assert(entityTypeMapping != null, "entityTypeMapping != null"); Debug.Assert(interestingMembers != null, "interestingMembers != null"); foreach (var propertyMapping in entityTypeMapping.MappingFragments.SelectMany(mf => mf.AllProperties)) { StorageScalarPropertyMapping scalarPropMapping = propertyMapping as StorageScalarPropertyMapping; StorageComplexPropertyMapping complexPropMapping = propertyMapping as StorageComplexPropertyMapping; StorageConditionPropertyMapping conditionMapping = propertyMapping as StorageConditionPropertyMapping; Debug.Assert(!(propertyMapping is StorageEndPropertyMapping), "association mapping properties should be handled elsewhere."); Debug.Assert(scalarPropMapping != null || complexPropMapping != null || conditionMapping != null, "Unimplemented property mapping"); //scalar property if (scalarPropMapping != null && scalarPropMapping.EdmProperty != null) { // (0) if a member is part of the key it is interesting if (MetadataHelper.IsPartOfEntityTypeKey(scalarPropMapping.EdmProperty)) { // For backwards compatibility we do return primary keys from the obsolete MetadataWorkspace.GetRequiredOriginalValueMembers() method if (interestingMembersKind == InterestingMembersKind.RequiredOriginalValueMembers) { interestingMembers.Add(scalarPropMapping.EdmProperty); } } //(3) if a scalar property has Fixed concurrency mode then it is "interesting" else if (MetadataHelper.GetConcurrencyMode(scalarPropMapping.EdmProperty) == ConcurrencyMode.Fixed) { interestingMembers.Add(scalarPropMapping.EdmProperty); } } else if (complexPropMapping != null) { // (7) All complex members - partial update scenarios only // (3.1) The complex property or its one of its children has fixed concurrency mode if (interestingMembersKind == InterestingMembersKind.PartialUpdate || MetadataHelper.GetConcurrencyMode(complexPropMapping.EdmProperty) == ConcurrencyMode.Fixed || HasFixedConcurrencyModeInAnyChildProperty(complexPropMapping)) { interestingMembers.Add(complexPropMapping.EdmProperty); } } else if (conditionMapping != null) { //(1) C-Side condition members are 'interesting' if (conditionMapping.EdmProperty != null) { interestingMembers.Add(conditionMapping.EdmProperty); } } } } /// <summary> /// Recurses down the complex property to find whether any of the nseted properties has concurrency mode set to "Fixed" /// </summary> /// <param name="complexMapping">Complex property mapping. Must not be null.</param> /// <returns><c>true</c> if any of the descendant properties has concurrency mode set to "Fixed". Otherwise <c>false</c>.</returns> private static bool HasFixedConcurrencyModeInAnyChildProperty(StorageComplexPropertyMapping complexMapping) { Debug.Assert(complexMapping != null, "complexMapping != null"); foreach (StoragePropertyMapping propertyMapping in complexMapping.TypeMappings.SelectMany(m => m.AllProperties)) { StorageScalarPropertyMapping childScalarPropertyMapping = propertyMapping as StorageScalarPropertyMapping; StorageComplexPropertyMapping childComplexPropertyMapping = propertyMapping as StorageComplexPropertyMapping; Debug.Assert(childScalarPropertyMapping != null || childComplexPropertyMapping != null, "Unimplemented property mapping for complex property"); //scalar property and has Fixed CC mode if (childScalarPropertyMapping != null && MetadataHelper.GetConcurrencyMode(childScalarPropertyMapping.EdmProperty) == ConcurrencyMode.Fixed) { return true; } // Complex Prop and sub-properties or itself has fixed CC mode else if (childComplexPropertyMapping != null && (MetadataHelper.GetConcurrencyMode(childComplexPropertyMapping.EdmProperty) == ConcurrencyMode.Fixed || HasFixedConcurrencyModeInAnyChildProperty(childComplexPropertyMapping))) { return true; } } return false; } /// <summary> /// Finds foreign key properties and adds them to the <paramref name="interestingMembers"/>. /// </summary> /// <param name="entitySetBase">Entity set <paramref name="entityType"/> relates to. Must not be null.</param> /// <param name="entityType">Entity type for which to find foreign key properties. Must not be null.</param> /// <param name="interestingMembers">The list the interesting members (if any) will be added to. Must not be null.</param> private void FindForeignKeyProperties(EntitySetBase entitySetBase, EntityTypeBase entityType, List<EdmMember> interestingMembers) { var entitySet = entitySetBase as EntitySet; if (entitySet != null && entitySet.HasForeignKeyRelationships) { // (6) Foreign keys // select all foreign key properties defined on the entityType and all its ancestors interestingMembers.AddRange( MetadataHelper.GetTypeAndParentTypesOf(entityType, this.m_edmCollection, true) .SelectMany(e => ((EntityType)e).Properties) .Where(p => entitySet.ForeignKeyDependents.SelectMany(fk => fk.Item2.ToProperties).Contains(p))); } } /// <summary> /// Finds interesting members for modification functions mapped to stored procedures and adds them to the <paramref name="interestingMembers"/>. /// </summary> /// <param name="functionMappings">Modification function mapping. Must not be null.</param> /// <param name="interestingMembersKind">Update scenario the members will be used in (in general - partial update vs. full update).</param> /// <param name="interestingMembers"></param> private static void FindInterestingFunctionMappingMembers(StorageEntityTypeModificationFunctionMapping functionMappings, InterestingMembersKind interestingMembersKind, ref List<EdmMember> interestingMembers) { Debug.Assert(functionMappings != null && functionMappings.UpdateFunctionMapping != null, "Expected function mapping fragment with non-null update function mapping"); Debug.Assert(interestingMembers != null, "interestingMembers != null"); // for partial update scenarios (e.g. EntityDataSourceControl) all members are interesting otherwise the data may be corrupt. // See bugs #272992 and #124460 in DevDiv database for more details. For full update scenarios and the obsolete // MetadataWorkspace.GetRequiredOriginalValueMembers() metod we return only members with Version set to "Original". if (interestingMembersKind == InterestingMembersKind.PartialUpdate) { // (5) Members included in Update ModificationFunction interestingMembers.AddRange(functionMappings.UpdateFunctionMapping.ParameterBindings.Select(p => p.MemberPath.Members.Last())); } else { //(4) Members in update ModificationFunction with Version="Original" are "interesting" // This also works when you have complex-types (4.1) Debug.Assert( interestingMembersKind == InterestingMembersKind.FullUpdate || interestingMembersKind == InterestingMembersKind.RequiredOriginalValueMembers, "Unexpected kind of interesting members - if you changed the InterestingMembersKind enum type update this code accordingly"); foreach (var parameterBinding in functionMappings.UpdateFunctionMapping.ParameterBindings.Where(p => !p.IsCurrent)) { //Last is the root element (with respect to the Entity) //For example, Entity1={ // S1, // C1{S2, // C2{ S3, S4 } // }, // S5} // if S4 matches (i.e. C1.C2.S4), then it returns C1 //because internally the list is [S4][C2][C1] interestingMembers.Add(parameterBinding.MemberPath.Members.Last()); } } } #endregion /// <summary> /// Calls the view dictionary to load the view, see detailed comments in the view dictionary class. /// </summary> internal GeneratedView GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace) { return this.m_viewDictionary.GetGeneratedView(extent, workspace, this); } // Add to the cache. If it is already present, then throw an exception private void AddInternal(Map storageMap) { storageMap.DataSpace = DataSpace.CSSpace; try { base.AddInternal(storageMap); } catch (ArgumentException e) { throw new MappingException(System.Data.Entity.Strings.Mapping_Duplicate_Type(storageMap.EdmItem.Identity), e); } } // Contains whether the given StorageEntityContainerName internal bool ContainsStorageEntityContainer(string storageEntityContainerName) { ReadOnlyCollection<StorageEntityContainerMapping> entityContainerMaps = this.GetItems<StorageEntityContainerMapping>(); return entityContainerMaps.Any(map => map.StorageEntityContainer.Name.Equals(storageEntityContainerName, StringComparison.Ordinal)); } /// <summary> /// This helper method loads items based on contents of in-memory XmlReader instances. /// Assumption: This method is called only from the constructor because m_extentMappingViews is not thread safe. /// </summary> /// <param name="xmlReaders">A list of XmlReader instances</param> /// <param name="mappingSchemaUris">A list of URIs</param> /// <returns>A list of schema errors</returns> private List<EdmSchemaError> LoadItems(IEnumerable<XmlReader> xmlReaders, List<string> mappingSchemaUris, Dictionary<EntitySetBase, GeneratedView> userDefinedQueryViewsDict, Dictionary<OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict, double expectedVersion) { Debug.Assert(m_memberMappings.Count == 0, "Assumption: This method is called only once, and from the constructor because m_extentMappingViews is not thread safe."); List<EdmSchemaError> errors = new List<EdmSchemaError>(); int index = -1; foreach (XmlReader xmlReader in xmlReaders) { index++; string location = null; if (mappingSchemaUris == null) { som.SchemaManager.TryGetBaseUri(xmlReader, out location); } else { location = mappingSchemaUris[index]; } StorageMappingItemLoader mapLoader = new StorageMappingItemLoader( xmlReader, this, location, // ASSUMPTION: location is only used for generating error-messages m_memberMappings); errors.AddRange(mapLoader.ParsingErrors); CheckIsSameVersion(expectedVersion, mapLoader.MappingVersion, errors); // Process container mapping. StorageEntityContainerMapping containerMapping = mapLoader.ContainerMapping; if (mapLoader.HasQueryViews && containerMapping != null) { // Compile the query views so that we can report the errors in the user specified views. CompileUserDefinedQueryViews(containerMapping, userDefinedQueryViewsDict, userDefinedQueryViewsOfTypeDict, errors); } // Add container mapping if there are no errors and entity container mapping is not already present. if (MetadataHelper.CheckIfAllErrorsAreWarnings(errors) && !this.Contains(containerMapping)) { AddInternal(containerMapping); } } CheckForDuplicateItems(EdmItemCollection, StoreItemCollection, errors); return errors; } /// <summary> /// This method compiles all the user defined query views in the <paramref name="entityContainerMapping"/>. /// </summary> private static void CompileUserDefinedQueryViews(StorageEntityContainerMapping entityContainerMapping, Dictionary<EntitySetBase, GeneratedView> userDefinedQueryViewsDict, Dictionary<OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict, IList<EdmSchemaError> errors) { ConfigViewGenerator config = new ConfigViewGenerator(); foreach (StorageSetMapping setMapping in entityContainerMapping.AllSetMaps) { if (setMapping.QueryView != null) { GeneratedView generatedView; if (!userDefinedQueryViewsDict.TryGetValue(setMapping.Set, out generatedView)) { // Parse the view so that we will get back any errors in the view. if (GeneratedView.TryParseUserSpecifiedView(setMapping, setMapping.Set.ElementType, setMapping.QueryView, true, // includeSubtypes entityContainerMapping.StorageMappingItemCollection, config, /*out*/ errors, out generatedView)) { // Add first QueryView userDefinedQueryViewsDict.Add(setMapping.Set, generatedView); } // Add all type-specific QueryViews foreach (OfTypeQVCacheKey key in setMapping.GetTypeSpecificQVKeys()) { Debug.Assert(key.First.Equals(setMapping.Set)); if (GeneratedView.TryParseUserSpecifiedView(setMapping, key.Second.First, // type setMapping.GetTypeSpecificQueryView(key), key.Second.Second, // includeSubtypes entityContainerMapping.StorageMappingItemCollection, config, /*out*/ errors, out generatedView)) { userDefinedQueryViewsOfTypeDict.Add(key, generatedView); } } } } } } private void CheckIsSameVersion(double expectedVersion, double currentLoaderVersion, IList<EdmSchemaError> errors) { if (m_mappingVersion == XmlConstants.UndefinedVersion) { m_mappingVersion = currentLoaderVersion; } if (expectedVersion != XmlConstants.UndefinedVersion && currentLoaderVersion != XmlConstants.UndefinedVersion && currentLoaderVersion != expectedVersion) { // Check that the mapping version is the same as the storage and model version errors.Add( new EdmSchemaError( Strings.Mapping_DifferentMappingEdmStoreVersion, (int)StorageMappingErrorCode.MappingDifferentMappingEdmStoreVersion, EdmSchemaErrorSeverity.Error)); } if (currentLoaderVersion != m_mappingVersion && currentLoaderVersion != XmlConstants.UndefinedVersion) { // Check that the mapping versions are all consistent with each other errors.Add( new EdmSchemaError( Strings.CannotLoadDifferentVersionOfSchemaInTheSameItemCollection, (int)StorageMappingErrorCode.CannotLoadDifferentVersionOfSchemaInTheSameItemCollection, EdmSchemaErrorSeverity.Error)); } } /// <summary> /// Return the update view loader /// </summary> /// <returns></returns> internal ViewLoader GetUpdateViewLoader() { if (_viewLoader == null) { _viewLoader = new ViewLoader(this); } return _viewLoader; } /// <summary> /// this method will be called in metadatworkspace, the signature is the same as the one in ViewDictionary /// </summary> /// <param name="workspace"></param> /// <param name="entity"></param> /// <param name="type"></param> /// <param name="includeSubtypes"></param> /// <param name="generatedView"></param> /// <returns></returns> internal bool TryGetGeneratedViewOfType(MetadataWorkspace workspace, EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out GeneratedView generatedView) { return this.m_viewDictionary.TryGetGeneratedViewOfType(workspace, entity, type, includeSubtypes, out generatedView); } // Check for duplicate items (items with same name) in edm item collection and store item collection. Mapping is the only logical place to do this. // The only other place is workspace, but that is at the time of registering item collections (only when the second one gets registered) and we // will have to throw exceptions at that time. If we do this check in mapping, we might throw error in a more consistent way (by adding it to error // collection). Also if someone is just creating item collection, and not registering it with workspace (tools), doing it in mapping makes more sense private static void CheckForDuplicateItems(EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection, List<EdmSchemaError> errorCollection) { Debug.Assert(edmItemCollection != null && storeItemCollection != null && errorCollection != null, "The parameters must not be null in CheckForDuplicateItems"); foreach (GlobalItem item in edmItemCollection) { if (storeItemCollection.Contains(item.Identity)) { errorCollection.Add(new EdmSchemaError(Strings.Mapping_ItemWithSameNameExistsBothInCSpaceAndSSpace(item.Identity), (int)StorageMappingErrorCode.ItemWithSameNameExistsBothInCSpaceAndSSpace, EdmSchemaErrorSeverity.Error)); } } } }//---- ItemCollection }//----
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.Settings; using Microsoft.Win32; using PowerShellTools; using VSRegistry = Microsoft.VisualStudio.Shell.VSRegistry; namespace Microsoft.VisualStudio.Project { /// <summary> /// Provides implementation IVsSingleFileGeneratorFactory for /// </summary> public class SingleFileGeneratorFactory : IVsSingleFileGeneratorFactory { #region nested types private class GeneratorMetaData { #region fields private Guid generatorClsid = Guid.Empty; private int generatesDesignTimeSource = -1; private int generatesSharedDesignTimeSource = -1; private int useDesignTimeCompilationFlag = -1; object generator; #endregion #region ctor /// <summary> /// Constructor /// </summary> public GeneratorMetaData() { } #endregion #region Public Properties /// <summary> /// Generator instance /// </summary> public Object Generator { get { return generator; } set { generator = value; } } /// <summary> /// GeneratesDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> public int GeneratesDesignTimeSource { get { return generatesDesignTimeSource; } set { generatesDesignTimeSource = value; } } /// <summary> /// GeneratesSharedDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> public int GeneratesSharedDesignTimeSource { get { return generatesSharedDesignTimeSource; } set { generatesSharedDesignTimeSource = value; } } /// <summary> /// UseDesignTimeCompilationFlag reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> public int UseDesignTimeCompilationFlag { get { return useDesignTimeCompilationFlag; } set { useDesignTimeCompilationFlag = value; } } /// <summary> /// Generator Class ID. /// </summary> public Guid GeneratorClsid { get { return generatorClsid; } set { generatorClsid = value; } } #endregion } #endregion #region fields /// <summary> /// Base generator registry key for MPF based project /// </summary> private RegistryKey baseGeneratorRegistryKey; /// <summary> /// CLSID reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string GeneratorClsid = "CLSID"; /// <summary> /// GeneratesDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string GeneratesDesignTimeSource = "GeneratesDesignTimeSource"; /// <summary> /// GeneratesSharedDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string GeneratesSharedDesignTimeSource = "GeneratesSharedDesignTimeSource"; /// <summary> /// UseDesignTimeCompilationFlag reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string UseDesignTimeCompilationFlag = "UseDesignTimeCompilationFlag"; /// <summary> /// Caches all the generators registered for the project type. /// </summary> private Dictionary<string, GeneratorMetaData> generatorsMap = new Dictionary<string, GeneratorMetaData>(); /// <summary> /// The project type guid of the associated project. /// </summary> private Guid projectType; /// <summary> /// A service provider /// </summary> private System.IServiceProvider serviceProvider; #endregion #region ctors /// <summary> /// Constructor for SingleFileGeneratorFactory /// </summary> /// <param name="projectGuid">The project type guid of the associated project.</param> /// <param name="serviceProvider">A service provider.</param> public SingleFileGeneratorFactory(Guid projectType, System.IServiceProvider serviceProvider) { this.projectType = projectType; this.serviceProvider = serviceProvider; } #endregion #region properties /// <summary> /// Defines the project type guid of the associated project. /// </summary> public Guid ProjectGuid { get { return this.projectType; } set { this.projectType = value; } } /// <summary> /// Defines an associated service provider. /// </summary> public System.IServiceProvider ServiceProvider { get { return this.serviceProvider; } set { this.serviceProvider = value; } } #endregion #region IVsSingleFileGeneratorFactory Helpers /// <summary> /// Returns the project generator key under [VS-ConfigurationRoot]]\Generators /// </summary> private SettingsStore SettingsManager { get { var settingsManager = new ShellSettingsManager(PowerShellToolsPackage.Instance); return settingsManager.GetReadOnlySettingsStore(SettingsScope.Configuration); } } private string StorePath { get { return "Generators\\" + this.ProjectGuid.ToString("B"); } } /// <summary> /// Returns the local registry instance /// </summary> private ILocalRegistry LocalRegistry { get { return this.serviceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry; } } #endregion #region IVsSingleFileGeneratorFactory Members /// <summary> /// Creates an instance of the single file generator requested /// </summary> /// <param name="progId">prog id of the generator to be created. For e.g HKLM\SOFTWARE\Microsoft\VisualStudio\9.0Exp\Generators\[prjfacguid]\[wszProgId]</param> /// <param name="generatesDesignTimeSource">GeneratesDesignTimeSource key value</param> /// <param name="generatesSharedDesignTimeSource">GeneratesSharedDesignTimeSource key value</param> /// <param name="useTempPEFlag">UseDesignTimeCompilationFlag key value</param> /// <param name="generate">IVsSingleFileGenerator interface</param> /// <returns>S_OK if succesful</returns> public virtual int CreateGeneratorInstance(string progId, out int generatesDesignTimeSource, out int generatesSharedDesignTimeSource, out int useTempPEFlag, out IVsSingleFileGenerator generate) { Guid genGuid; ErrorHandler.ThrowOnFailure(this.GetGeneratorInformation(progId, out generatesDesignTimeSource, out generatesSharedDesignTimeSource, out useTempPEFlag, out genGuid)); //Create the single file generator and pass it out. Check to see if it is in the cache if(!this.generatorsMap.ContainsKey(progId) || ((this.generatorsMap[progId]).Generator == null)) { Guid riid = VSConstants.IID_IUnknown; uint dwClsCtx = (uint)CLSCTX.CLSCTX_INPROC_SERVER; IntPtr genIUnknown = IntPtr.Zero; //create a new one. ErrorHandler.ThrowOnFailure(this.LocalRegistry.CreateInstance(genGuid, null, ref riid, dwClsCtx, out genIUnknown)); if(genIUnknown != IntPtr.Zero) { try { object generator = Marshal.GetObjectForIUnknown(genIUnknown); //Build the generator meta data object and cache it. GeneratorMetaData genData = new GeneratorMetaData(); genData.GeneratesDesignTimeSource = generatesDesignTimeSource; genData.GeneratesSharedDesignTimeSource = generatesSharedDesignTimeSource; genData.UseDesignTimeCompilationFlag = useTempPEFlag; genData.GeneratorClsid = genGuid; genData.Generator = generator; this.generatorsMap[progId] = genData; } finally { Marshal.Release(genIUnknown); } } } generate = (this.generatorsMap[progId]).Generator as IVsSingleFileGenerator; return VSConstants.S_OK; } /// <summary> /// Gets the default generator based on the file extension. HKLM\Software\Microsoft\VS\9.0\Generators\[prjfacguid]\.extension /// </summary> /// <param name="filename">File name with extension</param> /// <param name="progID">The generator prog ID</param> /// <returns>S_OK if successful</returns> public virtual int GetDefaultGenerator(string filename, out string progID) { progID = ""; return VSConstants.E_NOTIMPL; } /// <summary> /// Gets the generator information. /// </summary> /// <param name="progId">prog id of the generator to be created. For e.g HKLM\SOFTWARE\Microsoft\VisualStudio\9.0Exp\Generators\[prjfacguid]\[wszProgId]</param> /// <param name="generatesDesignTimeSource">GeneratesDesignTimeSource key value</param> /// <param name="generatesSharedDesignTimeSource">GeneratesSharedDesignTimeSource key value</param> /// <param name="useTempPEFlag">UseDesignTimeCompilationFlag key value</param> /// <param name="guiddGenerator">CLSID key value</param> /// <returns>S_OK if succesful</returns> public virtual int GetGeneratorInformation(string progId, out int generatesDesignTimeSource, out int generatesSharedDesignTimeSource, out int useTempPEFlag, out Guid guidGenerator) { RegistryKey genKey; generatesDesignTimeSource = -1; generatesSharedDesignTimeSource = -1; useTempPEFlag = -1; guidGenerator = Guid.Empty; if(string.IsNullOrEmpty(progId)) return VSConstants.S_FALSE; //Create the single file generator and pass it out. if(!this.generatorsMap.ContainsKey(progId)) { var generatorPath = StorePath + "\\" + progId; var properties = SettingsManager.GetPropertyNames(generatorPath); //Get the CLSID string guid = properties.Any(m => m == GeneratorClsid) ? SettingsManager.GetString(generatorPath, GeneratorClsid) : string.Empty; if (string.IsNullOrEmpty(guid)) return VSConstants.S_FALSE; GeneratorMetaData genData = new GeneratorMetaData(); genData.GeneratorClsid = guidGenerator = new Guid(guid); //Get the GeneratesDesignTimeSource flag. Assume 0 if not present. genData.GeneratesDesignTimeSource = generatesDesignTimeSource = properties.Any(m => m == GeneratesDesignTimeSource) ? SettingsManager.GetInt32(generatorPath, GeneratesDesignTimeSource) : 0; //Get the GeneratesSharedDesignTimeSource flag. Assume 0 if not present. genData.GeneratesSharedDesignTimeSource = generatesSharedDesignTimeSource = properties.Any(m => m == GeneratesSharedDesignTimeSource) ? SettingsManager.GetInt32(generatorPath, GeneratesSharedDesignTimeSource) : 0; //Get the UseDesignTimeCompilationFlag flag. Assume 0 if not present. genData.UseDesignTimeCompilationFlag = useTempPEFlag = properties.Any(m => m == UseDesignTimeCompilationFlag) ? SettingsManager.GetInt32(generatorPath, UseDesignTimeCompilationFlag) : 0; this.generatorsMap.Add(progId, genData); } else { GeneratorMetaData genData = this.generatorsMap[progId]; generatesDesignTimeSource = genData.GeneratesDesignTimeSource; //Get the GeneratesSharedDesignTimeSource flag. Assume 0 if not present. generatesSharedDesignTimeSource = genData.GeneratesSharedDesignTimeSource; //Get the UseDesignTimeCompilationFlag flag. Assume 0 if not present. useTempPEFlag = genData.UseDesignTimeCompilationFlag; //Get the CLSID guidGenerator = genData.GeneratorClsid; } return VSConstants.S_OK; } #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.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ReplicationProtectionContainerMappingsOperations. /// </summary> public static partial class ReplicationProtectionContainerMappingsOperationsExtensions { /// <summary> /// Remove protection container mapping. /// </summary> /// <remarks> /// The operation to delete or remove a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='removalInput'> /// Removal input. /// </param> public static void Delete(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput removalInput) { operations.DeleteAsync(fabricName, protectionContainerName, mappingName, removalInput).GetAwaiter().GetResult(); } /// <summary> /// Remove protection container mapping. /// </summary> /// <remarks> /// The operation to delete or remove a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='removalInput'> /// Removal input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput removalInput, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, removalInput, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets a protection container mapping/ /// </summary> /// <remarks> /// Gets the details of a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection Container mapping name. /// </param> public static ProtectionContainerMapping Get(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName) { return operations.GetAsync(fabricName, protectionContainerName, mappingName).GetAwaiter().GetResult(); } /// <summary> /// Gets a protection container mapping/ /// </summary> /// <remarks> /// Gets the details of a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection Container mapping name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainerMapping> GetAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create protection container mapping. /// </summary> /// <remarks> /// The operation to create a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='creationInput'> /// Mapping creation input. /// </param> public static ProtectionContainerMapping Create(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput creationInput) { return operations.CreateAsync(fabricName, protectionContainerName, mappingName, creationInput).GetAwaiter().GetResult(); } /// <summary> /// Create protection container mapping. /// </summary> /// <remarks> /// The operation to create a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='creationInput'> /// Mapping creation input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainerMapping> CreateAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput creationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, creationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Purge protection container mapping. /// </summary> /// <remarks> /// The operation to purge(force delete) a protection container mapping /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> public static void Purge(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName) { operations.PurgeAsync(fabricName, protectionContainerName, mappingName).GetAwaiter().GetResult(); } /// <summary> /// Purge protection container mapping. /// </summary> /// <remarks> /// The operation to purge(force delete) a protection container mapping /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PurgeAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PurgeWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the list of protection container mappings for a protection container. /// </summary> /// <remarks> /// Lists the protection container mappings for a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> public static IPage<ProtectionContainerMapping> ListByReplicationProtectionContainers(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName) { return operations.ListByReplicationProtectionContainersAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of protection container mappings for a protection container. /// </summary> /// <remarks> /// Lists the protection container mappings for a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainerMapping>> ListByReplicationProtectionContainersAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationProtectionContainersWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of all protection container mappings in a vault. /// </summary> /// <remarks> /// Lists the protection container mappings in the vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ProtectionContainerMapping> List(this IReplicationProtectionContainerMappingsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all protection container mappings in a vault. /// </summary> /// <remarks> /// Lists the protection container mappings in the vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainerMapping>> ListAsync(this IReplicationProtectionContainerMappingsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Remove protection container mapping. /// </summary> /// <remarks> /// The operation to delete or remove a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='removalInput'> /// Removal input. /// </param> public static void BeginDelete(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput removalInput) { operations.BeginDeleteAsync(fabricName, protectionContainerName, mappingName, removalInput).GetAwaiter().GetResult(); } /// <summary> /// Remove protection container mapping. /// </summary> /// <remarks> /// The operation to delete or remove a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='removalInput'> /// Removal input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput removalInput, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, removalInput, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Create protection container mapping. /// </summary> /// <remarks> /// The operation to create a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='creationInput'> /// Mapping creation input. /// </param> public static ProtectionContainerMapping BeginCreate(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput creationInput) { return operations.BeginCreateAsync(fabricName, protectionContainerName, mappingName, creationInput).GetAwaiter().GetResult(); } /// <summary> /// Create protection container mapping. /// </summary> /// <remarks> /// The operation to create a protection container mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='creationInput'> /// Mapping creation input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainerMapping> BeginCreateAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput creationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, creationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Purge protection container mapping. /// </summary> /// <remarks> /// The operation to purge(force delete) a protection container mapping /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> public static void BeginPurge(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName) { operations.BeginPurgeAsync(fabricName, protectionContainerName, mappingName).GetAwaiter().GetResult(); } /// <summary> /// Purge protection container mapping. /// </summary> /// <remarks> /// The operation to purge(force delete) a protection container mapping /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginPurgeAsync(this IReplicationProtectionContainerMappingsOperations operations, string fabricName, string protectionContainerName, string mappingName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginPurgeWithHttpMessagesAsync(fabricName, protectionContainerName, mappingName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the list of protection container mappings for a protection container. /// </summary> /// <remarks> /// Lists the protection container mappings for a protection container. /// </remarks> /// <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<ProtectionContainerMapping> ListByReplicationProtectionContainersNext(this IReplicationProtectionContainerMappingsOperations operations, string nextPageLink) { return operations.ListByReplicationProtectionContainersNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of protection container mappings for a protection container. /// </summary> /// <remarks> /// Lists the protection container mappings for a protection container. /// </remarks> /// <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<ProtectionContainerMapping>> ListByReplicationProtectionContainersNextAsync(this IReplicationProtectionContainerMappingsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationProtectionContainersNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of all protection container mappings in a vault. /// </summary> /// <remarks> /// Lists the protection container mappings in the vault. /// </remarks> /// <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<ProtectionContainerMapping> ListNext(this IReplicationProtectionContainerMappingsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all protection container mappings in a vault. /// </summary> /// <remarks> /// Lists the protection container mappings in the vault. /// </remarks> /// <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<ProtectionContainerMapping>> ListNextAsync(this IReplicationProtectionContainerMappingsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
//----------------------------------------------------------------------- // <copyright file="BasicTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #endif namespace Csla.Test.Basic { [TestClass] public class BasicTests { [TestMethod] public void TestNotUndoableField() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.DataBinding.ParentEntity p = Csla.Test.DataBinding.ParentEntity.NewParentEntity(); p.NotUndoable = "something"; p.Data = "data"; p.BeginEdit(); p.NotUndoable = "something else"; p.Data = "new data"; p.CancelEdit(); //NotUndoable property points to a private field marked with [NotUndoable()] //so its state is never copied when BeginEdit() is called Assert.AreEqual("something else", p.NotUndoable); //the Data property points to a field that is undoable, so it reverts Assert.AreEqual("data", p.Data); } [TestMethod] public void TestReadOnlyList() { //ReadOnlyList list = ReadOnlyList.GetReadOnlyList(); // Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["ReadOnlyList"]); } [TestMethod] public void TestNameValueList() { NameValueListObj nvList = NameValueListObj.GetNameValueListObj(); Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["NameValueListObj"]); Assert.AreEqual("element_1", nvList[1].Value); //won't work, because IsReadOnly is set to true after object is populated in the for //loop in DataPortal_Fetch //NameValueListObj.NameValuePair newPair = new NameValueListObj.NameValuePair(45, "something"); //nvList.Add(newPair); //Assert.AreEqual("something", nvList[45].Value); } [TestMethod] public void TestCommandBase() { Csla.ApplicationContext.GlobalContext.Clear(); CommandObject obj = new CommandObject(); Assert.AreEqual("Executed", obj.ExecuteServerCode().AProperty); } [TestMethod] public void CreateGenRoot() { Csla.ApplicationContext.GlobalContext.Clear(); GenRoot root; root = GenRoot.NewRoot(); Assert.IsNotNull(root); Assert.AreEqual("<new>", root.Data); Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["GenRoot"]); Assert.AreEqual(true, root.IsNew); Assert.AreEqual(false, root.IsDeleted); Assert.AreEqual(true, root.IsDirty); } [TestMethod] public void InheritanceUndo() { Csla.ApplicationContext.GlobalContext.Clear(); GenRoot root; root = GenRoot.NewRoot(); root.BeginEdit(); root.Data = "abc"; root.CancelEdit(); Csla.ApplicationContext.GlobalContext.Clear(); root = GenRoot.NewRoot(); root.BeginEdit(); root.Data = "abc"; root.ApplyEdit(); } [TestMethod] public void CreateRoot() { Csla.ApplicationContext.GlobalContext.Clear(); Root root; root = Csla.Test.Basic.Root.NewRoot(); Assert.IsNotNull(root); Assert.AreEqual("<new>", root.Data); Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["Root"]); Assert.AreEqual(true, root.IsNew); Assert.AreEqual(false, root.IsDeleted); Assert.AreEqual(true, root.IsDirty); } [TestMethod] public void AddChild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); Assert.AreEqual(1, root.Children.Count); Assert.AreEqual("1", root.Children[0].Data); } [TestMethod] public void AddRemoveChild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.Children.Remove(root.Children[0]); Assert.AreEqual(0, root.Children.Count); } [TestMethod] public void AddRemoveAddChild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.BeginEdit(); root.Children.Remove(root.Children[0]); root.Children.Add("2"); root.CancelEdit(); Assert.AreEqual(1, root.Children.Count); Assert.AreEqual("1", root.Children[0].Data); } [TestMethod] public void AddGrandChild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); Child child = root.Children[0]; child.GrandChildren.Add("1"); Assert.AreEqual(1, child.GrandChildren.Count); Assert.AreEqual("1", child.GrandChildren[0].Data); } [TestMethod] public void AddRemoveGrandChild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); Child child = root.Children[0]; child.GrandChildren.Add("1"); child.GrandChildren.Remove(child.GrandChildren[0]); Assert.AreEqual(0, child.GrandChildren.Count); } ///<remarks>"the non-generic method AreEqual cannot be used with type arguments" - though ///it is used with type arguments in BasicTests.vb ///</remarks> //[TestMethod] //public void CloneGraph() //{ // Csla.ApplicationContext.GlobalContext.Clear(); // Root root = Csla.Test.Basic.Root.NewRoot(); // FormSimulator form = new FormSimulator(root); // SerializableListener listener = new SerializableListener(root); // root.Children.Add("1"); // Child child = root.Children[0]; // Child.GrandChildren.Add("1"); // Assert.AreEqual<int>(1, child.GrandChildren.Count); // Assert.AreEqual<string>("1", child.GrandChildren[0].Data); // Root clone = ((Root)(root.Clone())); // child = clone.Children[0]; // Assert.AreEqual<int>(1, child.GrandChildren.Count); // Assert.AreEqual<string>("1", child.GrandChildren[0].Data); // Assert.AreEqual<string>("root Deserialized", ((string)(Csla.ApplicationContext.GlobalContext["Deserialized"]))); // Assert.AreEqual<string>("GC Deserialized", ((string)(Csla.ApplicationContext.GlobalContext["GCDeserialized"]))); //} [TestMethod] public void ClearChildList() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("A"); root.Children.Add("B"); root.Children.Add("C"); root.Children.Clear(); Assert.AreEqual(0, root.Children.Count, "Count should be 0"); Assert.AreEqual(3, root.Children.DeletedCount, "Deleted count should be 3"); } [TestMethod] public void NestedAddAcceptchild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.BeginEdit(); root.Children.Add("A"); root.BeginEdit(); root.Children.Add("B"); root.BeginEdit(); root.Children.Add("C"); root.ApplyEdit(); root.ApplyEdit(); root.ApplyEdit(); Assert.AreEqual(3, root.Children.Count); } [TestMethod] public void NestedAddDeleteAcceptChild() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.BeginEdit(); root.Children.Add("A"); root.BeginEdit(); root.Children.Add("B"); root.BeginEdit(); root.Children.Add("C"); Child childC = root.Children[2]; Assert.AreEqual(true, root.Children.Contains(childC), "Child should be in collection"); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); Assert.AreEqual(false, root.Children.Contains(childC), "Child should not be in collection"); Assert.AreEqual(true, root.Children.ContainsDeleted(childC), "Deleted child should be in deleted collection"); root.ApplyEdit(); Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after first applyedit"); root.ApplyEdit(); Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after ApplyEdit"); root.ApplyEdit(); Assert.AreEqual(0, root.Children.Count, "No children should remain"); Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after third applyedit"); } [TestMethod] public void BasicEquality() { Csla.ApplicationContext.GlobalContext.Clear(); Root r1 = Root.NewRoot(); r1.Data = "abc"; Assert.AreEqual(true, r1.Equals(r1), "objects should be equal on instance compare"); Assert.AreEqual(true, Equals(r1, r1), "objects should be equal on static compare"); Csla.ApplicationContext.GlobalContext.Clear(); Root r2 = Root.NewRoot(); r2.Data = "xyz"; Assert.AreEqual(false, r1.Equals(r2), "objects should not be equal"); Assert.AreEqual(false, Equals(r1, r2), "objects should not be equal"); Assert.AreEqual(false, r1.Equals(null), "Objects should not be equal"); Assert.AreEqual(false, Equals(r1, null), "Objects should not be equal"); Assert.AreEqual(false, Equals(null, r2), "Objects should not be equal"); } [TestMethod] public void ChildEquality() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Root.NewRoot(); root.Children.Add("abc"); root.Children.Add("xyz"); root.Children.Add("123"); Child c1 = root.Children[0]; Child c2 = root.Children[1]; Child c3 = root.Children[2]; root.Children.Remove(c3); Assert.AreEqual(true, c1.Equals(c1), "objects should be equal"); Assert.AreEqual(true, Equals(c1, c1), "objects should be equal"); Assert.AreEqual(false, c1.Equals(c2), "objects should not be equal"); Assert.AreEqual(false, Equals(c1, c2), "objects should not be equal"); Assert.AreEqual(false, c1.Equals(null), "objects should not be equal"); Assert.AreEqual(false, Equals(c1, null), "objects should not be equal"); Assert.AreEqual(false, Equals(null, c2), "objects should not be equal"); Assert.AreEqual(true, root.Children.Contains(c1), "Collection should contain c1"); Assert.AreEqual(true, root.Children.Contains(c2), "collection should contain c2"); Assert.AreEqual(false, root.Children.Contains(c3), "collection should not contain c3"); Assert.AreEqual(true, root.Children.ContainsDeleted(c3), "Deleted collection should contain c3"); } [TestMethod] public void DeletedListTest() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.Children.Add("2"); root.Children.Add("3"); root.BeginEdit(); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); root.ApplyEdit(); Root copy = root.Clone(); var deleted = (List<Child>)(root.Children.GetType().GetProperty("DeletedList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase).GetValue(copy.Children, null)); Assert.AreEqual(2, deleted.Count); Assert.AreEqual("1", deleted[0].Data); Assert.AreEqual("2", deleted[1].Data); Assert.AreEqual(1, root.Children.Count); } [TestMethod] public void DeletedListTestWithCancel() { Csla.ApplicationContext.GlobalContext.Clear(); Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.Children.Add("2"); root.Children.Add("3"); root.BeginEdit(); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); Root copy = root.Clone(); List<Child> deleted = (List<Child>)(root.Children.GetType().GetProperty("DeletedList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase).GetValue(copy.Children, null)); Assert.AreEqual(2, deleted.Count); Assert.AreEqual("1", deleted[0].Data); Assert.AreEqual("2", deleted[1].Data); Assert.AreEqual(1, root.Children.Count); root.CancelEdit(); deleted = (List<Child>)(root.Children.GetType().GetProperty("DeletedList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase).GetValue(root.Children, null)); Assert.AreEqual(0, deleted.Count); Assert.AreEqual(3, root.Children.Count); } [TestMethod] public void SuppressListChangedEventsDoNotRaiseCollectionChanged() { bool changed = false; var obj = new RootList(); obj.ListChanged += (o, e) => { changed = true; }; var child = new RootListChild(); // object is marked as child Assert.IsTrue(obj.RaiseListChangedEvents); using (obj.SuppressListChangedEvents) { Assert.IsFalse(obj.RaiseListChangedEvents); obj.Add(child); } Assert.IsFalse(changed, "Should not raise ListChanged event"); Assert.IsTrue(obj.RaiseListChangedEvents); Assert.AreEqual(child, obj[0]); } [TestCleanup] public void ClearContextsAfterEachTest() { Csla.ApplicationContext.GlobalContext.Clear(); } } public class FormSimulator { private Core.BusinessBase _obj; public FormSimulator(Core.BusinessBase obj) { this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged); this._obj = obj; } private void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {} } [Serializable()] public class SerializableListener { private Core.BusinessBase _obj; public SerializableListener(Core.BusinessBase obj) { this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged); this._obj = obj; } public void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { } } }
/* * 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.IO; using System.Net; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Serialization; using log4net; namespace OpenSim.Framework.Servers.HttpServer { public class RestSessionObject<TRequest> { private string sid; private string aid; private TRequest request_body; public string SessionID { get { return sid; } set { sid = value; } } public string AvatarID { get { return aid; } set { aid = value; } } public TRequest Body { get { return request_body; } set { request_body = value; } } } public class SynchronousRestSessionObjectPoster<TRequest, TResponse> { public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid) { RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>(); sobj.SessionID = sid; sobj.AvatarID = aid; sobj.Body = obj; Type type = typeof(RestSessionObject<TRequest>); WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; request.ContentType = "text/xml"; request.Timeout = 20000; MemoryStream buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, sobj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; Stream requestStream = request.GetRequestStream(); requestStream.Write(buffer.ToArray(), 0, length); buffer.Close(); requestStream.Close(); TResponse deserial = default(TResponse); using (WebResponse resp = request.GetResponse()) { XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); using (Stream respStream = resp.GetResponseStream()) deserial = (TResponse)deserializer.Deserialize(respStream); } return deserial; } } public class RestSessionObjectPosterResponse<TRequest, TResponse> { public ReturnResponse<TResponse> ResponseCallback; public void BeginPostObject(string requestUrl, TRequest obj, string sid, string aid) { BeginPostObject("POST", requestUrl, obj, sid, aid); } public void BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid) { RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>(); sobj.SessionID = sid; sobj.AvatarID = aid; sobj.Body = obj; Type type = typeof(RestSessionObject<TRequest>); WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; request.ContentType = "text/xml"; request.Timeout = 10000; MemoryStream buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, sobj); writer.Flush(); } buffer.Close(); int length = (int)buffer.Length; request.ContentLength = length; Stream requestStream = request.GetRequestStream(); requestStream.Write(buffer.ToArray(), 0, length); requestStream.Close(); // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request); request.BeginGetResponse(AsyncCallback, request); } private void AsyncCallback(IAsyncResult result) { WebRequest request = (WebRequest)result.AsyncState; using (WebResponse resp = request.EndGetResponse(result)) { TResponse deserial; XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); Stream stream = resp.GetResponseStream(); // This is currently a bad debug stanza since it gobbles us the response... // StreamReader reader = new StreamReader(stream); // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd()); deserial = (TResponse)deserializer.Deserialize(stream); if (stream != null) stream.Close(); if (deserial != null && ResponseCallback != null) { ResponseCallback(deserial); } } } } public delegate bool CheckIdentityMethod(string sid, string aid); public class RestDeserialiseSecureHandler<TRequest, TResponse> : BaseRequestHandler, IStreamHandler where TRequest : new() { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private RestDeserialiseMethod<TRequest, TResponse> m_method; private CheckIdentityMethod m_smethod; public RestDeserialiseSecureHandler( string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckIdentityMethod smethod) : base(httpMethod, path) { m_smethod = smethod; m_method = method; } public void Handle(string path, Stream request, Stream responseStream, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { RestSessionObject<TRequest> deserial = default(RestSessionObject<TRequest>); bool fail = false; using (XmlTextReader xmlReader = new XmlTextReader(request)) { try { XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>)); deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader); } catch (Exception e) { m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e); fail = true; } } TResponse response = default(TResponse); if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID)) { response = m_method(deserial.Body); } using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream)) { XmlSerializer serializer = new XmlSerializer(typeof(TResponse)); serializer.Serialize(xmlWriter, response); } } } public delegate bool CheckTrustedSourceMethod(IPEndPoint peer); public class RestDeserialiseTrustedHandler<TRequest, TResponse> : BaseRequestHandler, IStreamHandler where TRequest : new() { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The operation to perform once trust has been established. /// </summary> private RestDeserialiseMethod<TRequest, TResponse> m_method; /// <summary> /// The method used to check whether a request is trusted. /// </summary> private CheckTrustedSourceMethod m_tmethod; public RestDeserialiseTrustedHandler(string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckTrustedSourceMethod tmethod) : base(httpMethod, path) { m_tmethod = tmethod; m_method = method; } public void Handle(string path, Stream request, Stream responseStream, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { TRequest deserial = default(TRequest); bool fail = false; using (XmlTextReader xmlReader = new XmlTextReader(request)) { try { XmlSerializer deserializer = new XmlSerializer(typeof(TRequest)); deserial = (TRequest)deserializer.Deserialize(xmlReader); } catch (Exception e) { m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e); fail = true; } } TResponse response = default(TResponse); if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint)) { response = m_method(deserial); } using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream)) { XmlSerializer serializer = new XmlSerializer(typeof(TResponse)); serializer.Serialize(xmlWriter, response); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using Xunit; using static CodeGenerator.KnownHeaders; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class HttpRequestHeadersTests { [Fact] public void InitialDictionaryIsEmpty() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); Assert.Equal(0, headers.Count); Assert.False(headers.IsReadOnly); } [Fact] public void SettingUnknownHeadersWorks() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers["custom"] = new[] { "value" }; var header = Assert.Single(headers["custom"]); Assert.Equal("value", header); } [Fact] public void SettingKnownHeadersWorks() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers["host"] = new[] { "value" }; headers["content-length"] = new[] { "0" }; var host = Assert.Single(headers["host"]); var contentLength = Assert.Single(headers["content-length"]); Assert.Equal("value", host); Assert.Equal("0", contentLength); } [Fact] public void KnownAndCustomHeaderCountAddedTogether() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers["host"] = new[] { "value" }; headers["custom"] = new[] { "value" }; headers["Content-Length"] = new[] { "0" }; Assert.Equal(3, headers.Count); } [Fact] public void TryGetValueWorksForKnownAndUnknownHeaders() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); StringValues value; Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers["host"] = new[] { "value" }; Assert.True(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers["custom"] = new[] { "value" }; Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers["Content-Length"] = new[] { "0" }; Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); } [Fact] public void SameExceptionThrownForMissingKey() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); Assert.Throws<KeyNotFoundException>(() => headers["custom"]); Assert.Throws<KeyNotFoundException>(() => headers["host"]); Assert.Throws<KeyNotFoundException>(() => headers["Content-Length"]); } [Fact] public void EntriesCanBeEnumeratedAfterResets() { HttpRequestHeaders headers = new HttpRequestHeaders(); EnumerateEntries((IHeaderDictionary)headers); headers.Reset(); EnumerateEntries((IDictionary<string, StringValues>)headers); headers.Reset(); EnumerateEntries((IHeaderDictionary)headers); headers.Reset(); EnumerateEntries((IDictionary<string, StringValues>)headers); } [Fact] public void EnumeratorNotReusedBeforeReset() { HttpRequestHeaders headers = new HttpRequestHeaders(); IEnumerable<KeyValuePair<string, StringValues>> enumerable = headers; var enumerator0 = enumerable.GetEnumerator(); var enumerator1 = enumerable.GetEnumerator(); Assert.NotSame(enumerator0, enumerator1); } [Fact] public void EnumeratorReusedAfterReset() { HttpRequestHeaders headers = new HttpRequestHeaders(); IEnumerable<KeyValuePair<string, StringValues>> enumerable = headers; var enumerator0 = enumerable.GetEnumerator(); headers.Reset(); var enumerator1 = enumerable.GetEnumerator(); Assert.Same(enumerator0, enumerator1); } private static void EnumerateEntries(IHeaderDictionary headers) { var v1 = new[] { "localhost" }; var v2 = new[] { "0" }; var v3 = new[] { "value" }; headers.Host = v1; headers.ContentLength = 0; headers["custom"] = v3; Assert.Equal( new[] { new KeyValuePair<string, StringValues>("Host", v1), new KeyValuePair<string, StringValues>("Content-Length", v2), new KeyValuePair<string, StringValues>("custom", v3), }, headers); } private static void EnumerateEntries(IDictionary<string, StringValues> headers) { var v1 = new[] { "localhost" }; var v2 = new[] { "0" }; var v3 = new[] { "value" }; headers["host"] = v1; headers["Content-Length"] = v2; headers["custom"] = v3; Assert.Equal( new[] { new KeyValuePair<string, StringValues>("Host", v1), new KeyValuePair<string, StringValues>("Content-Length", v2), new KeyValuePair<string, StringValues>("custom", v3), }, headers); } [Fact] public void KeysAndValuesCanBeEnumerated() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); StringValues v1 = new[] { "localhost" }; StringValues v2 = new[] { "0" }; StringValues v3 = new[] { "value" }; headers["host"] = v1; headers["Content-Length"] = v2; headers["custom"] = v3; Assert.Equal<string>( new[] { "Host", "Content-Length", "custom" }, headers.Keys); Assert.Equal<StringValues>( new[] { v1, v2, v3 }, headers.Values); } [Fact] public void ContainsAndContainsKeyWork() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); var kv1 = new KeyValuePair<string, StringValues>("host", new[] { "localhost" }); var kv2 = new KeyValuePair<string, StringValues>("custom", new[] { "value" }); var kv3 = new KeyValuePair<string, StringValues>("Content-Length", new[] { "0" }); var kv1b = new KeyValuePair<string, StringValues>("host", new[] { "not-localhost" }); var kv2b = new KeyValuePair<string, StringValues>("custom", new[] { "not-value" }); var kv3b = new KeyValuePair<string, StringValues>("Content-Length", new[] { "1" }); Assert.False(headers.ContainsKey("host")); Assert.False(headers.ContainsKey("custom")); Assert.False(headers.ContainsKey("Content-Length")); Assert.False(headers.Contains(kv1)); Assert.False(headers.Contains(kv2)); Assert.False(headers.Contains(kv3)); headers["host"] = kv1.Value; Assert.True(headers.ContainsKey("host")); Assert.False(headers.ContainsKey("custom")); Assert.False(headers.ContainsKey("Content-Length")); Assert.True(headers.Contains(kv1)); Assert.False(headers.Contains(kv2)); Assert.False(headers.Contains(kv3)); Assert.False(headers.Contains(kv1b)); Assert.False(headers.Contains(kv2b)); Assert.False(headers.Contains(kv3b)); headers["custom"] = kv2.Value; Assert.True(headers.ContainsKey("host")); Assert.True(headers.ContainsKey("custom")); Assert.False(headers.ContainsKey("Content-Length")); Assert.True(headers.Contains(kv1)); Assert.True(headers.Contains(kv2)); Assert.False(headers.Contains(kv3)); Assert.False(headers.Contains(kv1b)); Assert.False(headers.Contains(kv2b)); Assert.False(headers.Contains(kv3b)); headers["Content-Length"] = kv3.Value; Assert.True(headers.ContainsKey("host")); Assert.True(headers.ContainsKey("custom")); Assert.True(headers.ContainsKey("Content-Length")); Assert.True(headers.Contains(kv1)); Assert.True(headers.Contains(kv2)); Assert.True(headers.Contains(kv3)); Assert.False(headers.Contains(kv1b)); Assert.False(headers.Contains(kv2b)); Assert.False(headers.Contains(kv3b)); } [Fact] public void AddWorksLikeSetAndThrowsIfKeyExists() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); StringValues value; Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers.Add("host", new[] { "localhost" }); headers.Add("custom", new[] { "value" }); headers.Add("Content-Length", new[] { "0" }); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.Throws<ArgumentException>(() => headers.Add("host", new[] { "localhost" })); Assert.Throws<ArgumentException>(() => headers.Add("custom", new[] { "value" })); Assert.Throws<ArgumentException>(() => headers.Add("Content-Length", new[] { "0" })); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); } [Fact] public void ClearRemovesAllHeaders() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers.Add("host", new[] { "localhost" }); headers.Add("custom", new[] { "value" }); headers.Add("Content-Length", new[] { "0" }); StringValues value; Assert.Equal(3, headers.Count); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); headers.Clear(); Assert.Equal(0, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); } [Fact] public void RemoveTakesHeadersOutOfDictionary() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers.Add("host", new[] { "localhost" }); headers.Add("custom", new[] { "value" }); headers.Add("Content-Length", new[] { "0" }); StringValues value; Assert.Equal(3, headers.Count); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.True(headers.Remove("host")); Assert.False(headers.Remove("host")); Assert.Equal(2, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.Remove("custom")); Assert.False(headers.Remove("custom")); Assert.Equal(1, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.True(headers.Remove("Content-Length")); Assert.False(headers.Remove("Content-Length")); Assert.Equal(0, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); } [Fact] public void CopyToMovesDataIntoArray() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers.Add("host", new[] { "localhost" }); headers.Add("Content-Length", new[] { "0" }); headers.Add("custom", new[] { "value" }); var entries = new KeyValuePair<string, StringValues>[5]; headers.CopyTo(entries, 1); Assert.Null(entries[0].Key); Assert.Equal(new StringValues(), entries[0].Value); Assert.Equal("Host", entries[1].Key); Assert.Equal(new[] { "localhost" }, entries[1].Value); Assert.Equal("Content-Length", entries[2].Key); Assert.Equal(new[] { "0" }, entries[2].Value); Assert.Equal("custom", entries[3].Key); Assert.Equal(new[] { "value" }, entries[3].Value); Assert.Null(entries[4].Key); Assert.Equal(new StringValues(), entries[4].Value); } [Fact] public void AppendThrowsWhenHeaderNameContainsNonASCIICharacters() { var headers = new HttpRequestHeaders(); const string key = "\u00141\u00F3d\017c"; #pragma warning disable CS0618 // Type or member is obsolete var exception = Assert.Throws<BadHttpRequestException>( #pragma warning restore CS0618 // Type or member is obsolete () => headers.Append(Encoding.Latin1.GetBytes(key), Encoding.ASCII.GetBytes("value"), checkForNewlineChars : false)); Assert.Equal(StatusCodes.Status400BadRequest, exception.StatusCode); } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseOnlyWhenAllowed(bool reuseValue, KnownHeader header) { const string HeaderValue = "Hello"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue, HeaderValue); Assert.Equal(HeaderValue, values.PrevHeaderValue); Assert.NotSame(HeaderValue, values.PrevHeaderValue); Assert.Equal(HeaderValue, values.NextHeaderValue); Assert.NotSame(HeaderValue, values.NextHeaderValue); Assert.Equal(values.PrevHeaderValue, values.NextHeaderValue); if (reuseValue) { // When materialized string is reused previous and new should be the same object Assert.Same(values.PrevHeaderValue, values.NextHeaderValue); } else { // When materialized string is not reused previous and new should be the different objects Assert.NotSame(values.PrevHeaderValue, values.NextHeaderValue); } } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseChangedValuesOverwrite(bool reuseValue, KnownHeader header) { const string HeaderValue1 = "Hello1"; const string HeaderValue2 = "Hello2"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue1, HeaderValue2); Assert.Equal(HeaderValue1, values.PrevHeaderValue); Assert.NotSame(HeaderValue1, values.PrevHeaderValue); Assert.Equal(HeaderValue2, values.NextHeaderValue); Assert.NotSame(HeaderValue2, values.NextHeaderValue); Assert.NotEqual(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseMissingValuesClear(bool reuseValue, KnownHeader header) { const string HeaderValue1 = "Hello1"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue1, nextValue: null); Assert.Equal(HeaderValue1, values.PrevHeaderValue); Assert.NotSame(HeaderValue1, values.PrevHeaderValue); Assert.Equal(string.Empty, values.NextHeaderValue); Assert.NotEqual(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseNeverWhenNotAscii(bool reuseValue, KnownHeader header) { const string HeaderValue = "Hello \u03a0"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue, HeaderValue); Assert.Equal(HeaderValue, values.PrevHeaderValue); Assert.NotSame(HeaderValue, values.PrevHeaderValue); Assert.Equal(HeaderValue, values.NextHeaderValue); Assert.NotSame(HeaderValue, values.NextHeaderValue); Assert.Equal(values.PrevHeaderValue, values.NextHeaderValue); Assert.NotSame(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseLatin1NotConfusedForUtf16AndStillRejected(bool reuseValue, KnownHeader header) { var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); var headerValue = new char[127]; // 64 + 32 + 16 + 8 + 4 + 2 + 1 for (var i = 0; i < headerValue.Length; i++) { headerValue[i] = 'a'; } for (var i = 0; i < headerValue.Length; i++) { // Set non-ascii Latin char that is valid Utf16 when widened; but not a valid utf8 -> utf16 conversion. headerValue[i] = '\u00a3'; for (var mode = 0; mode <= 1; mode++) { string headerValueUtf16Latin1CrossOver; if (mode == 0) { // Full length headerValueUtf16Latin1CrossOver = new string(headerValue); } else { // Truncated length (to ensure different paths from changing lengths in matching) headerValueUtf16Latin1CrossOver = new string(headerValue.AsSpan().Slice(0, i + 1)); } headers.Reset(); var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var prevSpan = Encoding.UTF8.GetBytes(headerValueUtf16Latin1CrossOver).AsSpan(); headers.Append(headerName, prevSpan, checkForNewlineChars : false); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.Equal(headerValueUtf16Latin1CrossOver, prevHeaderValue); Assert.NotSame(headerValueUtf16Latin1CrossOver, prevHeaderValue); headers.Reset(); Assert.Throws<InvalidOperationException>(() => { var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var nextSpan = Encoding.Latin1.GetBytes(headerValueUtf16Latin1CrossOver).AsSpan(); Assert.False(nextSpan.SequenceEqual(Encoding.ASCII.GetBytes(headerValueUtf16Latin1CrossOver))); headers.Append(headerName, nextSpan, checkForNewlineChars : false); }); } // Reset back to Ascii headerValue[i] = 'a'; } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void Latin1ValuesAcceptedInLatin1ModeButNotReused(bool reuseValue, KnownHeader header) { var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue, _ => Encoding.Latin1); var headerValue = new char[127]; // 64 + 32 + 16 + 8 + 4 + 2 + 1 for (var i = 0; i < headerValue.Length; i++) { headerValue[i] = 'a'; } for (var i = 0; i < headerValue.Length; i++) { // Set non-ascii Latin char that is valid Utf16 when widened; but not a valid utf8 -> utf16 conversion. headerValue[i] = '\u00a3'; for (var mode = 0; mode <= 1; mode++) { string headerValueUtf16Latin1CrossOver; if (mode == 0) { // Full length headerValueUtf16Latin1CrossOver = new string(headerValue); } else { // Truncated length (to ensure different paths from changing lengths in matching) headerValueUtf16Latin1CrossOver = new string(headerValue.AsSpan().Slice(0, i + 1)); } var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var latinValueSpan = Encoding.Latin1.GetBytes(headerValueUtf16Latin1CrossOver).AsSpan(); Assert.False(latinValueSpan.SequenceEqual(Encoding.ASCII.GetBytes(headerValueUtf16Latin1CrossOver))); headers.Reset(); headers.Append(headerName, latinValueSpan, checkForNewlineChars : false); headers.OnHeadersComplete(); var parsedHeaderValue1 = ((IHeaderDictionary)headers)[header.Name].ToString(); headers.Reset(); headers.Append(headerName, latinValueSpan, checkForNewlineChars : false); headers.OnHeadersComplete(); var parsedHeaderValue2 = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.Equal(headerValueUtf16Latin1CrossOver, parsedHeaderValue1); Assert.Equal(parsedHeaderValue1, parsedHeaderValue2); Assert.NotSame(parsedHeaderValue1, parsedHeaderValue2); } // Reset back to Ascii headerValue[i] = 'a'; } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void NullCharactersRejectedInUTF8AndLatin1Mode(bool useLatin1, KnownHeader header) { var headers = new HttpRequestHeaders(encodingSelector: useLatin1 ? _ => Encoding.Latin1 : (Func<string, Encoding>)null); var valueArray = new char[127]; // 64 + 32 + 16 + 8 + 4 + 2 + 1 for (var i = 0; i < valueArray.Length; i++) { valueArray[i] = 'a'; } for (var i = 1; i < valueArray.Length; i++) { // Set non-ascii Latin char that is valid Utf16 when widened; but not a valid utf8 -> utf16 conversion. valueArray[i] = '\0'; string valueString = new string(valueArray); headers.Reset(); Assert.Throws<InvalidOperationException>(() => { var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var valueSpan = Encoding.ASCII.GetBytes(valueString).AsSpan(); headers.Append(headerName, valueSpan, checkForNewlineChars : false); }); valueArray[i] = 'a'; } } [Fact] public void CanSpecifyEncodingBasedOnHeaderName() { const string headerValue = "Hello \u03a0"; var acceptNameBytes = Encoding.ASCII.GetBytes(HeaderNames.Accept); var cookieNameBytes = Encoding.ASCII.GetBytes(HeaderNames.Cookie); var headerValueBytes = Encoding.UTF8.GetBytes(headerValue); var headers = new HttpRequestHeaders(encodingSelector: headerName => { // For known headers, the HeaderNames value is passed in. if (ReferenceEquals(headerName, HeaderNames.Accept)) { return Encoding.GetEncoding("ASCII", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); } return Encoding.UTF8; }); Assert.Throws<InvalidOperationException>(() => headers.Append(acceptNameBytes, headerValueBytes, checkForNewlineChars : false)); headers.Append(cookieNameBytes, headerValueBytes, checkForNewlineChars : false); headers.OnHeadersComplete(); var parsedAcceptHeaderValue = ((IHeaderDictionary)headers).Accept.ToString(); var parsedCookieHeaderValue = ((IHeaderDictionary)headers).Cookie.ToString(); Assert.Empty(parsedAcceptHeaderValue); Assert.Equal(headerValue, parsedCookieHeaderValue); } [Fact] public void CanSpecifyEncodingForContentLength() { var contentLengthNameBytes = Encoding.ASCII.GetBytes(HeaderNames.ContentLength); // Always 32 bits per code point, so not a superset of ASCII var contentLengthValueBytes = Encoding.UTF32.GetBytes("1337"); var headers = new HttpRequestHeaders(encodingSelector: _ => Encoding.UTF32); headers.Append(contentLengthNameBytes, contentLengthValueBytes, checkForNewlineChars : false); headers.OnHeadersComplete(); Assert.Equal(1337, headers.ContentLength); Assert.Throws<InvalidOperationException>(() => new HttpRequestHeaders().Append(contentLengthNameBytes, contentLengthValueBytes, checkForNewlineChars : false)); } [Fact] public void ValueReuseNeverWhenUnknownHeader() { const string HeaderName = "An-Unknown-Header"; const string HeaderValue = "Hello"; var headers = new HttpRequestHeaders(reuseHeaderValues: true); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(HeaderName, variant: i); var nextName = ChangeNameCase(HeaderName, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue, HeaderValue); Assert.Equal(HeaderValue, values.PrevHeaderValue); Assert.NotSame(HeaderValue, values.PrevHeaderValue); Assert.Equal(HeaderValue, values.NextHeaderValue); Assert.NotSame(HeaderValue, values.NextHeaderValue); Assert.Equal(values.PrevHeaderValue, values.NextHeaderValue); Assert.NotSame(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseEmptyAfterReset(bool reuseValue, KnownHeader header) { const string HeaderValue = "Hello"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var prevSpan = Encoding.UTF8.GetBytes(HeaderValue).AsSpan(); headers.Append(headerName, prevSpan, checkForNewlineChars : false); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(prevHeaderValue); Assert.NotEqual(string.Empty, prevHeaderValue); Assert.Equal(HeaderValue, prevHeaderValue); Assert.NotSame(HeaderValue, prevHeaderValue); Assert.Single(headers); var count = headers.Count; Assert.Equal(1, count); headers.Reset(); // Empty after reset var nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.NotEqual(HeaderValue, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); headers.OnHeadersComplete(); // Still empty after complete nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.NotEqual(HeaderValue, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void MultiValueReuseEmptyAfterReset(bool reuseValue, KnownHeader header) { const string HeaderValue1 = "Hello1"; const string HeaderValue2 = "Hello2"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var prevSpan1 = Encoding.UTF8.GetBytes(HeaderValue1).AsSpan(); var prevSpan2 = Encoding.UTF8.GetBytes(HeaderValue2).AsSpan(); headers.Append(headerName, prevSpan1, checkForNewlineChars : false); headers.Append(headerName, prevSpan2, checkForNewlineChars : false); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[header.Name]; Assert.Equal(2, prevHeaderValue.Count); Assert.NotEqual(string.Empty, prevHeaderValue.ToString()); Assert.Single(headers); var count = headers.Count; Assert.Equal(1, count); headers.Reset(); // Empty after reset var nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); headers.OnHeadersComplete(); // Still empty after complete nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); } private static (string PrevHeaderValue, string NextHeaderValue) GetHeaderValues(HttpRequestHeaders headers, string prevName, string nextName, string prevValue, string nextValue) { headers.Reset(); var headerName = Encoding.ASCII.GetBytes(prevName).AsSpan(); var prevSpan = Encoding.UTF8.GetBytes(prevValue).AsSpan(); headers.Append(headerName, prevSpan, checkForNewlineChars : false); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[prevName].ToString(); headers.Reset(); if (nextValue != null) { headerName = Encoding.ASCII.GetBytes(prevName).AsSpan(); var nextSpan = Encoding.UTF8.GetBytes(nextValue).AsSpan(); headers.Append(headerName, nextSpan, checkForNewlineChars : false); } headers.OnHeadersComplete(); var newHeaderValue = ((IHeaderDictionary)headers)[nextName].ToString(); return (prevHeaderValue, newHeaderValue); } private static string ChangeNameCase(string name, int variant) { switch ((variant / 2) % 3) { case 0: return name; case 1: return name.ToLowerInvariant(); case 2: return name.ToUpperInvariant(); } // Never reached Assert.False(true); return name; } // Content-Length is numeric not a string, so we exclude it from the string reuse tests public static IEnumerable<object[]> KnownRequestHeaders => RequestHeaders.Where(h => h.Name != "Content-Length").Select(h => new object[] { true, h }).Concat( RequestHeaders.Where(h => h.Name != "Content-Length").Select(h => new object[] { false, h })); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Globalization; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests { public class ChunkedResponseTests : LoggedTest { [Fact] public async Task ResponsesAreChunkedAutomatically() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("Hello "), 0, 6)); await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("World!"), 0, 6)); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host:", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task ResponsesAreNotChunkedAutomaticallyForHttp10Requests() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { await httpContext.Response.WriteAsync("Hello "); await httpContext.Response.WriteAsync("World!"); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.0", "Connection: keep-alive", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "", "Hello World!"); } } } [Fact] public async Task IgnoresChangesToHttpProtocol() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { httpContext.Request.Protocol = "HTTP/2"; // Doesn't support chunking. This change should be ignored. var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("Hello "), 0, 6)); await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("World!"), 0, 6)); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host:", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task ResponsesAreChunkedAutomaticallyForHttp11NonKeepAliveRequests() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { await httpContext.Response.WriteAsync("Hello "); await httpContext.Response.WriteAsync("World!"); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "Connection: close", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task ResponsesAreChunkedAutomaticallyLargeResponseWithOverloadedWriteAsync() { var testContext = new TestServiceContext(LoggerFactory); var expectedString = new string('a', 10000); await using (var server = new TestServer(async httpContext => { await httpContext.Response.WriteAsync(expectedString); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "Connection: close", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "f92", new string('a', 3986), "ff9", new string('a', 4089), "785", new string('a', 1925), "0", "", ""); } } } [Theory] [InlineData(4096)] [InlineData(10000)] [InlineData(100000)] public async Task ResponsesAreChunkedAutomaticallyLargeChunksLargeResponseWithOverloadedWriteAsync(int length) { var testContext = new TestServiceContext(LoggerFactory); var expectedString = new string('a', length); await using (var server = new TestServer(async httpContext => { await httpContext.Response.StartAsync(); var memory = httpContext.Response.BodyWriter.GetMemory(length); Assert.True(length <= memory.Length); Encoding.ASCII.GetBytes(expectedString).CopyTo(memory); httpContext.Response.BodyWriter.Advance(length); await httpContext.Response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "Connection: close", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", length.ToString("x" , CultureInfo.InvariantCulture), new string('a', length), "0", "", ""); } } } [Theory] [InlineData(1)] [InlineData(16)] [InlineData(256)] [InlineData(4096)] public async Task ResponsesAreChunkedAutomaticallyPartialWrite(int partialLength) { var testContext = new TestServiceContext(LoggerFactory); var expectedString = new string('a', partialLength); await using (var server = new TestServer(async httpContext => { await httpContext.Response.StartAsync(); var memory = httpContext.Response.BodyWriter.GetMemory(100000); Encoding.ASCII.GetBytes(expectedString).CopyTo(memory); httpContext.Response.BodyWriter.Advance(partialLength); await httpContext.Response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "Connection: close", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", partialLength.ToString("x", CultureInfo.InvariantCulture), new string('a', partialLength), "0", "", ""); } } } [Fact] public async Task SettingConnectionCloseHeaderInAppDoesNotDisableChunking() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { httpContext.Response.Headers["Connection"] = "close"; await httpContext.Response.WriteAsync("Hello "); await httpContext.Response.WriteAsync("World!"); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", "Connection: close", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task ZeroLengthWritesAreIgnored() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("Hello "), 0, 6)); await response.BodyWriter.WriteAsync(new Memory<byte>(new byte[0], 0, 0)); await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("World!"), 0, 6)); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task ZeroLengthWritesFlushHeaders() { var testContext = new TestServiceContext(LoggerFactory); var flushed = new SemaphoreSlim(0, 1); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.WriteAsync(""); await flushed.WaitAsync(); await response.WriteAsync("Hello World!"); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", ""); flushed.Release(); await connection.Receive( "c", "Hello World!", "0", "", ""); } } } [Fact] public async Task EmptyResponseBodyHandledCorrectlyWithZeroLengthWrite() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(new byte[0], 0, 0)); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "0", "", ""); } } } [Fact] public async Task ConnectionClosedIfExceptionThrownAfterWrite() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("Hello World!"), 0, 12)); throw new Exception(); }, testContext)) { using (var connection = server.CreateConnection()) { // SendEnd is not called, so it isn't the client closing the connection. // client closing the connection. await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.ReceiveEnd( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "Hello World!", ""); } } } [Fact] public async Task ConnectionClosedIfExceptionThrownAfterZeroLengthWrite() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(new byte[0], 0, 0)); throw new Exception(); }, testContext)) { using (var connection = server.CreateConnection()) { // SendEnd is not called, so it isn't the client closing the connection. await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); // Headers are sent before connection is closed, but chunked body terminator isn't sent await connection.ReceiveEnd( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", ""); } } } [Fact] public async Task WritesAreFlushedPriorToResponseCompletion() { var testContext = new TestServiceContext(LoggerFactory); var flushWh = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("Hello "), 0, 6)); // Don't complete response until client has received the first chunk. await flushWh.Task.DefaultTimeout(); await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("World!"), 0, 6)); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", ""); flushWh.SetResult(); await connection.Receive( "6", "World!", "0", "", ""); } } } [Fact] public async Task ChunksCanBeWrittenManually() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; response.Headers["Transfer-Encoding"] = "chunked"; await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("6\r\nHello \r\n"), 0, 11)); await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("6\r\nWorld!\r\n"), 0, 11)); await response.BodyWriter.WriteAsync(new Memory<byte>(Encoding.ASCII.GetBytes("0\r\n\r\n"), 0, 5)); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task ChunksWithGetMemoryAfterStartAsyncBeforeFirstFlushStillFlushes() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.StartAsync(); var memory = response.BodyWriter.GetMemory(); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("Hello "); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); memory = response.BodyWriter.GetMemory(); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "Hello World!", "0", "", ""); } } } [Fact] public async Task ChunksWithGetMemoryBeforeFirstFlushStillFlushes() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("Hello "); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); memory = response.BodyWriter.GetMemory(); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "Hello World!", "0", "", ""); } } } [Fact] public async Task ChunksWithGetMemoryLargeWriteBeforeFirstFlush() { var length = new IntAsRef(); var semaphore = new SemaphoreSlim(initialCount: 0); var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(5000); length.Value = memory.Length; semaphore.Release(); var fisrtPartOfResponse = Encoding.ASCII.GetBytes(new string('a', memory.Length)); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(memory.Length); memory = response.BodyWriter.GetMemory(); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); // Wait for length to be set await semaphore.WaitAsync(); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", length.Value.ToString("x" , CultureInfo.InvariantCulture), new string('a', length.Value), "6", "World!", "0", "", ""); } } } [Fact] public async Task ChunksWithGetMemoryAndStartAsyncWithInitialFlushWorks() { var length = new IntAsRef(); var semaphore = new SemaphoreSlim(initialCount: 0); var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.BodyWriter.FlushAsync(); var memory = response.BodyWriter.GetMemory(5000); length.Value = memory.Length; semaphore.Release(); var fisrtPartOfResponse = Encoding.ASCII.GetBytes(new string('a', memory.Length)); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(memory.Length); memory = response.BodyWriter.GetMemory(); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); // Wait for length to be set await semaphore.WaitAsync(); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", length.Value.ToString("x" , CultureInfo.InvariantCulture), new string('a', length.Value), "6", "World!", "0", "", ""); } } } [Fact] public async Task ChunksWithGetMemoryBeforeFlushEdgeCase() { var length = 0; var semaphore = new SemaphoreSlim(initialCount: 0); var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.StartAsync(); var memory = response.BodyWriter.GetMemory(); length = memory.Length - 1; semaphore.Release(); var fisrtPartOfResponse = Encoding.ASCII.GetBytes(new string('a', length)); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(length); var secondMemory = response.BodyWriter.GetMemory(6); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(secondMemory); response.BodyWriter.Advance(6); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); // Wait for length to be set await semaphore.WaitAsync(); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", length.ToString("x" , CultureInfo.InvariantCulture), new string('a', length), "6", "World!", "0", "", ""); } } } [Fact] public async Task ChunkGetMemoryMultipleAdvance() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.StartAsync(); var memory = response.BodyWriter.GetMemory(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("Hello "); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(memory.Slice(6)); response.BodyWriter.Advance(6); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "Hello World!", "0", "", ""); } } } [Fact] public async Task ChunkGetSpanMultipleAdvance() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.StartAsync(); // To avoid using span in an async method void NonAsyncMethod() { var span = response.BodyWriter.GetSpan(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("Hello "); fisrtPartOfResponse.CopyTo(span); response.BodyWriter.Advance(6); var secondPartOfResponse = Encoding.ASCII.GetBytes("World!"); secondPartOfResponse.CopyTo(span.Slice(6)); response.BodyWriter.Advance(6); } NonAsyncMethod(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "Hello World!", "0", "", ""); } } } [Fact] public async Task ChunkGetMemoryAndWrite() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.StartAsync(); var memory = response.BodyWriter.GetMemory(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("Hello "); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); await response.WriteAsync("World!"); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "Hello World!", "0", "", ""); } } } [Fact] public async Task ChunkGetMemoryAndWriteWithoutStart() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("Hello "); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); await response.WriteAsync("World!"); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "6", "Hello ", "6", "World!", "0", "", ""); } } } [Fact] public async Task GetMemoryWithSizeHint() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; await response.StartAsync(); var memory = response.BodyWriter.GetMemory(0); // Headers are already written to memory, sliced appropriately Assert.Equal(4005, memory.Length); memory = response.BodyWriter.GetMemory(1000000); Assert.Equal(4005, memory.Length); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", "0", "", ""); } } } [Fact] public async Task GetMemoryWithSizeHintWithoutStartAsync() { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(0); Assert.Equal(4096, memory.Length); memory = response.BodyWriter.GetMemory(1000000); Assert.Equal(1000000, memory.Length); await Task.CompletedTask; }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", "Content-Length: 0", $"Date: {testContext.DateHeaderValue}", "", ""); } } } [Theory] [InlineData(15)] [InlineData(255)] public async Task ChunkGetMemoryWithoutStartWithSmallerSizesWork(int writeSize) { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes(new string('a', writeSize)); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(writeSize); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", writeSize.ToString("X", CultureInfo.InvariantCulture).ToLowerInvariant(), new string('a', writeSize), "0", "", ""); } } } [Theory] [InlineData(15)] [InlineData(255)] public async Task ChunkGetMemoryWithStartWithSmallerSizesWork(int writeSize) { var testContext = new TestServiceContext(LoggerFactory); await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes(new string('a', writeSize)); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(writeSize); await response.BodyWriter.FlushAsync(); }, testContext)) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host: ", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {testContext.DateHeaderValue}", "Transfer-Encoding: chunked", "", writeSize.ToString("X", CultureInfo.InvariantCulture).ToLowerInvariant(), new string('a', writeSize), "0", "", ""); } } } [Fact] public async Task ChunkedWithBothPipeAndStreamWorks() { await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var memory = response.BodyWriter.GetMemory(4096); var fisrtPartOfResponse = Encoding.ASCII.GetBytes("hello,"); fisrtPartOfResponse.CopyTo(memory); response.BodyWriter.Advance(6); var secondPartOfResponse = Encoding.ASCII.GetBytes(" world"); secondPartOfResponse.CopyTo(memory.Slice(6)); response.BodyWriter.Advance(6); await response.Body.WriteAsync(Encoding.ASCII.GetBytes("hello, world")); await response.BodyWriter.WriteAsync(Encoding.ASCII.GetBytes("hello, world")); await response.WriteAsync("hello, world"); }, new TestServiceContext(LoggerFactory))) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host:", "", ""); await connection.Receive( "HTTP/1.1 200 OK", $"Date: {server.Context.DateHeaderValue}", "Transfer-Encoding: chunked", "", "c", "hello, world", "c", "hello, world", "c", "hello, world", "c", "hello, world", "0", "", ""); } } } private class IntAsRef { public int Value { get; set; } } } }
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using nanoFramework.Tools.Debugger; using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Extension.MetaData { public class MetaDataImport : IMetaDataImport2, IMetaDataAssemblyImport { private readonly CorDebugAssembly _assembly; private readonly Engine _engine; private readonly Guid _guidModule; private IntPtr _fakeSig; private readonly int _cbFakeSig; private ArrayList _alEnums; private int _handleEnumNext = 1; private bool _alert = false; public MetaDataImport (CorDebugAssembly assembly) { _assembly = assembly; _engine = _assembly.Process.Engine; _guidModule = Guid.NewGuid (); _alEnums = new ArrayList(); byte[] fakeSig = new byte[] { (byte)CorCallingConvention.IMAGE_CEE_CS_CALLCONV_DEFAULT, 0x0 /*count of params*/, (byte)CorElementType.ELEMENT_TYPE_VOID}; _cbFakeSig = fakeSig.Length; _fakeSig = Marshal.AllocCoTaskMem (_cbFakeSig); Marshal.Copy (fakeSig, 0, _fakeSig, _cbFakeSig); } ~MetaDataImport () { Marshal.FreeCoTaskMem (_fakeSig); } [Conditional("DEBUG")] private void NotImpl() { Debug.Assert(!_alert, "IMDI NotImpl"); } private class HCorEnum { public int m_handle; public int[] m_tokens; public int m_iToken; public HCorEnum(int handle, int[] tokens) { m_handle = handle; m_tokens = tokens; m_iToken = 0; } public int Reset(uint uPos) { m_iToken = (int)uPos; return COM_HResults.S_OK; } public int Count { get { return m_tokens.Length; } } public int Enum(IntPtr dest, uint cMax, IntPtr pct) { int cItems = Math.Min((int)cMax, this.Count - m_iToken); Marshal.WriteInt32(pct, cItems); Marshal.Copy(m_tokens, m_iToken, pct, cItems); m_iToken += cItems; return COM_HResults.S_OK; } } private HCorEnum CreateEnum(int[] tokens) { HCorEnum hce = new HCorEnum(_handleEnumNext, tokens); _alEnums.Add(hce); _handleEnumNext++; return hce; } private HCorEnum HCorEnumFromHandle(int handle) { foreach (HCorEnum hce in _alEnums) { if (hce.m_handle == handle) return hce; } return null; } private int EnumNoTokens( IntPtr phEnum, IntPtr pcTokens ) { int[] tokens = new int[0]; HCorEnum hce = CreateEnum( tokens ); if( phEnum != IntPtr.Zero ) Marshal.WriteInt32( phEnum, hce.m_handle ); if( pcTokens != IntPtr.Zero ) Marshal.WriteInt32( pcTokens, 0 ); return COM_HResults.S_OK; } #region IMetaDataImport2 Members public int EnumGenericParams (IntPtr phEnum, uint tk, IntPtr rGenericParams, uint cMax, IntPtr pcGenericParams) { return EnumNoTokens( phEnum, pcGenericParams ); } public int GetGenericParamProps (uint gp, IntPtr pulParamSeq, IntPtr pdwParamFlags, IntPtr ptOwner, IntPtr ptkKind, IntPtr wzName, uint cchName, IntPtr pchName) { // MetaDataImport.GetGenericParamProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetMethodSpecProps (uint mi, IntPtr tkParent, IntPtr ppvSigBlob, IntPtr pcbSigBlob) { // MetaDataImport.GetMethodSpecProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumGenericParamConstraints (IntPtr phEnum, uint tk, IntPtr rGenericParamConstraints, uint cMax, IntPtr pcGenericParamConstraints) { return EnumNoTokens( phEnum, pcGenericParamConstraints ); } public int GetGenericParamConstraintProps (uint gpc, IntPtr ptGenericParam, IntPtr ptkConstraintType) { // MetaDataImport.GetGenericParamConstraintProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPEKind (IntPtr pdwPEKind, IntPtr pdwMAchine) { // MetaDataImport.GetPEKind is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetVersionString (IntPtr pwzBuf, int ccBufSize, IntPtr pccBufSize) { // MetaDataImport.GetVersionString is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumMethodSpecs(IntPtr phEnum, uint tk, IntPtr rMethodSpecs, uint cMax, IntPtr pcMethodSpecs) { return EnumNoTokens( phEnum, pcMethodSpecs ); } #endregion #region IMetaDataImport/IMetaDataAssemblyImport Members public void CloseEnum (IntPtr hEnum) { HCorEnum hce = HCorEnumFromHandle(hEnum.ToInt32()); if (hce != null) _alEnums.Remove(hce); } #endregion #region IMetaDataImport Members public int CountEnum (IntPtr hEnum, IntPtr pulCount) { HCorEnum hce = HCorEnumFromHandle(hEnum.ToInt32()); Marshal.WriteInt32(pulCount, hce.Count); return COM_HResults.S_OK; } public int ResetEnum (IntPtr hEnum, uint ulPos) { HCorEnum hce = HCorEnumFromHandle(hEnum.ToInt32()); return hce.Reset(ulPos); } public int EnumTypeDefs (IntPtr phEnum, IntPtr rTypeDefs, uint cMax, IntPtr pcTypeDefs) { return EnumNoTokens( phEnum, pcTypeDefs ); } public int EnumInterfaceImpls (IntPtr phEnum, uint td, IntPtr rImpls, uint cMax, IntPtr pcImpls) { return EnumNoTokens( phEnum, pcImpls ); } public int EnumTypeRefs (IntPtr phEnum, IntPtr rTypeRefs, uint cMax, IntPtr pcTypeRefs) { return EnumNoTokens( phEnum, pcTypeRefs ); } public int FindTypeDefByName (string szTypeDef, uint tkEnclosingClass, IntPtr mdTypeDef) { // MetaDataImport.FindTypeDefByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetScopeProps (IntPtr szName, uint cchName, IntPtr pchName, IntPtr pmvid) { // MetaDataImport.GetScopeProps is not implemented _assembly.ICorDebugAssembly.GetName (cchName, pchName, szName); if (pmvid != IntPtr.Zero) { byte [] guidModule = _guidModule.ToByteArray(); Marshal.Copy (guidModule, 0, pmvid, guidModule.Length); } return COM_HResults.S_OK; } public int GetModuleFromScope (IntPtr pmd) { // MetaDataImport.GetModuleFromScope is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetTypeDefProps (uint td, IntPtr szTypeDef, uint cchTypeDef, IntPtr pchTypeDef, IntPtr pdwTypeDefFlags, IntPtr ptkExtends) { uint tk = nanoCLR_TypeSystem.SymbollessSupport.nanoCLRTokenFromTypeDefToken(td); uint index = nanoCLR_TypeSystem.ClassMemberIndexFromnanoCLRToken (td, _assembly); string name = _engine.GetTypeName(index); Utility.MarshalString (name, cchTypeDef, pchTypeDef, szTypeDef); Utility.MarshalInt (pchTypeDef, 0); Utility.MarshalInt (pdwTypeDefFlags, 0); Utility.MarshalInt (ptkExtends, 0); return COM_HResults.S_OK; } public int GetInterfaceImplProps (uint iiImpl, IntPtr pClass, IntPtr ptkIface) { // MetaDataImport.GetInterfaceImplProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetTypeRefProps (uint tr, IntPtr ptkResolutionScope, IntPtr szName, uint cchName, IntPtr pchName) { // MetaDataImport.GetTypeRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int ResolveTypeRef (uint tr, IntPtr riid, ref object ppIScope, IntPtr ptd) { // MetaDataImport.ResolveTypeRef is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumMembers (IntPtr phEnum, uint cl, IntPtr rMembers, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMembersWithName (IntPtr phEnum, uint cl, string szName, IntPtr rMembers, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMethods (IntPtr phEnum, uint cl, IntPtr rMethods, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMethodsWithName (IntPtr phEnum, uint cl, string szName, IntPtr rMethods, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumFields (IntPtr phEnum, uint cl, IntPtr rFields, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumFieldsWithName (IntPtr phEnum, uint cl, string szName, IntPtr rFields, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumParams (IntPtr phEnum, uint mb, IntPtr rParams, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMemberRefs (IntPtr phEnum, uint tkParent, IntPtr rMemberRefs, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMethodImpls (IntPtr phEnum, uint td, IntPtr rMethodBody, IntPtr rMethodDecl, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumPermissionSets (IntPtr phEnum, uint tk, int dwActions, IntPtr rPermission, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int FindMember (uint td, string szName, IntPtr pvSigBlob, uint cbSigBlob, IntPtr pmb) { // MetaDataImport.FindMember is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindMethod (uint td, string szName, IntPtr pvSigBlog, uint cbSigBlob, IntPtr pmb) { // MetaDataImport.FindMethod is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindField (uint td, string szName, IntPtr pvSigBlog, uint cbSigBlob, IntPtr pmb) { // MetaDataImport.FindField is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindMemberRef (uint td, string szName, IntPtr pvSigBlog, uint cbSigBlob, IntPtr pmr) { // MetaDataImport.FindMemberRef is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetMethodProps (uint mb, IntPtr pClass, IntPtr szMethod, uint cchMethod, IntPtr pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA, IntPtr pdwImplFlags) { uint tk = nanoCLR_TypeSystem.SymbollessSupport.nanoCLRTokenFromMethodDefToken (mb); uint md = nanoCLR_TypeSystem.ClassMemberIndexFromnanoCLRToken (tk, _assembly); Debugger.WireProtocol.Commands.Debugging_Resolve_Method.Result resolvedMethod = _engine.ResolveMethod(md); string name = null; uint tkClass = 0; if (resolvedMethod != null) { name = resolvedMethod.m_name; uint tkType = nanoCLR_TypeSystem.nanoCLRTokenFromTypeIndex (resolvedMethod.m_td); tkClass = nanoCLR_TypeSystem.SymbollessSupport.TypeDefTokenFromnanoCLRToken (tkType); } Utility.MarshalString (name, cchMethod, pchMethod, szMethod); Utility.MarshalInt (pClass, (int)tkClass); Utility.MarshalInt(pdwAttr, (int)CorMethodAttr.mdStatic); Utility.MarshalInt(pulCodeRVA, 0); Utility.MarshalInt(pdwImplFlags, 0); Utility.MarshalInt(pcbSigBlob, _cbFakeSig); Utility.MarshalInt(ppvSigBlob, _fakeSig.ToInt32 ()); return COM_HResults.S_OK; } public int GetMemberRefProps (uint mr, IntPtr ptk, IntPtr szMember, uint cchMember, IntPtr pchMember, IntPtr ppvSigBlob, IntPtr pcbSigBlob) { // MetaDataImport.GetMemberRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumProperties (IntPtr phEnum, uint td, IntPtr rProperties, uint cMax, IntPtr pcProperties) { return EnumNoTokens( phEnum, pcProperties ); } public int EnumEvents (IntPtr phEnum, uint td, IntPtr rEvents, uint cMax, IntPtr pcEvents) { return EnumNoTokens( phEnum, pcEvents ); } public int GetEventProps (uint ev, IntPtr pClass, IntPtr szEvent, uint cchEvent, IntPtr pchEvent, IntPtr pdwEventFlags, IntPtr ptkEventType, IntPtr pmdAddOn, IntPtr pmdRemoveOn, IntPtr pmdFire, IntPtr rmdOtherMethod, uint cMax, IntPtr pcOtherMethod) { // MetaDataImport.GetEventProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumMethodSemantics (IntPtr phEnum, uint mb, IntPtr rEventProp, uint cMax, IntPtr pcEventProp) { return EnumNoTokens( phEnum, pcEventProp ); } public int GetMethodSemantics (uint mb, uint tkEventProp, IntPtr pdwSemanticFlags) { // MetaDataImport.GetMethodSemantics is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetClassLayout (uint td, IntPtr pdwPackSize, IntPtr rFieldOffset, uint cMax, IntPtr pcFieldOffset, IntPtr pulClassSize) { // MetaDataImport.GetClassLayour is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetFieldMarshal (uint tk, IntPtr ppvNativeType, IntPtr pcbNativeType) { // MetaDataImport.GetFieldMarshal is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetRVA (uint tk, IntPtr pulCodeRVA, IntPtr pdwImplFlags) { // MetaDataImport.GetRVA is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPermissionSetProps (uint pm, IntPtr pdwAction, IntPtr ppvPermission, IntPtr pcbPermission) { // MetaDataImport.GetPermissionSetProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetSigFromToken (uint mdSig, IntPtr ppvSig, IntPtr pcbSig) { // MetaDataImport.GetSigFromToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetModuleRefProps (uint mur, IntPtr szName, uint cchName, IntPtr pchName) { // MetaDataImport.GetModuleRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumModuleRefs (IntPtr phEnum, IntPtr rModuleRefs, uint cmax, IntPtr pcModuleRefs) { return EnumNoTokens( phEnum, pcModuleRefs ); } public int GetTypeSpecFromToken (uint typespec, IntPtr ppvSig, IntPtr pcbSig) { // MetaDataImport.GetTypeSpecFromToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetNameFromToken (uint tk, IntPtr pszUtf8NamePtr) { // MetaDataImport.GetNameFromToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumUnresolvedMethods (IntPtr phEnum, IntPtr rMethods, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int GetUserString (uint stk, IntPtr szString, uint cchString, IntPtr pchString) { // MetaDataImport.GetUserString is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPinvokeMap (uint tk, IntPtr pdwMappingFlags, IntPtr szImportName, uint cchImportName, IntPtr pchImportName, IntPtr pmrImportDLL) { // MetaDataImport.GetPinvokeMap is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumSignatures (IntPtr phEnum, IntPtr rSignatures, uint cmax, IntPtr pcSignatures) { return EnumNoTokens( phEnum, pcSignatures ); } public int EnumTypeSpecs (IntPtr phEnum, IntPtr rTypeSpecs, uint cmax, IntPtr pcTypeSpecs) { return EnumNoTokens( phEnum, pcTypeSpecs ); } public int EnumUserStrings (IntPtr phEnum, IntPtr rStrings, uint cmax, IntPtr pcStrings) { return EnumNoTokens( phEnum, pcStrings ); } public int GetParamForMethodIndex (uint md, uint ulParamSeq, IntPtr ppd) { // MetaDataImport.GetParamForMethodIndex is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumUserStrings (IntPtr phEnum, uint tk, uint tkType, IntPtr rCustomAttributes, uint cMax, IntPtr pcCustomAttributes) { return EnumNoTokens( phEnum, pcCustomAttributes ); } public int GetCustomAttributeProps (uint cv, IntPtr ptkObj, IntPtr ptkType, IntPtr ppBlob, IntPtr pcbSize) { return COM_HResults.S_FALSE; } public int FindTypeRef (uint tkResolutionScope, string szName, IntPtr ptr) { // MetaDataImport.FindTypeRef is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetMemberProps (uint mb, IntPtr pClass, IntPtr szMember, uint cchMember, IntPtr pchMember, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA, IntPtr pdwImplFlags, IntPtr pdwCPlusTypeFlag, IntPtr ppValue, IntPtr pcchValue) { // MetaDataImport.GetMemberProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetFieldProps (uint mb, IntPtr pClass, IntPtr szField, uint cchField, IntPtr pchField, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pdwCPlusTypeFlag, IntPtr ppValue, IntPtr pcchValue) { // MetaDataImport.GetFieldProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPropertyProps (uint prop, IntPtr pClass, IntPtr szProperty, uint cchProperty, IntPtr pchProperty, IntPtr pdwPropFlags, IntPtr ppvSig, IntPtr pbSig, IntPtr pdwCPlusTypeFlag, IntPtr ppDefaultValue, IntPtr pcchDefaultValue, IntPtr pmdSetter, IntPtr pmdGetter, IntPtr rmdOtherMethod, uint cMax, IntPtr pcOtherMethod) { // MetaDataImport.GetPropertyProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetParamProps (uint tk, IntPtr pmd, IntPtr pulSequence, IntPtr szName, uint cchName, IntPtr pchName, IntPtr pdwAttr, IntPtr pdwCPlusTypeFlag, IntPtr ppValue, IntPtr pcchValue) { // MetaDataImport.GetParamProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetCustomAttributeByName (uint tkObj, string szName, IntPtr ppData, IntPtr pcbData) { // MetaDataImport.GetCustomAttributeByName is not implemented return COM_HResults.E_NOTIMPL; } public int IsValidToken (uint tk) { // MetaDataImport.IsValidToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetNestedClassProps (uint tdNestedClass, IntPtr ptdEnclosingClass) { // MetaDataImport.GetNestedClassProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetNativeCallConvFromSig (IntPtr pvSig, uint cbSig, IntPtr pCallConv) { // MetaDataImport.GetNativeCallConvFromSig is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int IsGlobal (uint pd, IntPtr pbGlobal) { // MetaDataImport.IsGlobal is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } #endregion #region IMetaDataAssemblyImport Members public int GetAssemblyProps (uint mda, IntPtr ppbPublicKey, IntPtr pcbPublicKey, IntPtr pulHashAlgId, IntPtr szName, uint cchName, IntPtr pchName, IntPtr pMetaData, IntPtr pdwAssemblyFlags) { _assembly.ICorDebugAssembly.GetName(cchName, pchName, szName); return COM_HResults.S_OK; } public int GetAssemblyRefProps (uint mdar, IntPtr ppbPublicKeyOrToken, IntPtr pcbPublicKeyOrToken, IntPtr szName, uint cchName, IntPtr pchName, IntPtr pMetaData, IntPtr ppbHashValue, IntPtr pcbHashValue, IntPtr pdwAssemblyRefFlags) { // MetaDataImport.GetAssemblyRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetFileProps (uint mdf, IntPtr szName, uint cchName, IntPtr pchName, IntPtr ppbHashValue, IntPtr pcbHashValue, IntPtr pdwFileFlags) { // MetaDataImport.GetFileProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetExportedTypeProps (uint mdct, IntPtr szName, uint cchName, IntPtr pchName, IntPtr ptkImplementation, IntPtr ptkTypeDef, IntPtr pdwExportedTypeFlags) { // MetaDataImport.GetExportedTypeProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetManifestResourceProps (uint mdmr, IntPtr szName, uint cchName, IntPtr pchName, IntPtr ptkImplementation, IntPtr pdwOffset, IntPtr pdwResourceFlags) { // MetaDataImport.GetManifestResourceProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumAssemblyRefs (IntPtr phEnum, IntPtr rAssemblyRefs, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumFiles (IntPtr phEnum, IntPtr rFiles, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumExportedTypes (IntPtr phEnum, IntPtr rExportedTypes, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumManifestResources (IntPtr phEnum, IntPtr rManifestResources, uint cMax, IntPtr pcTokens) { // MetaDataImport.EnumManifestResources is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetAssemblyFromScope (IntPtr ptkAssembly) { //Only one assembly per MetaDataImport, doesn't matter what token we give them back return COM_HResults.E_NOTIMPL; } public int FindExportedTypeByName (string szName, uint mdtExportedType, IntPtr ptkExportedType) { // MetaDataImport.FindExportedTypeByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindManifestResourceByName (string szName, IntPtr ptkManifestResource) { // MetaDataImport.FindManifestResourceByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindAssembliesByName (string szAppBase, string szPrivateBin, string szAssemblyName, IntPtr ppIUnk, uint cMax, IntPtr pcAssemblies) { // MetaDataImport.FindAssembliesByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } #endregion } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using MathNet.Numerics.Interpolation; using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.Geometry; using SpatialAnalysis.Data; using SpatialAnalysis.Miscellaneous; using SpatialAnalysis.Optimization; using SpatialAnalysis.Events; using System.IO; using SpatialAnalysis.Interoperability; namespace SpatialAnalysis.FieldUtility { /// <summary> /// Class ActivityDestination. /// </summary> public class ActivityDestination { /// <summary> /// Gets or sets the origins of the activity. /// </summary> /// <value>The origins.</value> public HashSet<Cell> Origins { get; set; } /// <summary> /// Gets or sets the default state of the agent in the activity area. /// </summary> /// <value>The default state.</value> public StateBase DefaultState { get; set; } private BarrierPolygon _destinationArea; /// <summary> /// A polygon that shows the destination area /// </summary> public BarrierPolygon DestinationArea { get { return _destinationArea; } } /// <summary> /// Gets or sets the name of the engaged activity. /// </summary> /// <value>The name of the engaged activity.</value> public string EngagedActivityName { get; set; } /// <summary> /// Gets the name of the activity. /// </summary> /// <value>The name.</value> public string Name { get { return this.EngagedActivityName; } } private double _maximumEngagementTime = 60.0d; /// <summary> /// Gets or sets the maximum engagement time. /// </summary> /// <value>The maximum engagement time.</value> /// <exception cref="System.ArgumentException">'Maximum Engagement Time' should be larger than 'Minimum Engagement Time'</exception> public double MaximumEngagementTime { get { return _maximumEngagementTime; } set { if (this._maximumEngagementTime != value) { if (value > this.MinimumEngagementTime) { this._maximumEngagementTime = value; } else { throw new ArgumentException("'Maximum Engagement Time' should be larger than 'Minimum Engagement Time'"); } } } } private double _minimumEngagementTime = 10.0d; /// <summary> /// Gets or sets the minimum engagement time. /// </summary> /// <value>The minimum engagement time.</value> /// <exception cref="System.ArgumentException">'Minimum Engagement Time' should be smaller than 'Maximum Engagement Time' and larger than zero</exception> public double MinimumEngagementTime { get { return _minimumEngagementTime; } set { if (this._minimumEngagementTime != value) { if (this._minimumEngagementTime > 0.0d && this._minimumEngagementTime < this.MaximumEngagementTime) { this._minimumEngagementTime = value; } else { throw new ArgumentException("'Minimum Engagement Time' should be smaller than 'Maximum Engagement Time' and larger than zero"); } } } } /// <summary> /// Initializes a new instance of the <see cref="ActivityDestination"/> class. /// </summary> /// <param name="name">The name of activity.</param> /// <param name="origins">The origins of the activity.</param> /// <param name="defaultState">The default state of the agent in the activity area.</param> /// <param name="destinationArea">The destination area.</param> public ActivityDestination(string name, HashSet<Cell> origins, StateBase defaultState, BarrierPolygon destinationArea) { this.DefaultState = defaultState; this._destinationArea = destinationArea; //trim the unwanted chars from the input name char[] charsToTrim = {' ', '\''}; this.EngagedActivityName = name.Trim(charsToTrim); this.Origins = origins; } /// <summary> /// Initializes a new instance of the <see cref="ActivityDestination"/> class. /// </summary> /// <param name="activityDestination">The activity destination to be copied deeply.</param> public ActivityDestination(ActivityDestination activityDestination) { this.EngagedActivityName=activityDestination.Name; this._destinationArea=activityDestination.DestinationArea; this.DefaultState = activityDestination.DefaultState; this._minimumEngagementTime= activityDestination._minimumEngagementTime; this._maximumEngagementTime=activityDestination._maximumEngagementTime; this.Origins = activityDestination.Origins; } /// <summary> /// Tries the set engagement time. /// </summary> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> /// <returns><c>true</c> if engagement time set, <c>false</c> otherwise.</returns> public bool TrySetEngagementTime(double min, double max) { if (min > 0 && max > min) { this._minimumEngagementTime = min; this._maximumEngagementTime = max; return true; } return false; } /// <summary> /// Gets the string representation of this instance. /// </summary> /// <returns>System.String.</returns> public string GetStringRepresentation() { StringBuilder sb = new StringBuilder(); //sb.AppendLine("# Name:"); sb.AppendLine(this.Name); //sb.AppendLine("# Default State:"); sb.AppendLine(this.DefaultState.ToString()); //sb.AppendLine("# Area"); sb.AppendLine(this.DestinationArea.ToString()); //sb.AppendLine("# Engagement Time:"); sb.AppendLine(this.MinimumEngagementTime.ToString() + "," + this.MaximumEngagementTime.ToString()); string s = sb.ToString(); sb.Clear(); sb = null; return s; } /// <summary> /// creates an Activity Destination from its string representation /// </summary> /// <param name="lines">The lines.</param> /// <param name="startIndex">The start index.</param> /// <param name="cellularFloor">The cellular floor.</param> /// <param name="tolerance">The tolerance.</param> /// <returns>ActivityDestination.</returns> /// <exception cref="System.ArgumentException"> /// Activity does not include a name! /// or /// Failed to parse activity's engagement duration: " + lines[startIndex + 3] /// or /// Activity does not include cell origins! /// or /// Failed to set activity engagement duration! /// </exception> public static ActivityDestination FromString(List<string> lines, int startIndex, Length_Unit_Types unitType, CellularFloor cellularFloor, double tolerance = 0.0000001d) { string name = lines[startIndex]; if (string.IsNullOrEmpty(lines[startIndex]) || string.IsNullOrWhiteSpace(lines[startIndex])) { throw new ArgumentException("Activity does not include a name!"); } StateBase state = StateBase.FromStringRepresentation(lines[startIndex + 1]); BarrierPolygon barrier = BarrierPolygon.FromStringRepresentation(lines[startIndex + 2]); //unit converion UnitConversion.Transform(state.Location, unitType, cellularFloor.UnitType); UnitConversion.Transform(state.Velocity, unitType, cellularFloor.UnitType); UnitConversion.Transform(barrier.BoundaryPoints, unitType, cellularFloor.UnitType); var strings = lines[startIndex + 3].Split(','); double min = 0, max = 0; if (!double.TryParse(strings[0], out min) || !double.TryParse(strings[1], out max)) { throw new ArgumentException("Failed to parse activity's engagement duration: " + lines[startIndex + 3]); } HashSet<Cell> origins = new HashSet<Cell>(); var indices = cellularFloor.GetIndicesInsideBarrier(barrier, tolerance); if (indices.Count > 0) { foreach (var index in indices) { Cell cell = cellularFloor.FindCell(index); if (cell != null && cell.FieldOverlapState == OverlapState.Inside) { origins.Add(cell); } } } if (origins.Count == 0) { throw new ArgumentException("Activity does not include cell origins!"); } ActivityDestination dest = new ActivityDestination(name, origins, state, barrier); if (!dest.TrySetEngagementTime(min, max)) { throw new ArgumentException("Failed to set activity engagement duration!"); } return dest; } } /// <summary> /// Class Activity. /// </summary> /// <seealso cref="SpatialAnalysis.FieldUtility.ActivityDestination" /> /// <seealso cref="SpatialAnalysis.Data.ISpatialData" /> public class Activity : ActivityDestination, ISpatialData { /// <summary> /// The gradient interpolation neighborhood size /// </summary> public static int GradientInterpolationNeighborhoodSize = 1; /// <summary> /// The interpolation method /// </summary> public static InterpolationMethod InterpolationMethod = InterpolationMethod.CubicSpline; /// <summary> /// Indicates whether to use engagement with this activity in capturing event]. /// </summary> /// <value><c>true</c> if it should be used to capture events; otherwise, <c>false</c>.</value> public bool UseToCaptureEvent { get; set; } /// <summary> /// Gets or sets the potentials of the walkable floor for this activity. /// </summary> /// <value>The potentials.</value> public Dictionary<Cell, double> Potentials { get; set; } /// <summary> /// Returns the potentials of the walkable floor for this activity. /// </summary> /// <value>The data.</value> public Dictionary<Cell, double> Data { get { return this.Potentials; } } private CellularFloor _cellularFloor { get; set; } /// <summary> /// Gets the type of data. /// </summary> /// <value>The type.</value> public DataType Type { get { return DataType.ActivityPotentialField; } } double _min; /// <summary> /// Gets the minimum value of the data. /// </summary> /// <value>The minimum.</value> public double Min { get { return _min; } } double _max; /// <summary> /// Gets the maximum value of the data. /// </summary> /// <value>The maximum.</value> public double Max { get { return _max; } } /// <summary> /// Initializes a new instance of the <see cref="Activity"/> class. /// </summary> /// <param name="potentials">The potentials.</param> /// <param name="origins">The origins.</param> /// <param name="destinationArea">The destination area.</param> /// <param name="defaultState">The default state.</param> /// <param name="engagedActivityName">Name of the engaged activity.</param> /// <param name="cellularFloor">The cellular floor.</param> public Activity(Dictionary<Cell, double> potentials, HashSet<Cell> origins, BarrierPolygon destinationArea, StateBase defaultState, string engagedActivityName, CellularFloor cellularFloor) : base(engagedActivityName, origins, defaultState, destinationArea) { this.Potentials = potentials; this.EngagedActivityName = engagedActivityName; this._cellularFloor = cellularFloor; this._min = double.PositiveInfinity; this._max = double.NegativeInfinity; foreach (var item in this.Potentials.Values) { this._max = (this._max < item) ? item : this._max; this._min = (this._min > item) ? item : this._min; } this.Origins = new HashSet<Cell>(origins); this.DefaultState = defaultState.Copy(); //this._destinationArea = destinationArea; this.UseToCaptureEvent = true; } /// <summary> /// Initializes a new instance of the <see cref="Activity"/> class. /// </summary> /// <param name="activityDestination">The activity destination.</param> /// <param name="cellularFloor">The cellular floor.</param> public Activity(ActivityDestination activityDestination, CellularFloor cellularFloor) : base(activityDestination) { this._cellularFloor = cellularFloor; var indices = this._cellularFloor.GetIndicesInsideBarrier(activityDestination.DestinationArea, .000001); } #region Gradient Interpolation private IInterpolation toInterpolation(IndexRange range) { double[] x = new double[range.Length]; double[] y = new double[x.Length]; Index next = range.Min.Copy(); switch (range.Direction) { case Direction.Horizontal: for (int i = 0; i < x.Length; i++) { Cell cell = this._cellularFloor.FindCell(next); x[i] = cell.U; y[i] = this.Potentials[cell]; next.I += 1; } break; case Direction.Vertical: for (int i = 0; i < x.Length; i++) { Cell cell = this._cellularFloor.FindCell(next); x[i] = cell.V; y[i] = this.Potentials[cell]; next.J += 1; } break; default: break; } IInterpolation interpolator = null; switch (Activity.InterpolationMethod) { case SpatialAnalysis.FieldUtility.InterpolationMethod.CubicSpline: if (x.Length > 1) { interpolator = CubicSpline.InterpolateBoundariesSorted(x, y, SplineBoundaryCondition.Natural, 0, SplineBoundaryCondition.Natural, 0); } else { interpolator = LinearSpline.InterpolateSorted(x, y); } break; //case FieldUtility.InterpolationMethod.Barycentric: // interpolator = Barycentric.InterpolatePolynomialEquidistantSorted(x, y); // break; case SpatialAnalysis.FieldUtility.InterpolationMethod.Linear: interpolator = LinearSpline.InterpolateSorted(x, y); break; default: break; } x = null; y = null; next = null; return interpolator; } private IndexRange verticalRange (Index index) { int minJ = index.J, maxJ = index.J; Index next = index.Copy(); for (int j = 0; j <= Activity.GradientInterpolationNeighborhoodSize; j++) { next.J += 1; Cell cell = this._cellularFloor.FindCell(next); if (cell != null) { if (this.Potentials.ContainsKey(cell)) { maxJ = next.J; } else { break; } } else { break; } } next = index.Copy(); for (int j = 0; j < Activity.GradientInterpolationNeighborhoodSize; j++) { next.J -= 1; Cell cell = this._cellularFloor.FindCell(next); if (cell != null) { if (this.Potentials.ContainsKey(cell)) { minJ = next.J; } else { break; } } else { break; } } IndexRange range = new IndexRange(new Index(index.I, minJ), new Index(index.I, maxJ), Direction.Vertical); next = null; return range; } private IndexRange horizontalRange(Index index) { int minI = index.I, maxI = index.I; Index next = index.Copy(); for (int i = 0; i <= Activity.GradientInterpolationNeighborhoodSize; i++) { next.I += 1; Cell cell = this._cellularFloor.FindCell(next); if (cell != null) { if (this.Potentials.ContainsKey(cell)) { maxI = next.I; } else { break; } } else { break; } } next = index.Copy(); for (int i = 0; i < Activity.GradientInterpolationNeighborhoodSize; i++) { next.I -= 1; Cell cell = this._cellularFloor.FindCell(next); if (cell != null) { if (this.Potentials.ContainsKey(cell)) { minI = next.I; } else { break; } } else { break; } } IndexRange range = new IndexRange(new Index(minI, index.J), new Index(maxI, index.J), Direction.Horizontal); next = null; return range; } private IInterpolation interpolation_U(UV point, Index index) { IndexRange horizontalExpansion = this.horizontalRange(index); //getting all vertical ranges of the horizontal IndexRange[] verticals = new IndexRange[horizontalExpansion.Length]; Index next = horizontalExpansion.Min.Copy(); for (int i = 0; i < horizontalExpansion.Length; i++) { verticals[i] = this.verticalRange(next); next.I++; } //getting interpolators for u values IInterpolation[] verticalsU = new IInterpolation[horizontalExpansion.Length]; for (int i = 0; i < verticals.Length; i++) { verticalsU[i] = this.toInterpolation(verticals[i]); } //generating u interpolation double[] x = new double[horizontalExpansion.Length]; double[] y = new double[horizontalExpansion.Length]; next = horizontalExpansion.Min.Copy(); for (int i = 0; i < horizontalExpansion.Length; i++) { x[i] = this._cellularFloor.FindCell(next).U; y[i] = verticalsU[i].Interpolate(point.V); next.I++; } IInterpolation interpolatorU = null; switch (Activity.InterpolationMethod) { case SpatialAnalysis.FieldUtility.InterpolationMethod.CubicSpline: if (x.Length > 1) { interpolatorU = CubicSpline.InterpolateBoundariesSorted(x, y, SplineBoundaryCondition.Natural, 0, SplineBoundaryCondition.Natural, 0); } else { interpolatorU = LinearSpline.InterpolateSorted(x, y); } break; //case FieldUtility.InterpolationMethod.Barycentric: // interpolatorU = Barycentric.InterpolatePolynomialEquidistantSorted(x, y); // break; case SpatialAnalysis.FieldUtility.InterpolationMethod.Linear: interpolatorU = LinearSpline.InterpolateSorted(x, y); break; default: break; } return interpolatorU; } private IInterpolation interpolation_V(UV point, Index index) { IndexRange verticalExpansion = this.verticalRange(index); IndexRange[] horizontals = new IndexRange[verticalExpansion.Length]; Index next = verticalExpansion.Min.Copy(); for (int i = 0; i < verticalExpansion.Length; i++) { horizontals[i] = this.horizontalRange(next); next.J++; } IInterpolation[] horizontalV = new IInterpolation[verticalExpansion.Length]; for (int i = 0; i < horizontals.Length; i++) { horizontalV[i] = this.toInterpolation(horizontals[i]); } double[] x = new double[verticalExpansion.Length]; double[] y = new double[verticalExpansion.Length]; next = verticalExpansion.Min.Copy(); for (int i = 0; i < verticalExpansion.Length; i++) { x[i] = this._cellularFloor.FindCell(next).V; y[i] = horizontalV[i].Interpolate(point.U); next.J++; } //getting U IInterpolation interpolatorV = null; switch (Activity.InterpolationMethod) { case SpatialAnalysis.FieldUtility.InterpolationMethod.CubicSpline: if (x.Length > 1) { interpolatorV = CubicSpline.InterpolateBoundariesSorted(x, y, SplineBoundaryCondition.Natural, 0, SplineBoundaryCondition.Natural, 0); } else { interpolatorV = LinearSpline.InterpolateSorted(x, y); } break; //case FieldUtility.InterpolationMethod.Barycentric: // interpolatorV = Barycentric.InterpolatePolynomialEquidistantSorted(x, y); // break; case SpatialAnalysis.FieldUtility.InterpolationMethod.Linear: interpolatorV = LinearSpline.InterpolateSorted(x, y); break; default: break; } return interpolatorV; } /// <summary> /// Differentiates the specified point to get the steepest gradient. /// </summary> /// <param name="point">The point.</param> /// <returns>UV.</returns> public UV Differentiate(UV point) { Index index = this._cellularFloor.FindIndex(point); if (this.Origins.Contains(this._cellularFloor.Cells[index.I,index.J])) { UV vector = this.DefaultState.Location - point; vector.Unitize(); return vector; } try { IInterpolation u_Interpolation = this.interpolation_U(point, index); IInterpolation v_Interpolation = this.interpolation_V(point, index); return new UV(-1 * u_Interpolation.Differentiate(point.U), -1 * v_Interpolation.Differentiate(point.V)); } catch (Exception) { } return null; } /// <summary> /// Interpolates the potentials at the specified point. /// </summary> /// <param name="point">The point.</param> /// <returns>System.Nullable&lt;System.Double&gt;.</returns> public double? Interpolate(UV point) { Index index = this._cellularFloor.FindIndex(point); try { IInterpolation u_Interpolation = this.interpolation_U(point, index); return u_Interpolation.Interpolate(point.U); } catch (Exception) { } try { IInterpolation v_Interpolation = this.interpolation_V(point, index); return v_Interpolation.Interpolate(point.V); } catch (Exception) { } return null; } public double? GetPotential(UV point) { /* INDEXING MODEL up up_right origin right */ try { Index index = this._cellularFloor.FindIndex(point); int I = index.I, J = index.J; if (!Data.ContainsKey(this._cellularFloor.Cells[I, J])) return null; double u = point.U - _cellularFloor.Cells[I, J].U; double v = point.V - _cellularFloor.Cells[I, J].V; double origin = Data[_cellularFloor.FindCell(index)]; J++; bool contains_up = Data.ContainsKey(this._cellularFloor.Cells[I, J]); double up = origin; if (contains_up) up = Data[this._cellularFloor.Cells[I, J]]; I++; J--; bool contains_right = Data.ContainsKey(this._cellularFloor.Cells[I, J]); double right = origin; if (contains_right) right = Data[this._cellularFloor.Cells[I, J]]; J++; bool contains_up_right = Data.ContainsKey(this._cellularFloor.Cells[I, J]); double up_right = origin; if (contains_up_right) up_right = Data[this._cellularFloor.Cells[I, J]]; /* All Possible cases will be investigated */ //none of the corners exist if (!contains_up && !contains_right && !contains_up_right) { return origin; } //only one of the corners exist { //ONLY contains_up_right if (!contains_up && !contains_right && contains_up_right) { double distance_to_origin = UV.GetDistanceBetween(point, this._cellularFloor.Cells[index.I, index.J]); double distance_to_up_tight = UV.GetDistanceBetween(point, this._cellularFloor.Cells[index.I + 1, index.J + 1]); double total_distance = distance_to_origin + distance_to_up_tight; double potential = (distance_to_up_tight * origin + distance_to_origin * up_right) / (total_distance); return potential; } //ONLY contains_right if (!contains_up && contains_right && !contains_up_right) { double t = u / this._cellularFloor.CellSize; double potential = (1 - t) * origin + t * right; return potential; } //ONLY contains_up if (contains_up && !contains_right && !contains_up_right) { double t = v / this._cellularFloor.CellSize; double potential = (1 - t) * origin + t * up; return potential; } } /* only one of the corners does not exist. The missing corner's potential will be calculated assuming that center = up + right = origing + up_right the result will be a planar quad */ { //EXCEPT contains_up_right if (contains_up && contains_right && !contains_up_right) { up_right = up + right - origin; } //EXCEPT contains_right if (contains_up && !contains_right && contains_up_right) { right = origin + up_right - up; } //EXCEPT contains_up if (!contains_up && contains_right && contains_up_right) { up = origin + up_right - right; } } //ALL corners have potentials or predicted potentials double a = u / this._cellularFloor.CellSize; double b = v / this._cellularFloor.CellSize; double value = origin * (1 - a) * (1 - b) + up * a * (1 - b) + up * (1 - a) * b + up_right * a * b; return value; } catch (Exception e) { MessageBox.Show(e.Report()); } return null; } #endregion /// <summary> /// Gets a path using the gradient-descend method /// </summary> /// <param name="p">The point to get the gradient from.</param> /// <param name="distanceFactor">The distance tolerance.</param> /// <returns>List&lt;UV&gt;.</returns> public List<UV> GetGradientPath(UV p, double distanceFactor = 0.1d, int maxIterations = 5000) { //distanceFactor = UnitConversion.Convert(distanceFactor, Length_Unit_Types.FEET, this._cellularFloor.UnitType); //set the termination conditions double distanceTolerance = this._cellularFloor.CellSize * this._cellularFloor.CellSize; //find a minimum potential for the termination of the descenting process double min = 0; if(this.Origins.Count == 1) // a neighborhood of size 2 will be selected if only one cell is set as the origin of the potential field { foreach (Index item in Index.Neighbors) { Index nextIndex = this.Origins.First().CellToIndex + item; foreach (Index index in Index.Neighbors) { Index neighbor = nextIndex + index; if (this.Potentials.ContainsKey(this._cellularFloor.Cells[neighbor.I, neighbor.J])) { min = Math.Max(min, this.Potentials[this._cellularFloor.Cells[neighbor.I, neighbor.J]]); } } } } else // a neighborhood of size 1 will be chosen to { foreach (Cell cell in this.Origins) { foreach (Index index in Index.Neighbors) { Index neighbor = cell.CellToIndex + index; if (this.Potentials.ContainsKey(this._cellularFloor.Cells[neighbor.I, neighbor.J])) { min = Math.Max(min, this.Potentials[this._cellularFloor.Cells[neighbor.I, neighbor.J]]); } } } } List<UV> path = new List<UV>(); path.Add(p); UV previous = new UV(); UV current = p.Copy(); int n = 0; UV gradient = this.Differentiate(current); gradient.Unitize(); gradient *= distanceFactor; UV next = current + gradient; double? current_potential = this.GetPotential(p); double? previous_potential = current_potential; bool terminate = false; if (current_potential == null) { terminate = true; } if (current_potential.Value < min) { terminate = true; } while (!terminate) { path.Add(next); previous = current; current = next; gradient = this.Differentiate(current); gradient.Unitize(); gradient *= distanceFactor; next = current + gradient; /*check termination conditions*/ // 1- out of floor Index index = this._cellularFloor.FindIndex(next); if(!this.Potentials.ContainsKey(this._cellularFloor.Cells[index.I, index.J])) { MessageBox.Show("Path Was pushed outside floor!"); break; } current_potential = this.GetPotential(next); if (current_potential == null) { break; } // 2- increasing potentials /* This condition is numerically unstable and depends on the stepfactor! if (previous_potential.Value < current_potential.Value) { terminate = true; } previous_potential = current_potential; */ // 3- passing minimum threshold potential /* if (current_potential.Value < min) { terminate = true; } */ // 4- passing distance threshold to the default state if (UV.GetLengthSquared(current, this.DefaultState.Location) < distanceTolerance) { terminate = true; } // 5- iteration off limit n++; if (n > maxIterations) { MessageBox.Show("Maximum number of iterations in descending was riched\n" + maxIterations.ToString()); break; } } //double d = (destination - current).LengthSquared(); //MessageBox.Show("Iteration: " + n.ToString() + "\ndistance: " + d.ToString() + "\nDot: " + dot.ToString()); path.Add(this.DefaultState.Location); return path; } public override string ToString() { return this.Name; } } /// <summary> /// Represents the direction of interpolation on the surface of 2D data /// </summary> enum U_Or_V { U = 0, V = 1 } /// <summary> /// The range of neighborhood for interpolation either at horizontal or vertical directions. /// </summary> class IndexRange { private int length; /// <summary> /// Gets the length of index range. /// </summary> /// <value>The length.</value> public int Length { get { return this.length; } } public Direction Direction { get; set; } /// <summary> /// Gets or sets the minimum index. /// </summary> /// <value>The minimum.</value> public Index Min { get; set; } /// <summary> /// Gets or sets the maximum index. /// </summary> /// <value>The maximum.</value> public Index Max { get; set; } /// <summary> /// Initializes a new instance of the <see cref="IndexRange"/> class. /// </summary> /// <param name="min">The minimum index.</param> /// <param name="max">The maximum index.</param> /// <param name="direction">The direction.</param> public IndexRange(Index min, Index max, Direction direction) { this.Min = min; this.Max = max; this.Direction = direction; switch (this.Direction) { case Direction.Horizontal: this.length = this.Max.I - this.Min.I + 1; break; case Direction.Vertical: this.length = this.Max.J - this.Min.J + 1; break; default: break; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using TM.Data.Pluralsight.Json; using TM.Data.Pluralsight.Properties; using TM.Shared; using TM.Shared.DownloadManager; namespace TM.Data.Pluralsight { internal class PluralsightWebDataService : DataServiceBase { private readonly Uri _authorInfoUrl = new Uri("http://www.pluralsight.com/data/author/"); private readonly Uri _courseInfoUrl = new Uri("http://www.pluralsight.com/data/course/"); private readonly Uri _courseToCUrl = new Uri("http://www.pluralsight.com/data/course/content/"); private readonly Dictionary<string, string> _authorsInfoContainer; private readonly Dictionary<string, string> _coursesInfoContainer; private readonly Dictionary<string, string> _coursesToCContainer; private readonly AsyncLazy<Dictionary<string, Specializations>> _courseSpecializationsContainer; private readonly string _archiveCurrentSaveDirectory; private readonly IHttpDownloadManager _httpDownloadManager; private readonly bool _createArchives; public static PluralsightWebDataService CreateForDataQuery(IHttpDownloadManager httpDownloadManager) { return new PluralsightWebDataService(string.Empty, httpDownloadManager, Shared.FileSystemProxy.Instance, createArchives:false); } /// <exception cref="ArgumentNullException"> /// <paramref name="archiveCurrentSaveDirectory"/> or /// <paramref name="httpDownloadManager"/> or /// <paramref name="fileSystemProxy"/> is <see langword="null" />.</exception> public PluralsightWebDataService(string archiveCurrentSaveDirectory, IHttpDownloadManager httpDownloadManager, IFileSystemProxy fileSystemProxy, bool createArchives = true) : base(fileSystemProxy) { if (archiveCurrentSaveDirectory == null) throw new ArgumentNullException("archiveCurrentSaveDirectory"); if (httpDownloadManager == null) throw new ArgumentNullException("httpDownloadManager"); if (fileSystemProxy == null) throw new ArgumentNullException("fileSystemProxy"); _archiveCurrentSaveDirectory = archiveCurrentSaveDirectory; _httpDownloadManager = httpDownloadManager; _authorsInfoContainer = new Dictionary<string, string>(); _coursesInfoContainer = new Dictionary<string, string>(); _coursesToCContainer = new Dictionary<string, string>(); _courseSpecializationsContainer = new AsyncLazy<Dictionary<string, Specializations>>(async () => await InitializeCourseSpecializationContainerAsync()); _createArchives = createArchives; } #region DataServiceBase Overrides protected internal override async Task<string> GetAuthorJsonDataAsync(string urlName) { var requestUri = new Uri(_authorInfoUrl, urlName); var authorJsonData = await GetJsonDataAsync(requestUri); return authorJsonData; } protected override void UpdateAuthorsArchive(string urlName, string jsonData) { _authorsInfoContainer[urlName] = jsonData; } protected internal override async Task<string> GetCourseJsonDataAsync(string urlName) { var requestUri = new Uri(_courseInfoUrl, urlName); var courseJsonData = await GetJsonDataAsync(requestUri); return courseJsonData; } protected override void UpdateCourseArchive(string urlName, string jsonData) { _coursesInfoContainer[urlName] = jsonData; } protected internal override async Task<string> GetCourseToCJsonDataAsync(string urlName) { var requestUri = new Uri(_courseToCUrl, urlName); var courseToCJsonData = await GetJsonDataAsync(requestUri); return courseToCJsonData; } protected override void UpdateCourseToCArchive(string urlName, string jsonData) { _coursesToCContainer[urlName] = jsonData; } protected override async Task<Dictionary<string, Specializations>> InitializeCourseSpecializationContainerAsync() { var developerUrlNames = await GetCoursesUrlNamesForSpecializationAsync("developer"); var itAdministratorUrlNames = await GetCoursesUrlNamesForSpecializationAsync("it-ops"); var creativeProfessionalUrlNames = await GetCoursesUrlNamesForSpecializationAsync("creative"); var specializationsContainer = developerUrlNames .ToDictionary(x => x, x => Specializations.SoftwareDeveloper); AddSpecialization(specializationsContainer, itAdministratorUrlNames, Specializations.ITAdministrator); AddSpecialization(specializationsContainer, creativeProfessionalUrlNames, Specializations.CreativeProfessional); return specializationsContainer; } protected override async Task<Dictionary<string, Specializations>> GetInstanceOfCourseSpecializationsContainerAsync() { return await _courseSpecializationsContainer; } private bool _disposed; protected override void Dispose(bool disposing) { if ( _createArchives && disposing && !_disposed) { try { CreateArchives(); } catch { } _disposed = true; } base.Dispose(disposing); } #endregion #region Helpers /// <exception><see cref="DownloadException{T}"/> An error occurred while download.</exception> private async Task<string> GetJsonDataAsync(Uri requestUri) { var response = await _httpDownloadManager.DownloadAsStringAsync(requestUri, acceptMediaType: "application/json"); if (!response.IsSuccess) { // ReSharper disable once ExceptionNotDocumented throw new DownloadException<string>(Resources.DownloadException_Message, response); } return response.Result; } private async Task<List<string>> GetCoursesUrlNamesForSpecializationAsync(string specializationId) { int totalCourses; var downloadedCourses = 0; const int coursesToDownload = 500; var page = 1; var coursesUrlNames = new List<string>(); DownloadResult<string> response; do { var requestUri = new Uri(string.Format("http://www.pluralsight.com/data/courses/tags?id={0}&page={1}&pageSize={2}&sort=new&level=", specializationId, page, coursesToDownload)); response = await _httpDownloadManager.DownloadAsStringAsync(requestUri, acceptMediaType: "application/json"); if (response.IsSuccess) { var courseList = JsonConvert.DeserializeObject<JsonCourseList>(response.Result); totalCourses = courseList.totalNumberOfCoursesFound; downloadedCourses += courseList.courses.Length; coursesUrlNames.AddRange(courseList.courses.Select(x => x.name)); page++; } else { return null; } } while (response.IsSuccess && downloadedCourses != totalCourses); return coursesUrlNames; } private void AddSpecialization(Dictionary<string, Specializations> specializationsContainer, List<string> coursesUrlNames, Specializations specializationToAdd) { foreach (var urlName in coursesUrlNames) { Specializations currentSpecialization; if (specializationsContainer.TryGetValue(urlName, out currentSpecialization)) { specializationsContainer[urlName] = currentSpecialization | specializationToAdd; } else { specializationsContainer[urlName] = specializationToAdd; } } } internal void CreateArchives() { string archiveName; if (_authorsInfoContainer != null && _authorsInfoContainer.Any()) { archiveName = AuthorsArchiveNamePrefix + DateTime.UtcNow.ToString(DateTimeFormatPattern) + ArchiveFileExtension; CreateArchive(archiveName, _authorsInfoContainer); } if (_coursesInfoContainer != null && _coursesInfoContainer.Any()) { archiveName = CoursesArchiveNamePrefix + DateTime.UtcNow.ToString(DateTimeFormatPattern) + ArchiveFileExtension; CreateArchive(archiveName, _coursesInfoContainer); } if (_coursesToCContainer != null && _coursesToCContainer.Any()) { archiveName = CoursesToCArchiveNamePrefix + DateTime.UtcNow.ToString(DateTimeFormatPattern) + ArchiveFileExtension; CreateArchive(archiveName, _coursesToCContainer); } if (_courseSpecializationsContainer != null && _courseSpecializationsContainer.IsValueCreated) { archiveName = CourseSpecializationsArchiveNamePrefix + DateTime.UtcNow.ToString(DateTimeFormatPattern) + ArchiveFileExtension; CreateArchive(archiveName, _courseSpecializationsContainer.Value.Result); } } internal void CreateArchive<TValue>(string archiveName, Dictionary<string, TValue> archive) { var archiveFile = new ArchiveFile<TValue> { Date = DateTime.UtcNow, TrainingProviderName = TrainingProviderName, Content = archive }; var fileName = Path.Combine(_archiveCurrentSaveDirectory, archiveName); var enumConverter = new StringEnumConverter { AllowIntegerValues = false, CamelCaseText = false }; FileSystemProxy.WriteTextToNewFile(fileName, JsonConvert.SerializeObject(archiveFile, Formatting.Indented, enumConverter)); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Resources; using Microsoft.Build.CommandLine; using Microsoft.Build.Construction; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Shouldly; using Xunit; namespace Microsoft.Build.UnitTests { public class CommandLineSwitchesTests { public CommandLineSwitchesTests() { // Make sure resources are initialized MSBuildApp.Initialize(); } [Fact] public void BogusSwitchIdentificationTests() { CommandLineSwitches.ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; CommandLineSwitches.IsParameterlessSwitch("bogus", out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeFalse(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.Invalid); duplicateSwitchErrorMessage.ShouldBeNull(); CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch("bogus", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeFalse(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Invalid); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeFalse(); } [Theory] [InlineData("help")] [InlineData("HELP")] [InlineData("Help")] [InlineData("h")] [InlineData("H")] [InlineData("?")] public void HelpSwitchIdentificationTests(string help) { CommandLineSwitches.IsParameterlessSwitch(help, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.Help); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("version")] [InlineData("Version")] [InlineData("VERSION")] [InlineData("ver")] [InlineData("VER")] [InlineData("Ver")] public void VersionSwitchIdentificationTests(string version) { CommandLineSwitches.IsParameterlessSwitch(version, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.Version); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("nologo")] [InlineData("NOLOGO")] [InlineData("NoLogo")] public void NoLogoSwitchIdentificationTests(string nologo) { CommandLineSwitches.IsParameterlessSwitch(nologo, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.NoLogo); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("noautoresponse")] [InlineData("NOAUTORESPONSE")] [InlineData("NoAutoResponse")] [InlineData("noautorsp")] [InlineData("NOAUTORSP")] [InlineData("NoAutoRsp")] public void NoAutoResponseSwitchIdentificationTests(string noautoresponse) { CommandLineSwitches.IsParameterlessSwitch(noautoresponse, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("noconsolelogger")] [InlineData("NOCONSOLELOGGER")] [InlineData("NoConsoleLogger")] [InlineData("noconlog")] [InlineData("NOCONLOG")] [InlineData("NoConLog")] public void NoConsoleLoggerSwitchIdentificationTests(string noconsolelogger) { CommandLineSwitches.ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; CommandLineSwitches.IsParameterlessSwitch(noconsolelogger, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("fileLogger")] [InlineData("FILELOGGER")] [InlineData("FileLogger")] [InlineData("fl")] [InlineData("FL")] public void FileLoggerSwitchIdentificationTests(string filelogger) { CommandLineSwitches.ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; CommandLineSwitches.IsParameterlessSwitch(filelogger, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.FileLogger); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("distributedfilelogger")] [InlineData("DISTRIBUTEDFILELOGGER")] [InlineData("DistributedFileLogger")] [InlineData("dfl")] [InlineData("DFL")] public void DistributedFileLoggerSwitchIdentificationTests(string distributedfilelogger) { CommandLineSwitches.ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; CommandLineSwitches.IsParameterlessSwitch(distributedfilelogger, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("flp")] [InlineData("FLP")] [InlineData("fileLoggerParameters")] [InlineData("FILELOGGERPARAMETERS")] public void FileLoggerParametersIdentificationTests(string fileloggerparameters) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(fileloggerparameters, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } #if FEATURE_NODE_REUSE [Theory] [InlineData("nr")] [InlineData("NR")] [InlineData("nodereuse")] [InlineData("NodeReuse")] public void NodeReuseParametersIdentificationTests(string nodereuse) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(nodereuse, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.NodeReuse); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } #endif [Fact] public void ProjectSwitchIdentificationTests() { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; Assert.True(CommandLineSwitches.IsParameterizedSwitch(null, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed)); Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Project, parameterizedSwitch); Assert.NotNull(duplicateSwitchErrorMessage); Assert.False(multipleParametersAllowed); Assert.Null(missingParametersErrorMessage); Assert.True(unquoteParameters); // for the virtual project switch, we match on null, not empty string Assert.False(CommandLineSwitches.IsParameterizedSwitch(String.Empty, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed)); Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Invalid, parameterizedSwitch); Assert.Null(duplicateSwitchErrorMessage); Assert.False(multipleParametersAllowed); Assert.Null(missingParametersErrorMessage); Assert.False(unquoteParameters); } [Theory] [InlineData("ignoreprojectextensions")] [InlineData("IgnoreProjectExtensions")] [InlineData("IGNOREPROJECTEXTENSIONS")] [InlineData("ignore")] [InlineData("IGNORE")] public void IgnoreProjectExtensionsSwitchIdentificationTests(string ignoreprojectextensions) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(ignoreprojectextensions, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeTrue(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } [Theory] [InlineData("target")] [InlineData("TARGET")] [InlineData("Target")] [InlineData("t")] [InlineData("T")] public void TargetSwitchIdentificationTests(string target) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(target, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Target); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeTrue(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } [Theory] [InlineData("property")] [InlineData("PROPERTY")] [InlineData("Property")] [InlineData("p")] [InlineData("P")] public void PropertySwitchIdentificationTests(string property) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(property, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Property); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeTrue(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } [Theory] [InlineData("logger")] [InlineData("LOGGER")] [InlineData("Logger")] [InlineData("l")] [InlineData("L")] public void LoggerSwitchIdentificationTests(string logger) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(logger, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Logger); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeFalse(); } [Theory] [InlineData("verbosity")] [InlineData("VERBOSITY")] [InlineData("Verbosity")] [InlineData("v")] [InlineData("V")] public void VerbositySwitchIdentificationTests(string verbosity) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(verbosity, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Verbosity); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } [Theory] [InlineData("ds")] [InlineData("DS")] [InlineData("Ds")] [InlineData("detailedsummary")] [InlineData("DETAILEDSUMMARY")] [InlineData("DetailedSummary")] public void DetailedSummarySwitchIndentificationTests(string detailedsummary) { CommandLineSwitches.ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; CommandLineSwitches.IsParameterlessSwitch(detailedsummary, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue(); parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.DetailedSummary); duplicateSwitchErrorMessage.ShouldBeNull(); } [Theory] [InlineData("m")] [InlineData("M")] [InlineData("maxcpucount")] [InlineData("MAXCPUCOUNT")] public void MaxCPUCountSwitchIdentificationTests(string maxcpucount) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(maxcpucount, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.MaxCPUCount); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldNotBeNull(); unquoteParameters.ShouldBeTrue(); } #if FEATURE_XML_SCHEMA_VALIDATION [Theory] [InlineData("validate")] [InlineData("VALIDATE")] [InlineData("Validate")] [InlineData("val")] [InlineData("VAL")] [InlineData("Val")] public void ValidateSwitchIdentificationTests(string validate) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(validate, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Validate); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); } #endif [Theory] [InlineData("preprocess")] [InlineData("pp")] public void PreprocessSwitchIdentificationTests(string preprocess) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(preprocess, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Preprocess); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); } [Theory] [InlineData("targets")] [InlineData("tArGeTs")] [InlineData("ts")] public void TargetsSwitchIdentificationTests(string @switch) { CommandLineSwitches.IsParameterizedSwitch( @switch, out var parameterizedSwitch, out var duplicateSwitchErrorMessage, out var multipleParametersAllowed, out var missingParametersErrorMessage, out var unquoteParameters, out var emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Targets); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); emptyParametersAllowed.ShouldBeFalse(); } [Fact] public void TargetsSwitchParameter() { CommandLineSwitches switches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>() { "/targets:targets.txt" }, switches); switches.HaveErrors().ShouldBeFalse(); switches[CommandLineSwitches.ParameterizedSwitch.Targets].ShouldBe(new[] { "targets.txt" }); } [Fact] public void TargetsSwitchDoesNotSupportMultipleOccurrences() { CommandLineSwitches switches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>() { "/targets /targets" }, switches); switches.HaveErrors().ShouldBeTrue(); } [Theory] [InlineData("isolate")] [InlineData("ISOLATE")] [InlineData("isolateprojects")] [InlineData("isolateProjects")] public void IsolateProjectsSwitchIdentificationTests(string isolateprojects) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(isolateprojects, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.IsolateProjects); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); emptyParametersAllowed.ShouldBeFalse(); } [Theory] [InlineData("graph")] [InlineData("GRAPH")] [InlineData("graphbuild")] [InlineData("graphBuild")] public void GraphBuildSwitchIdentificationTests(string graph) { CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; bool emptyParametersAllowed; CommandLineSwitches.IsParameterizedSwitch(graph, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.GraphBuild); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); emptyParametersAllowed.ShouldBeFalse(); } [Theory] [InlineData("low")] [InlineData("LOW")] [InlineData("lowpriority")] [InlineData("lowPriority")] public void LowPrioritySwitchIdentificationTests(string lowpriority) { CommandLineSwitches.IsParameterizedSwitch(lowpriority, out CommandLineSwitches.ParameterizedSwitch parameterizedSwitch, out string duplicateSwitchErrorMessage, out bool multipleParametersAllowed, out string missingParametersErrorMessage, out bool unquoteParameters, out bool emptyParametersAllowed).ShouldBeTrue(); parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.LowPriority); duplicateSwitchErrorMessage.ShouldBeNull(); multipleParametersAllowed.ShouldBeFalse(); missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); emptyParametersAllowed.ShouldBeFalse(); } [Fact] public void InputResultsCachesSupportsMultipleOccurrence() { CommandLineSwitches switches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(){"/irc", "/irc:a;b", "/irc:c;d"}, switches); switches[CommandLineSwitches.ParameterizedSwitch.InputResultsCaches].ShouldBe(new []{null, "a", "b", "c", "d"}); switches.HaveErrors().ShouldBeFalse(); } [Fact] public void OutputResultsCache() { CommandLineSwitches switches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(){"/orc:a"}, switches); switches[CommandLineSwitches.ParameterizedSwitch.OutputResultsCache].ShouldBe(new []{"a"}); switches.HaveErrors().ShouldBeFalse(); } [Fact] public void OutputResultsCachesDoesNotSupportMultipleOccurrences() { CommandLineSwitches switches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(){"/orc:a", "/orc:b"}, switches); switches.HaveErrors().ShouldBeTrue(); } [Fact] public void SetParameterlessSwitchTests() { CommandLineSwitches switches = new CommandLineSwitches(); switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoLogo, "/nologo"); Assert.Equal("/nologo", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoLogo)); Assert.True(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoLogo)); Assert.True(switches[CommandLineSwitches.ParameterlessSwitch.NoLogo]); // set it again switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoLogo, "-NOLOGO"); Assert.Equal("-NOLOGO", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoLogo)); Assert.True(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoLogo)); Assert.True(switches[CommandLineSwitches.ParameterlessSwitch.NoLogo]); // we didn't set this switch Assert.Null(switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Version)); Assert.False(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Version)); Assert.False(switches[CommandLineSwitches.ParameterlessSwitch.Version]); } [Fact] public void SetParameterizedSwitchTests1() { CommandLineSwitches switches = new CommandLineSwitches(); Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/v:q", "q", false, true, false)); Assert.Equal("/v:q", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Verbosity)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Verbosity)); string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Verbosity]; Assert.NotNull(parameters); Assert.Single(parameters); Assert.Equal("q", parameters[0]); // set it again -- this is bogus, because the /verbosity switch doesn't allow multiple parameters, but for the // purposes of testing the SetParameterizedSwitch() method, it doesn't matter Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/verbosity:\"diag\";minimal", "\"diag\";minimal", true, true, false)); Assert.Equal("/v:q /verbosity:\"diag\";minimal", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Verbosity)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Verbosity)); parameters = switches[CommandLineSwitches.ParameterizedSwitch.Verbosity]; Assert.NotNull(parameters); Assert.Equal(3, parameters.Length); Assert.Equal("q", parameters[0]); Assert.Equal("diag", parameters[1]); Assert.Equal("minimal", parameters[2]); } [Fact] public void SetParameterizedSwitchTests2() { CommandLineSwitches switches = new CommandLineSwitches(); // we haven't set this switch yet Assert.Null(switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target)); Assert.False(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target]; Assert.NotNull(parameters); Assert.Empty(parameters); // fake/missing parameters -- this is bogus because the /target switch allows multiple parameters but we're turning // that off here just for testing purposes Assert.False(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:\"", "\"", false, true, false)); // switch has been set Assert.Equal("/t:\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target]; // but no parameters Assert.NotNull(parameters); Assert.Empty(parameters); // more fake/missing parameters Assert.False(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:A,\"\";B", "A,\"\";B", true, true, false)); Assert.Equal("/t:\" /t:A,\"\";B", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target]; // now we have some parameters Assert.NotNull(parameters); Assert.Equal(2, parameters.Length); Assert.Equal("A", parameters[0]); Assert.Equal("B", parameters[1]); } [Fact] public void SetParameterizedSwitchTests3() { CommandLineSwitches switches = new CommandLineSwitches(); // we haven't set this switch yet Assert.Null(switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger)); Assert.False(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger)); string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger]; Assert.NotNull(parameters); Assert.Empty(parameters); // don't unquote fake/missing parameters Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Logger, "/l:\"", "\"", false, false, false)); Assert.Equal("/l:\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger)); parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger]; Assert.NotNull(parameters); Assert.Single(parameters); Assert.Equal("\"", parameters[0]); // don't unquote multiple fake/missing parameters -- this is bogus because the /logger switch does not take multiple // parameters, but for testing purposes this is fine Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Logger, "/LOGGER:\"\",asm;\"p,a;r\"", "\"\",asm;\"p,a;r\"", true, false, false)); Assert.Equal("/l:\" /LOGGER:\"\",asm;\"p,a;r\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger)); parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger]; Assert.NotNull(parameters); Assert.Equal(4, parameters.Length); Assert.Equal("\"", parameters[0]); Assert.Equal("\"\"", parameters[1]); Assert.Equal("asm", parameters[2]); Assert.Equal("\"p,a;r\"", parameters[3]); } [Fact] public void SetParameterizedSwitchTestsAllowEmpty() { CommandLineSwitches switches = new CommandLineSwitches(); Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors, "/warnaserror", "", multipleParametersAllowed: true, unquoteParameters: false, emptyParametersAllowed: true)); Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors)); string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors]; Assert.NotNull(parameters); Assert.True(parameters.Length > 0); Assert.Null(parameters.Last()); } [Fact] public void AppendErrorTests1() { CommandLineSwitches switchesLeft = new CommandLineSwitches(); CommandLineSwitches switchesRight = new CommandLineSwitches(); Assert.False(switchesLeft.HaveErrors()); Assert.False(switchesRight.HaveErrors()); switchesLeft.Append(switchesRight); Assert.False(switchesLeft.HaveErrors()); Assert.False(switchesRight.HaveErrors()); switchesLeft.SetUnknownSwitchError("/bogus"); Assert.True(switchesLeft.HaveErrors()); Assert.False(switchesRight.HaveErrors()); switchesLeft.Append(switchesRight); Assert.True(switchesLeft.HaveErrors()); Assert.False(switchesRight.HaveErrors()); VerifySwitchError(switchesLeft, "/bogus"); switchesRight.Append(switchesLeft); Assert.True(switchesLeft.HaveErrors()); Assert.True(switchesRight.HaveErrors()); VerifySwitchError(switchesLeft, "/bogus"); VerifySwitchError(switchesRight, "/bogus"); } [Fact] public void AppendErrorTests2() { CommandLineSwitches switchesLeft = new CommandLineSwitches(); CommandLineSwitches switchesRight = new CommandLineSwitches(); Assert.False(switchesLeft.HaveErrors()); Assert.False(switchesRight.HaveErrors()); switchesLeft.SetUnknownSwitchError("/bogus"); switchesRight.SetUnexpectedParametersError("/nologo:foo"); Assert.True(switchesLeft.HaveErrors()); Assert.True(switchesRight.HaveErrors()); VerifySwitchError(switchesLeft, "/bogus"); VerifySwitchError(switchesRight, "/nologo:foo"); switchesLeft.Append(switchesRight); VerifySwitchError(switchesLeft, "/bogus"); VerifySwitchError(switchesRight, "/nologo:foo"); } [Fact] public void AppendParameterlessSwitchesTests() { CommandLineSwitches switchesLeft = new CommandLineSwitches(); switchesLeft.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.Help, "/?"); Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.False(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); CommandLineSwitches switchesRight1 = new CommandLineSwitches(); switchesRight1.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, "/noconlog"); Assert.False(switchesRight1.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.True(switchesRight1.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); switchesLeft.Append(switchesRight1); Assert.Equal("/noconlog", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger]); // this switch is not affected Assert.Equal("/?", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.Help]); CommandLineSwitches switchesRight2 = new CommandLineSwitches(); switchesRight2.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, "/NOCONSOLELOGGER"); Assert.False(switchesRight2.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.True(switchesRight2.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); switchesLeft.Append(switchesRight2); Assert.Equal("/NOCONSOLELOGGER", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger)); Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger]); Assert.Equal("/?", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help)); Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.Help]); Assert.False(switchesLeft.HaveErrors()); } [Fact] public void AppendParameterizedSwitchesTests1() { CommandLineSwitches switchesLeft = new CommandLineSwitches(); switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "tempproject.proj", "tempproject.proj", false, true, false); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project)); Assert.False(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); CommandLineSwitches switchesRight = new CommandLineSwitches(); switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:build", "build", true, true, false); Assert.False(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project)); Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); switchesLeft.Append(switchesRight); Assert.Equal("tempproject.proj", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Project)); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project)); string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Project]; Assert.NotNull(parameters); Assert.Single(parameters); Assert.Equal("tempproject.proj", parameters[0]); Assert.Equal("/t:build", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target)); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Target]; Assert.NotNull(parameters); Assert.Single(parameters); Assert.Equal("build", parameters[0]); } [Fact] public void AppendParameterizedSwitchesTests2() { CommandLineSwitches switchesLeft = new CommandLineSwitches(); switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/target:Clean", "Clean", true, true, false); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); CommandLineSwitches switchesRight = new CommandLineSwitches(); switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:\"RESOURCES\";build", "\"RESOURCES\";build", true, true, false); Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); switchesLeft.Append(switchesRight); Assert.Equal("/t:\"RESOURCES\";build", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target)); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target)); string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Target]; Assert.NotNull(parameters); Assert.Equal(3, parameters.Length); Assert.Equal("Clean", parameters[0]); Assert.Equal("RESOURCES", parameters[1]); Assert.Equal("build", parameters[2]); } [Fact] public void AppendParameterizedSwitchesTests3() { CommandLineSwitches switchesLeft = new CommandLineSwitches(); switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "tempproject.proj", "tempproject.proj", false, true, false); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project)); CommandLineSwitches switchesRight = new CommandLineSwitches(); switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "Rhubarb.proj", "Rhubarb.proj", false, true, false); Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project)); switchesLeft.Append(switchesRight); Assert.Equal("tempproject.proj", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Project)); Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project)); string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Project]; Assert.NotNull(parameters); Assert.Single(parameters); Assert.Equal("tempproject.proj", parameters[0]); Assert.True(switchesLeft.HaveErrors()); VerifySwitchError(switchesLeft, "Rhubarb.proj"); } [Fact] public void InvalidToolsVersionErrors() { Assert.Throws<InitializationException>(() => { string filename = null; try { filename = FileUtilities.GetTemporaryFile(); ProjectRootElement project = ProjectRootElement.Create(); project.Save(filename); MSBuildApp.BuildProject( filename, null, "ScoobyDoo", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), new ILogger[] { }, LoggerVerbosity.Normal, new DistributedLoggerRecord[] { }, #if FEATURE_XML_SCHEMA_VALIDATION false, null, #endif 1, true, new StringWriter(), new StringWriter(), false, warningsAsErrors: null, warningsAsMessages: null, enableRestore: false, profilerLogger: null, enableProfiler: false, interactive: false, isolateProjects: false, graphBuild: false, lowPriority: false, inputResultsCaches: null, outputResultsCache: null ); } finally { if (File.Exists(filename)) File.Delete(filename); } } ); } [Fact] public void TestHaveAnySwitchesBeenSet() { // Check if method works with parameterized switch CommandLineSwitches switches = new CommandLineSwitches(); Assert.False(switches.HaveAnySwitchesBeenSet()); switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/v:q", "q", false, true, false); Assert.True(switches.HaveAnySwitchesBeenSet()); // Check if method works with parameterless switches switches = new CommandLineSwitches(); Assert.False(switches.HaveAnySwitchesBeenSet()); switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.Help, "/?"); Assert.True(switches.HaveAnySwitchesBeenSet()); } #if FEATURE_NODE_REUSE /// <summary> /// /nodereuse:false /nodereuse:true should result in "true" /// </summary> [Fact] public void ProcessNodeReuseSwitchTrueLast() { bool nodeReuse = MSBuildApp.ProcessNodeReuseSwitch(new string[] { "false", "true" }); Assert.True(nodeReuse); } /// <summary> /// /nodereuse:true /nodereuse:false should result in "false" /// </summary> [Fact] public void ProcessNodeReuseSwitchFalseLast() { bool nodeReuse = MSBuildApp.ProcessNodeReuseSwitch(new string[] { "true", "false" }); Assert.False(nodeReuse); } #endif /// <summary> /// Regress DDB #143341: /// msbuild /clp:v=quiet /clp:v=diag /m:2 /// gave console logger in quiet verbosity; expected diagnostic /// </summary> [Fact] public void ExtractAnyLoggerParameterPickLast() { string result = MSBuildApp.ExtractAnyLoggerParameter("v=diag;v=q", new string[] { "v", "verbosity" }); Assert.Equal("v=q", result); } /// <summary> /// Verifies that when the /warnaserror switch is not specified, the set of warnings is null. /// </summary> [Fact] public void ProcessWarnAsErrorSwitchNotSpecified() { CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "" }), commandLineSwitches); Assert.Null(MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches)); } /// <summary> /// Verifies that the /warnaserror switch is parsed properly when codes are specified. /// </summary> [Fact] public void ProcessWarnAsErrorSwitchWithCodes() { ISet<string> expectedWarningsAsErrors = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "B", "c", "D", "e" }; CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "\"/warnaserror: a,B ; c \"", // Leading, trailing, leading and trailing whitespace "/warnaserror:A,b,C", // Repeats of different case "\"/warnaserror:, ,,\"", // Empty items "/err:D,d;E,e", // A different source with new items and uses the short form "/warnaserror:a", // A different source with a single duplicate "/warnaserror:a,b", // A different source with multiple duplicates }), commandLineSwitches); ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches); Assert.NotNull(actualWarningsAsErrors); Assert.Equal(expectedWarningsAsErrors, actualWarningsAsErrors, StringComparer.OrdinalIgnoreCase); } /// <summary> /// Verifies that an empty /warnaserror switch clears the list of codes. /// </summary> [Fact] public void ProcessWarnAsErrorSwitchEmptySwitchClearsSet() { CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "/warnaserror:a;b;c", "/warnaserror", }), commandLineSwitches); ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches); Assert.NotNull(actualWarningsAsErrors); Assert.Empty(actualWarningsAsErrors); } /// <summary> /// Verifies that when values are specified after an empty /warnaserror switch that they are added to the cleared list. /// </summary> [Fact] public void ProcessWarnAsErrorSwitchValuesAfterEmptyAddOn() { ISet<string> expectedWarningsAsErors = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "e", "f", "g" }; CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "/warnaserror:a;b;c", "/warnaserror", "/warnaserror:e;f;g", }), commandLineSwitches); ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches); Assert.NotNull(actualWarningsAsErrors); Assert.Equal(expectedWarningsAsErors, actualWarningsAsErrors, StringComparer.OrdinalIgnoreCase); } /// <summary> /// Verifies that the /warnaserror switch is parsed properly when no codes are specified. /// </summary> [Fact] public void ProcessWarnAsErrorSwitchEmpty() { CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new [] { "/warnaserror" }), commandLineSwitches); ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches); Assert.NotNull(actualWarningsAsErrors); Assert.Empty(actualWarningsAsErrors); } /// <summary> /// Verifies that when the /warnasmessage switch is used with no values that an error is shown. /// </summary> [Fact] public void ProcessWarnAsMessageSwitchEmpty() { CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "/warnasmessage" }), commandLineSwitches); VerifySwitchError(commandLineSwitches, "/warnasmessage", AssemblyResources.GetString("MissingWarnAsMessageParameterError")); } /// <summary> /// Verifies that the /warnasmessage switch is parsed properly when codes are specified. /// </summary> [Fact] public void ProcessWarnAsMessageSwitchWithCodes() { ISet<string> expectedWarningsAsMessages = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "B", "c", "D", "e" }; CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "\"/warnasmessage: a,B ; c \"", // Leading, trailing, leading and trailing whitespace "/warnasmessage:A,b,C", // Repeats of different case "\"/warnasmessage:, ,,\"", // Empty items "/nowarn:D,d;E,e", // A different source with new items and uses the short form "/warnasmessage:a", // A different source with a single duplicate "/warnasmessage:a,b", // A different source with multiple duplicates }), commandLineSwitches); ISet<string> actualWarningsAsMessages = MSBuildApp.ProcessWarnAsMessageSwitch(commandLineSwitches); Assert.NotNull(actualWarningsAsMessages); Assert.Equal(expectedWarningsAsMessages, actualWarningsAsMessages, StringComparer.OrdinalIgnoreCase); } /// <summary> /// Verifies that when the /profileevaluation switch is used with no values "no-file" is specified. /// </summary> [Fact] public void ProcessProfileEvaluationEmpty() { CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); MSBuildApp.GatherCommandLineSwitches(new List<string>(new[] { "/profileevaluation" }), commandLineSwitches); commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.ProfileEvaluation][0].ShouldBe("no-file"); } [Fact] public void ProcessBooleanSwitchTest() { MSBuildApp.ProcessBooleanSwitch(new string[0], defaultValue: true, resourceName: null).ShouldBeTrue(); MSBuildApp.ProcessBooleanSwitch(new string[0], defaultValue: false, resourceName: null).ShouldBeFalse(); MSBuildApp.ProcessBooleanSwitch(new [] { "true" }, defaultValue: false, resourceName: null).ShouldBeTrue(); MSBuildApp.ProcessBooleanSwitch(new[] { "false" }, defaultValue: true, resourceName: null).ShouldBeFalse(); Should.Throw<CommandLineSwitchException>(() => MSBuildApp.ProcessBooleanSwitch(new[] { "invalid" }, defaultValue: true, resourceName: "InvalidRestoreValue")); } /// <summary> /// Verifies that when the /profileevaluation switch is used with invalid filenames an error is shown. /// </summary> [MemberData(nameof(GetInvalidFilenames))] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")] [Theory] public void ProcessProfileEvaluationInvalidFilename(string filename) { bool enableProfiler = false; Should.Throw( () => MSBuildApp.ProcessProfileEvaluationSwitch(new[] {filename}, new List<ILogger>(), out enableProfiler), typeof(CommandLineSwitchException)); } public static IEnumerable<object[]> GetInvalidFilenames() { yield return new object[] { $"a_file_with${Path.GetInvalidFileNameChars().First()}invalid_chars" }; yield return new object[] { $"C:\\a_path\\with{Path.GetInvalidPathChars().First()}invalid\\chars" }; } #if FEATURE_RESOURCEMANAGER_GETRESOURCESET /// <summary> /// Verifies that help messages are correctly formed with the right width and leading spaces. /// </summary> [Fact] public void HelpMessagesAreValid() { ResourceManager resourceManager = new ResourceManager("MSBuild.Strings", typeof(AssemblyResources).Assembly); const string switchLeadingSpaces = " "; const string otherLineLeadingSpaces = " "; const string examplesLeadingSpaces = " "; foreach (KeyValuePair<string, string> item in resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, createIfNotExists: true, tryParents: true) .Cast<DictionaryEntry>().Where(i => i.Key is string && ((string)i.Key).StartsWith("HelpMessage_")) .Select(i => new KeyValuePair<string, string>((string)i.Key, (string)i.Value))) { string[] helpMessageLines = item.Value.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < helpMessageLines.Length; i++) { // All lines should be 80 characters or less Assert.True(helpMessageLines[i].Length <= 80, $"Line {i + 1} of '{item.Key}' should be no longer than 80 characters."); string trimmedLine = helpMessageLines[i].Trim(); if (i == 0) { if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("@")) { // If the first line in a switch it needs a certain amount of leading spaces Assert.StartsWith(switchLeadingSpaces, helpMessageLines[i]); } else { // Otherwise it should have no leading spaces because it's a section Assert.False(helpMessageLines[i].StartsWith(" ")); } } else { // Ignore empty lines if (!String.IsNullOrWhiteSpace(helpMessageLines[i])) { if (item.Key.Contains("Examples")) { // Examples require a certain number of leading spaces Assert.StartsWith(examplesLeadingSpaces, helpMessageLines[i]); } else if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("@")) { // Switches require a certain number of leading spaces Assert.StartsWith(switchLeadingSpaces, helpMessageLines[i]); } else { // All other lines require a certain number of leading spaces Assert.StartsWith(otherLineLeadingSpaces, helpMessageLines[i]); } } } } } } #endif /// <summary> /// Verifies that a switch collection has an error registered for the given command line arg. /// </summary> private void VerifySwitchError(CommandLineSwitches switches, string badCommandLineArg, string expectedMessage = null) { bool caughtError = false; try { switches.ThrowErrors(); } catch (CommandLineSwitchException e) { Assert.Equal(badCommandLineArg, e.CommandLineArg); caughtError = true; if (expectedMessage != null) { Assert.Contains(expectedMessage, e.Message); } // so I can see the message in NUnit's "Standard Out" window Console.WriteLine(e.Message); } finally { Assert.True(caughtError); } } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ namespace UniversalDetector.Core { public abstract class HebrewModel : SequenceModel { //Model Table: //total sequences: 100% //first 512 sequences: 98.4004% //first 1024 sequences: 1.5981% //rest sequences: 0.087% //negative sequences: 0.0015% private readonly static byte[] HEBREW_LANG_MODEL = { 0,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,2,1,2,0,1,0,0, 3,0,3,1,0,0,1,3,2,0,1,1,2,0,2,2,2,1,1,1,1,2,1,1,1,2,0,0,2,2,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2, 1,2,1,2,1,2,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2, 1,2,1,3,1,1,0,0,2,0,0,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,1,2,2,1,3, 1,2,1,1,2,2,0,0,2,2,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,2,3,2, 1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,2,3,2,2,2,1,2,2,2,2, 1,2,1,1,2,2,0,1,2,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,2,2,2,2,2, 0,2,0,2,2,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,2,2,2, 0,2,1,2,2,2,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,2,3,2,2,2, 1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,2,0,2, 0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,2,3,2,1,2,1,1,1, 0,1,1,1,1,1,3,0,1,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0, 0,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,2,1,2,3,3,2,3,3,3,3,2,3,2,1,2,0,2,1,2, 0,2,0,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,1,2,2,3,3,2,3,2,3,2,2,3,1,2,2,0,2,2,2, 0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,2,2,3,3,3,3,1,3,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,2,3,2,2,2,1,2,2,0,2,2,2,2, 0,2,0,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,1,3,2,3,3,2,3,3,2,2,1,2,2,2,2,2,2, 0,2,1,2,1,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,2,3,3,2,3,3,3,3,2,3,2,3,3,3,3,3,2,2,2,2,2,2,2,1, 0,2,0,1,2,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,1,2,3,3,3,3,3,3,3,2,3,2,3,2,1,2,3,0,2,1,2,2, 0,2,1,1,2,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,2,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,1,3,1,2,2,2,1,2,3,3,1,2,1,2,2,2,2, 0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,0,2,3,3,3,1,3,3,3,1,2,2,2,2,1,1,2,2,2,2,2,2, 0,2,0,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,2,2,3,3,3,2,1,2,3,2,3,2,2,2,2,1,2,1,1,1,2,2, 0,2,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0, 1,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,3,2,3,1,2,2,2,2,3,2,3,1,1,2,2,1,2,2,1,1,0,2,2,2,2, 0,1,0,1,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,0,0,1,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 3,2,2,1,2,2,2,2,2,2,2,1,2,2,1,2,2,1,1,1,1,1,1,1,1,2,1,1,0,3,3,3, 0,3,0,2,2,2,2,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,1,2,2,2,1,1,1,2,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,0,0,0,0,0,0, 0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,0,2,1,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 0,3,1,1,2,2,2,2,2,1,2,2,2,1,1,2,2,2,2,2,2,2,1,2,2,1,0,1,1,1,1,0, 0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,1,1,1,1,2,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,0,0, 2,1,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,1,2,1,2,1,1,1,1,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,1,2,1,1,1,2,1,2,1,2,0,1,0,1, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,1,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,2,1,2,1,1,0,1,0,1, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,0,0, 0,1,1,1,2,1,2,2,2,0,2,0,2,0,1,1,2,1,1,1,1,2,1,0,1,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,0,0,1,0,1,2,2,0,1,0,0,1,1,2,2,1,2,0,2,0,0,0,1,2,0,1, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,2,1,2,0,2,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,1,2,2,0,0,1,0,0,0,1,0,0,1, 1,1,2,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,2,1, 0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1, 2,0,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,2,1,1,2,0,1,0,0,0,1,1,0,1, 1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,0,0,2,1,1,2,0,2,0,0,0,1,1,0,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,2,2,1,2,1,1,0,1,0,0,0,1,1,0,1, 2,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,2,1,1,1,0,2,1,1,0,0,0,2,1,0,1, 1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,0,2,1,1,0,1,0,0,0,1,1,0,1, 2,2,1,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,0,1,2,1,0,2,0,0,0,1,1,0,1, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, 0,1,0,0,2,0,2,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1, 1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,2,1,1,1,1,1,0,1,0,0,0,0,1,0,1, 0,1,1,1,2,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,1,0,0,0,0,0,1,1,1,1,1,0,1,0,0,0,1,1,0,0, }; public HebrewModel(byte[] charToOrderMap, string name) : base(charToOrderMap, HEBREW_LANG_MODEL, 0.984004f, false, name) { } } public class Win1255Model : HebrewModel { /* 255: Control characters that usually does not exist in any text 254: Carriage/Return 253: symbol (punctuation) that does not belong to word 252: 0 - 9 */ //Windows-1255 language model //Character Mapping Table: private readonly static byte[] WIN1255_CHAR_TO_ORDER_MAP = { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 +253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 69, 91, 79, 80, 92, 89, 97, 90, 68,111,112, 82, 73, 95, 85, //40 78,121, 86, 71, 67,102,107, 84,114,103,115,253,253,253,253,253, //50 253, 50, 74, 60, 61, 42, 76, 70, 64, 53,105, 93, 56, 65, 54, 49, //60 66,110, 51, 43, 44, 63, 81, 77, 98, 75,108,253,253,253,253,253, //70 124,202,203,204,205, 40, 58,206,207,208,209,210,211,212,213,214, 215, 83, 52, 47, 46, 72, 32, 94,216,113,217,109,218,219,220,221, 34,116,222,118,100,223,224,117,119,104,125,225,226, 87, 99,227, 106,122,123,228, 55,229,230,101,231,232,120,233, 48, 39, 57,234, 30, 59, 41, 88, 33, 37, 36, 31, 29, 35,235, 62, 28,236,126,237, 238, 38, 45,239,240,241,242,243,127,244,245,246,247,248,249,250, 9, 8, 20, 16, 3, 2, 24, 14, 22, 1, 25, 15, 4, 11, 6, 23, 12, 19, 13, 26, 18, 27, 21, 17, 7, 10, 5,251,252,128, 96,253, }; public Win1255Model() : base(WIN1255_CHAR_TO_ORDER_MAP, "windows-1255") { } } }
//----------------------------------------------------------------------- // <copyright file="DataPortalException.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This exception is returned for any errors occuring</summary> //----------------------------------------------------------------------- using System; #if !NETFX_CORE using System.Security.Permissions; #endif namespace Csla { /// <summary> /// This exception is returned for any errors occurring /// during the server-side DataPortal invocation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] [Serializable] public class DataPortalException : Exception { /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message">Text describing the exception.</param> /// <param name="businessObject">The business object /// as it was at the time of the exception.</param> public DataPortalException(string message, object businessObject) : base(message) { _innerStackTrace = String.Empty; _businessObject = businessObject; } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message">Text describing the exception.</param> /// <param name="ex">Inner exception.</param> /// <param name="businessObject">The business object /// as it was at the time of the exception.</param> public DataPortalException(string message, Exception ex, object businessObject) : base(message, ex) { _innerStackTrace = ex.StackTrace; _businessObject = businessObject; } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message"> /// Exception message. /// </param> /// <param name="ex"> /// Inner exception. /// </param> public DataPortalException(string message, Exception ex) : base(message, ex) { _innerStackTrace = ex.StackTrace; } #if !NETFX_PHONE || PCL46 || PCL259 #if !NETCORE && !PCL46 && !ANDROID && !NETSTANDARD2_0 && !PCL259 /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="info">Info about the exception.</param> public DataPortalException(WcfPortal.WcfErrorInfo info) : base(info.Message) { this.ErrorInfo = new Csla.Server.Hosts.HttpChannel.HttpErrorInfo(info); } #endif /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="info">Info about the exception.</param> public DataPortalException(Csla.Server.Hosts.HttpChannel.HttpErrorInfo info) : base(info.Message) { this.ErrorInfo = info; } /// <summary> /// Gets a string representation /// of this object. /// </summary> public override string ToString() { var sb = new System.Text.StringBuilder(); sb.AppendLine(base.ToString()); if (ErrorInfo != null) { sb.AppendLine("------------------------------"); var error = this.ErrorInfo; while (error != null) { sb.AppendFormat("{0}: {1}", error.ExceptionTypeName, error.Message); sb.Append(Environment.NewLine); sb.Append(error.StackTrace); sb.Append(Environment.NewLine); error = error.InnerError; } } return sb.ToString(); } /// <summary> /// Gets information about the original /// server-side exception. That exception /// is not an exception on the client side, /// but this property returns information /// about the exception. /// </summary> public Csla.Server.Hosts.HttpChannel.HttpErrorInfo ErrorInfo { get; private set; } #endif private object _businessObject; private string _innerStackTrace; /// <summary> /// Returns a reference to the business object /// from the server-side DataPortal. /// </summary> /// <remarks> /// Remember that this object may be in an invalid /// or undefined state. This is the business object /// (and any child objects) as it existed when the /// exception occured on the server. Thus the object /// state may have been altered by the server and /// may no longer reflect data in the database. /// </remarks> public object BusinessObject { get { return _businessObject; } } /// <summary> /// Gets the original server-side exception. /// </summary> /// <returns>An exception object.</returns> /// <remarks> /// When an exception occurs in business code behind /// the data portal, it is wrapped in a /// <see cref="Csla.Server.DataPortalException"/>, which /// is then wrapped in a /// <see cref="Csla.DataPortalException"/>. This property /// unwraps and returns the original exception /// thrown by the business code on the server. /// </remarks> public Exception BusinessException { get { var result = this.InnerException; if (result != null) result = result.InnerException; if (result is DataPortalException dpe && dpe.InnerException != null) result = dpe.InnerException; if (result is Csla.Reflection.CallMethodException cme && cme.InnerException != null) result = cme.InnerException; return result; } } /// <summary> /// Get the combined stack trace from the server /// and client. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)")] public override string StackTrace { get { return String.Format("{0}{1}{2}", _innerStackTrace, Environment.NewLine, base.StackTrace); } } #if !(ANDROID || IOS) && !NETFX_CORE && !NETSTANDARD2_0 /// <summary> /// Creates an instance of the object for serialization. /// </summary> /// <param name="info">Serialiation info object.</param> /// <param name="context">Serialization context object.</param> protected DataPortalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _businessObject = info.GetValue("_businessObject", typeof(object)); _innerStackTrace = info.GetString("_innerStackTrace"); } /// <summary> /// Serializes the object. /// </summary> /// <param name="info">Serialiation info object.</param> /// <param name="context">Serialization context object.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("_businessObject", _businessObject); info.AddValue("_innerStackTrace", _innerStackTrace); } #endif } }
using System; using FluentAssertions.Execution; using Xunit; using Xunit.Sdk; namespace FluentAssertions.Specs { public class NullableBooleanAssertionSpecs { [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_have_a_value_it_should_succeed() { bool? nullableBoolean = true; nullableBoolean.Should().HaveValue(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_not_be_null_it_should_succeed() { bool? nullableBoolean = true; nullableBoolean.Should().NotBeNull(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail() { bool? nullableBoolean = null; Action act = () => nullableBoolean.Should().HaveValue(); act.ShouldThrow<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_not_be_null_it_should_fail() { bool? nullableBoolean = null; Action act = () => nullableBoolean.Should().NotBeNull(); act.ShouldThrow<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail_with_descriptive_message() { bool? nullableBoolean = null; var assertions = nullableBoolean.Should(); assertions.Invoking(x => x.HaveValue("because we want to test the failure {0}", "message")) .ShouldThrow<XunitException>() .WithMessage("Expected a value because we want to test the failure message."); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_not_be_null_it_should_fail_with_descriptive_message() { bool? nullableBoolean = null; var assertions = nullableBoolean.Should(); assertions.Invoking(x => x.NotBeNull("because we want to test the failure {0}", "message")) .ShouldThrow<XunitException>() .WithMessage("Expected a value because we want to test the failure message."); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_not_have_a_value_it_should_succeed() { bool? nullableBoolean = null; nullableBoolean.Should().NotHaveValue(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_be_null_it_should_succeed() { bool? nullableBoolean = null; nullableBoolean.Should().BeNull(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_not_have_a_value_it_should_fail() { bool? nullableBoolean = true; Action act = () => nullableBoolean.Should().NotHaveValue(); act.ShouldThrow<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail() { bool? nullableBoolean = true; Action act = () => nullableBoolean.Should().BeNull(); act.ShouldThrow<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_be_not_have_a_value_it_should_fail_with_descriptive_message() { bool? nullableBoolean = true; var assertions = nullableBoolean.Should(); assertions.Invoking(x => x.NotHaveValue("because we want to test the failure {0}", "message")) .ShouldThrow<XunitException>() .WithMessage("Did not expect a value because we want to test the failure message, but found True."); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail_with_descriptive_message() { bool? nullableBoolean = true; var assertions = nullableBoolean.Should(); assertions.Invoking(x => x.BeNull("because we want to test the failure {0}", "message")) .ShouldThrow<XunitException>() .WithMessage("Did not expect a value because we want to test the failure message, but found True."); } [Fact] public void When_asserting_boolean_null_value_is_false_it_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().BeFalse("we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<XunitException>() .WithMessage("Expected False because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_boolean_null_value_is_true_it_sShould_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().BeTrue("we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<XunitException>() .WithMessage("Expected True because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_boolean_null_value_to_be_equal_to_different_nullable_boolean_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; bool? differentNullableBoolean = false; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().Be(differentNullableBoolean, "we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<XunitException>() .WithMessage("Expected False because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_boolean_null_value_to_be_equal_to_null_it_sShould_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; bool? otherNullableBoolean = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().Be(otherNullableBoolean); //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [Fact] public void When_asserting_true_is_not_false_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? trueBoolean = true; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => trueBoolean.Should().NotBeFalse(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [Fact] public void When_asserting_null_is_not_false_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? nullValue = null; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => nullValue.Should().NotBeFalse(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [Fact] public void When_asserting_false_is_not_false_it_should_fail_with_descriptive_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? falseBoolean = false; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => falseBoolean.Should().NotBeFalse("we want to test the failure message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldThrow<XunitException>() .WithMessage("Expected*nullable*boolean*not*False*because we want to test the failure message, but found False."); } [Fact] public void When_asserting_false_is_not_true_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? trueBoolean = false; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => trueBoolean.Should().NotBeTrue(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [Fact] public void When_asserting_null_is_not_true_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? nullValue = null; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => nullValue.Should().NotBeTrue(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [Fact] public void When_asserting_true_is_not_true_it_should_fail_with_descriptive_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? falseBoolean = true; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => falseBoolean.Should().NotBeTrue("we want to test the failure message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldThrow<XunitException>() .WithMessage("Expected*nullable*boolean*not*True*because we want to test the failure message, but found True."); } [Fact] public void Should_support_chaining_constraints_with_and() { bool? nullableBoolean = true; nullableBoolean.Should() .HaveValue() .And .BeTrue(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Text.Primitives.Tests.Encoding { public class Utf8EncoderTests { public static object[][] TryEncodeFromUTF16ToUTF8TestData = { // empty new object[] { true, new byte[] { }, new char[]{ (char)0x0050 }, false }, // multiple bytes new object[] { true, new byte[] { 0x50, 0xCF, 0xA8, 0xEA, 0xBF, 0x88, 0xF0, 0xA4, 0xA7, 0xB0 }, new char[]{ (char)0x0050, (char)0x03E8, (char)0xAFC8, (char)0xD852, (char)0xDDF0 }, true }, }; [Theory, MemberData("TryEncodeFromUTF16ToUTF8TestData")] public void UTF16ToUTF8EncodingTestForReadOnlySpanOfChar(bool useUtf8Encoder, byte[] expectedBytes, char[] chars, bool expectedReturnVal) { TextEncoder encoder = useUtf8Encoder ? TextEncoder.Utf8 : TextEncoder.Utf16; ReadOnlySpan<char> characters = new ReadOnlySpan<char>(chars); Span<byte> buffer = new Span<byte>(new byte[expectedBytes.Length]); int bytesWritten; int consumed; Assert.Equal(expectedReturnVal, encoder.TryEncode(characters, buffer, out consumed, out bytesWritten)); Assert.Equal(expectedReturnVal ? expectedBytes.Length : 0, bytesWritten); if (expectedReturnVal) { Assert.Equal(characters.Length, consumed); Assert.True(AreByteArraysEqual(expectedBytes, buffer.ToArray())); } } public static object[][] TryEncodeFromUnicodeMultipleCodePointsTestData = { // empty new object[] { true, new byte[] { }, new uint[] { 0x50 }, false }, new object[] { false, new byte[] { }, new uint[] { 0x50 }, false }, // multiple bytes new object[] { true, new byte[] { 0x50, 0xCF, 0xA8, 0xEA, 0xBF, 0x88, 0xF0, 0xA4, 0xA7, 0xB0 }, new uint[] { 0x50, 0x3E8, 0xAFC8, 0x249F0 } , true }, new object[] { false, new byte[] { 0x50, 0x00, 0xE8, 0x03, 0xC8, 0xAF, 0x52, 0xD8, 0xF0, 0xDD }, new uint[] { 0x50, 0x3E8, 0xAFC8, 0x249F0 } , true }, // multiple bytes - buffer too small new object[] { true, new byte[] { 0x50 }, new uint[] { 0x50, 0x3E8, 0xAFC8, 0x249F0 } , false }, new object[] { false, new byte[] { 0x50, 0x00 }, new uint[] { 0x50, 0x3E8, 0xAFC8, 0x249F0 } , false }, }; [Theory, MemberData("TryEncodeFromUnicodeMultipleCodePointsTestData")] public void TryEncodeFromUnicodeMultipleCodePoints(bool useUtf8Encoder, byte[] expectedBytes, uint[] codePointsArray, bool expectedReturnVal) { TextEncoder encoder = useUtf8Encoder ? TextEncoder.Utf8 : TextEncoder.Utf16; ReadOnlySpan<uint> codePoints = new ReadOnlySpan<uint>(codePointsArray); Span<byte> buffer = new Span<byte>(new byte[expectedBytes.Length]); int bytesWritten; int consumed; Assert.Equal(expectedReturnVal, encoder.TryEncode(codePoints, buffer, out consumed, out bytesWritten)); Assert.Equal(expectedBytes.Length, bytesWritten); if (expectedReturnVal) { Assert.Equal(codePoints.Length, consumed); Assert.True(AreByteArraysEqual(expectedBytes, buffer.ToArray())); } } public static object[][] TryDecodeToUnicodeMultipleCodePointsTestData = { //empty new object[] { true, new uint[] {}, new byte[] {}, true }, new object[] { false, new uint[] {}, new byte[] {}, true }, // multiple bytes new object[] { true, new uint[] { 0x50, 0x3E8, 0xAFC8, 0x249F0 }, new byte[] { 0x50, 0xCF, 0xA8, 0xEA, 0xBF, 0x88, 0xF0, 0xA4, 0xA7, 0xB0 }, true }, new object[] { false, new uint[] { 0x50, 0x3E8, 0xAFC8, 0x249F0 }, new byte[] { 0x50, 0x00, 0xE8, 0x03, 0xC8, 0xAF, 0x52, 0xD8, 0xF0, 0xDD }, true }, }; [Theory, MemberData("TryDecodeToUnicodeMultipleCodePointsTestData")] public void TryDecodeToUnicodeMultipleCodePoints(bool useUtf8Encoder, uint[] expectedCodePointsArray, byte[] inputBytesArray, bool expectedReturnVal) { TextEncoder encoder = useUtf8Encoder ? TextEncoder.Utf8 : TextEncoder.Utf16; Span<uint> expectedCodePoints = new Span<uint>(expectedCodePointsArray); Span<byte> inputBytes = new Span<byte>(inputBytesArray); Span<uint> codePoints = new Span<uint>(new uint[expectedCodePoints.Length]); int bytesWritten; int consumed; Assert.Equal(expectedReturnVal, encoder.TryDecode(inputBytes, codePoints, out consumed, out bytesWritten)); if (expectedReturnVal) { Assert.Equal(inputBytes.Length, consumed); Assert.True(AreCodePointArraysEqual(expectedCodePoints.ToArray(), codePoints.ToArray())); } } [Theory] [InlineData(true)] [InlineData(false)] public void BruteTestingRoundtripEncodeDecodeAllUnicodeCodePoints(bool useUtf8Encoder) { TextEncoder encoder = useUtf8Encoder ? TextEncoder.Utf8 : TextEncoder.Utf16; const uint maximumValidCodePoint = 0x10FFFF; uint[] expectedCodePoints = new uint[maximumValidCodePoint + 1]; for (uint i = 0; i <= maximumValidCodePoint; i++) { if (i >= 0xD800 && i <= 0xDFFF) { expectedCodePoints[i] = 0; // skip surrogate characters } else { expectedCodePoints[i] = i; } } ReadOnlySpan<uint> expectedCodePointsSpan = new ReadOnlySpan<uint>(expectedCodePoints); uint maxBytes = 4 * (maximumValidCodePoint + 1); Span<byte> buffer = new Span<byte>(new byte[maxBytes]); int bytesEncoded; int consumed; Assert.True(encoder.TryEncode(expectedCodePointsSpan, buffer, out consumed, out bytesEncoded)); buffer = buffer.Slice(0, bytesEncoded); Span<uint> codePoints = new Span<uint>(new uint[maximumValidCodePoint + 1]); int written; Assert.True(encoder.TryDecode(buffer, codePoints, out consumed, out written)); Assert.Equal(bytesEncoded, consumed); Assert.Equal(maximumValidCodePoint + 1, (uint)written); for (int i = 0; i <= maximumValidCodePoint; i++) { Assert.Equal(expectedCodePointsSpan[i], codePoints[i]); } } [Theory] [InlineData(true)] [InlineData(false)] public void EncodeAllUnicodeCodePoints(bool useUtf8Encoder) { TextEncoder encoder = useUtf8Encoder ? TextEncoder.Utf8 : TextEncoder.Utf16; Text.Encoding systemEncoder = useUtf8Encoder ? Text.Encoding.UTF8 : Text.Encoding.Unicode; const uint maximumValidCodePoint = 0x10FFFF; uint[] codePoints = new uint[maximumValidCodePoint + 1]; var plainText = new StringBuilder(); for (int i = 0; i <= maximumValidCodePoint; i++) { if (i >= 0xD800 && i <= 0xDFFF) { codePoints[i] = 0; // skip surrogate characters plainText.Append((char)0); // skip surrogate characters } else { codePoints[i] = (uint)i; if (i > 0xFFFF) { plainText.Append(char.ConvertFromUtf32(i)); } else { plainText.Append((char)i); } } } ReadOnlySpan<uint> codePointsSpan = new ReadOnlySpan<uint>(codePoints); uint maxBytes = 4 * (maximumValidCodePoint + 1); Span<byte> buffer = new Span<byte>(new byte[maxBytes]); int bytesWritten; int consumed; Assert.True(encoder.TryEncode(codePointsSpan, buffer, out consumed, out bytesWritten)); string unicodeString = plainText.ToString(); ReadOnlySpan<char> characters = unicodeString.AsSpan(); int byteCount = systemEncoder.GetByteCount(unicodeString); byte[] buff = new byte[byteCount]; Span<byte> expectedBuffer; char[] charArray = characters.ToArray(); systemEncoder.GetBytes(charArray, 0, characters.Length, buff, 0); expectedBuffer = new Span<byte>(buff); int minLength = Math.Min(expectedBuffer.Length, buffer.Length); for (int i = 0; i < minLength; i++) { Assert.Equal(expectedBuffer[i], buffer[i]); } } public bool AreByteArraysEqual(byte[] arrayOne, byte[] arrayTwo) { if (arrayOne.Length != arrayTwo.Length) return false; for (int i = 0; i < arrayOne.Length; i++) { if (arrayOne[i] != arrayTwo[i]) return false; } return true; } public bool AreCodePointArraysEqual(uint[] arrayOne, uint[] arrayTwo) { if (arrayOne.Length != arrayTwo.Length) return false; for (int i = 0; i < arrayOne.Length; i++) { if (!arrayOne[i].Equals(arrayTwo[i])) return false; } return true; } public static object[] PartialEncodeDecodeUtf8ToUtf16TestCases = new object[] { //new object[] //{ // /* output buffer size */, /* consumed on first pass */, // new byte[] { /* UTF-8 encoded input data */ }, // new byte[] { /* expected output first pass */ }, // new byte[] { /* expected output second pass */ }, //}, new object[] { 4, 2, new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F }, new byte[] { 0x48, 0x00, 0x65, 0x00 }, new byte[] { 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00 }, }, new object[] { 5, 6, new byte[] { 0xE6, 0xA8, 0x99, 0xE6, 0xBA, 0x96, 0xE8, 0x90, 0xAC, 0xE5, 0x9C, 0x8B, 0xE7, 0xA2, 0xBC }, new byte[] { 0x19, 0x6A, 0x96, 0x6E }, new byte[] { 0x2C, 0x84, 0x0B, 0x57, 0xBC, 0x78 }, }, }; [Theory, MemberData("PartialEncodeDecodeUtf8ToUtf16TestCases")] public void TryPartialUtf8ToUtf16EncodingTest(int outputSize, int expectedConsumed, byte[] inputBytes, byte[] expected1, byte[] expected2) { int written; int consumed; var input = new Span<byte>(inputBytes); var output = new Span<byte>(new byte[outputSize]); Assert.False(TextEncoder.Utf16.TryEncode(input, output, out consumed, out written)); Assert.Equal(expected1.Length, written); Assert.Equal(expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected1, output.Slice(0, written).ToArray())); input = input.Slice(consumed); output = new Span<byte>(new byte[expected2.Length]); Assert.True(TextEncoder.Utf16.TryEncode(input, output, out consumed, out written)); Assert.Equal(expected2.Length, written); Assert.Equal(inputBytes.Length - expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected2, output.ToArray())); } [Theory, MemberData("PartialEncodeDecodeUtf8ToUtf16TestCases")] public void TryPartialUtf8ToUtf16DecodingTest(int outputSize, int expectedConsumed, byte[] inputBytes, byte[] expected1, byte[] expected2) { int written; int consumed; var input = new Span<byte>(inputBytes); var output = new Span<byte>(new byte[outputSize]); Assert.False(TextEncoder.Utf8.TryDecode(input, output.NonPortableCast<byte, char>(), out consumed, out written)); Assert.Equal(expected1.Length, written * sizeof(char)); Assert.Equal(expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected1, output.Slice(0, written * sizeof(char)).ToArray())); input = input.Slice(consumed); output = new Span<byte>(new byte[expected2.Length]); Assert.True(TextEncoder.Utf8.TryDecode(input, output.NonPortableCast<byte, char>(), out consumed, out written)); Assert.Equal(expected2.Length, written * sizeof(char)); Assert.Equal(inputBytes.Length - expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected2, output.ToArray())); } public static object[] PartialEncodeDecodeUtf16ToUtf8TestCases = new object[] { //new object[] //{ // /* output buffer size */, /* consumed on first pass */, // new char[] { /* UTF-16 encoded input data */ }, // new byte[] { /* expected output first pass */ }, // new byte[] { /* expected output second pass */ }, //}, new object[] { 2, 2, new char[] { '\u0048', '\u0065', '\u006C', '\u006C', '\u006F' }, new byte[] { 0x48, 0x65 }, new byte[] { 0x6C, 0x6C, 0x6F }, }, new object[] { 7, 2, new char[] { '\u6A19', '\u6E96', '\u842C', '\u570B', '\u78BC' }, new byte[] { 0xE6, 0xA8, 0x99, 0xE6, 0xBA, 0x96 }, new byte[] { 0xE8, 0x90, 0xAC, 0xE5, 0x9C, 0x8B, 0xE7, 0xA2, 0xBC }, }, }; [Theory, MemberData("PartialEncodeDecodeUtf16ToUtf8TestCases")] public void TryPartialUtf16ToUtf8EncodingTest(int outputSize, int expectedConsumed, char[] inputBytes, byte[] expected1, byte[] expected2) { int written; int consumed; var input = new Span<char>(inputBytes); var output = new Span<byte>(new byte[outputSize]); Assert.False(TextEncoder.Utf8.TryEncode(input, output, out consumed, out written)); Assert.Equal(expected1.Length, written); Assert.Equal(expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected1, output.Slice(0, written).ToArray())); input = input.Slice(consumed); output = new Span<byte>(new byte[expected2.Length]); Assert.True(TextEncoder.Utf8.TryEncode(input, output, out consumed, out written)); Assert.Equal(expected2.Length, written); Assert.Equal(inputBytes.Length - expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected2, output.ToArray())); } [Theory, MemberData("PartialEncodeDecodeUtf16ToUtf8TestCases")] public void TryPartialUtf16ToUtf8DecodingTest(int outputSize, int expectedConsumed, char[] inputBytes, byte[] expected1, byte[] expected2) { int written; int consumed; var input = new Span<char>(inputBytes).AsBytes(); var output = new Span<byte>(new byte[outputSize]); Assert.False(TextEncoder.Utf16.TryDecode(input, output, out consumed, out written)); Assert.Equal(expected1.Length, written); Assert.Equal(expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected1, output.Slice(0, written).ToArray())); input = input.Slice(consumed * sizeof(char)); output = new Span<byte>(new byte[expected2.Length]); Assert.True(TextEncoder.Utf16.TryDecode(input, output, out consumed, out written)); Assert.Equal(expected2.Length, written); Assert.Equal(inputBytes.Length - expectedConsumed, consumed); Assert.True(AreByteArraysEqual(expected2, output.ToArray())); } } }
#region File Description //----------------------------------------------------------------------------- // PrimitiveBatch.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace PathDrawing { // PrimitiveBatch is a class that handles efficient rendering automatically for its // users, in a similar way to SpriteBatch. PrimitiveBatch can render lines, points, // and triangles to the screen. public class PrimitiveBatch : IDisposable { // this constant controls how large the vertices buffer is. Larger buffers will // require flushing less often, which can increase performance. However, having // buffer that is unnecessarily large will waste memory. const int DefaultBufferSize = 500; // a block of vertices that calling AddVertex will fill. Flush will draw using // this array, and will determine how many primitives to draw from // positionInBuffer. VertexPositionColor[] vertices = new VertexPositionColor[DefaultBufferSize]; // keeps track of how many vertices have been added. this value increases until // we run out of space in the buffer, at which time Flush is automatically // called. int positionInBuffer = 0; // the vertex declaration that will be set on the device for drawing. this is // created automatically using VertexPositionColor's vertex elements. VertexDeclaration vertexDeclaration; // a basic effect, which contains the shaders that we will use to draw our // primitives. BasicEffect basicEffect; // the device that we will issue draw calls to. GraphicsDevice device; // this value is set by Begin, and is the type of primitives that we are // drawing. PrimitiveType primitiveType; // how many verts does each of these primitives take up? points are 1, // lines are 2, and triangles are 3. int numVertsPerPrimitive; // hasBegun is flipped to true once Begin is called, and is used to make // sure users don't call End before Begin is called. bool hasBegun = false; bool isDisposed = false; // the constructor creates a new PrimitiveBatch and sets up all of the internals // that PrimitiveBatch will need. public PrimitiveBatch(GraphicsDevice graphicsDevice) { if (graphicsDevice == null) { throw new ArgumentNullException("graphicsDevice"); } device = graphicsDevice; vertexDeclaration = VertexPositionColor.VertexDeclaration; // set up a new basic effect, and enable vertex colors. basicEffect = new BasicEffect(graphicsDevice); basicEffect.VertexColorEnabled = true; // projection uses CreateOrthographicOffCenter to create 2d projection // matrix with 0,0 in the upper left. basicEffect.Projection = Matrix.CreateOrthographicOffCenter (0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && !isDisposed) { if (vertexDeclaration != null) vertexDeclaration.Dispose(); if (basicEffect != null) basicEffect.Dispose(); isDisposed = true; } } // Begin is called to tell the PrimitiveBatch what kind of primitives will be // drawn, and to prepare the graphics card to render those primitives. public void Begin(PrimitiveType primitiveType) { if (hasBegun) { throw new InvalidOperationException ("End must be called before Begin can be called again."); } // these three types reuse vertices, so we can't flush properly without more // complex logic. Since that's a bit too complicated for this sample, we'll // simply disallow them. if (primitiveType == PrimitiveType.LineStrip || primitiveType == PrimitiveType.TriangleStrip) { throw new NotSupportedException ("The specified primitiveType is not supported by PrimitiveBatch."); } this.primitiveType = primitiveType; // how many verts will each of these primitives require? this.numVertsPerPrimitive = NumVertsPerPrimitive(primitiveType); // prepare the graphics device for drawing by setting the vertex declaration // and telling our basic effect to begin. basicEffect.CurrentTechnique.Passes[0].Apply(); // flip the error checking boolean. It's now ok to call AddVertex, Flush, // and End. hasBegun = true; } // AddVertex is called to add another vertex to be rendered. To draw a point, // AddVertex must be called once. for lines, twice, and for triangles 3 times. // this function can only be called once begin has been called. // if there is not enough room in the vertices buffer, Flush is called // automatically. public void AddVertex(Vector2 vertex, Color color) { if (!hasBegun) { throw new InvalidOperationException ("Begin must be called before AddVertex can be called."); } // are we starting a new primitive? if so, and there will not be enough room // for a whole primitive, flush. bool newPrimitive = ((positionInBuffer % numVertsPerPrimitive) == 0); if (newPrimitive && (positionInBuffer + numVertsPerPrimitive) >= vertices.Length) { Flush(); } // once we know there's enough room, set the vertex in the buffer, // and increase position. vertices[positionInBuffer].Position = new Vector3(vertex, 0); vertices[positionInBuffer].Color = color; positionInBuffer++; } // End is called once all the primitives have been drawn using AddVertex. // it will call Flush to actually submit the draw call to the graphics card, and // then tell the basic effect to end. public void End() { if (!hasBegun) { throw new InvalidOperationException ("Begin must be called before End can be called."); } // Draw whatever the user wanted us to draw Flush(); hasBegun = false; } // Flush is called to issue the draw call to the graphics card. Once the draw // call is made, positionInBuffer is reset, so that AddVertex can start over // at the beginning. End will call this to draw the primitives that the user // requested, and AddVertex will call this if there is not enough room in the // buffer. private void Flush() { if (!hasBegun) { throw new InvalidOperationException ("Begin must be called before Flush can be called."); } // how many primitives will we draw? int primitiveCount = positionInBuffer / numVertsPerPrimitive; // no work to do if (primitiveCount == 0) { return; } // submit the draw call to the graphics card device.DrawUserPrimitives<VertexPositionColor>(primitiveType, vertices, 0, primitiveCount); // now that we've drawn, it's ok to reset positionInBuffer back to zero, // and write over any vertices that may have been set previously. positionInBuffer = 0; } #region Helper functions // NumVertsPerPrimitive is a boring helper function that tells how many vertices // it will take to draw each kind of primitive. static private int NumVertsPerPrimitive(PrimitiveType primitive) { int numVertsPerPrimitive; switch (primitive) { case PrimitiveType.LineList: numVertsPerPrimitive = 2; break; case PrimitiveType.TriangleList: numVertsPerPrimitive = 3; break; default: throw new InvalidOperationException("primitive is not valid"); } return numVertsPerPrimitive; } #endregion } }
namespace android.view.inputmethod { [global::MonoJavaBridge.JavaClass()] public sealed partial class InputMethodManager : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal InputMethodManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public bool isActive(android.view.View arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "isActive", "(Landroid/view/View;)Z", ref global::android.view.inputmethod.InputMethodManager._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public bool isActive() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "isActive", "()Z", ref global::android.view.inputmethod.InputMethodManager._m1); } private static global::MonoJavaBridge.MethodId _m2; public void restartInput(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "restartInput", "(Landroid/view/View;)V", ref global::android.view.inputmethod.InputMethodManager._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public bool showSoftInput(android.view.View arg0, int arg1, android.os.ResultReceiver arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "showSoftInput", "(Landroid/view/View;ILandroid/os/ResultReceiver;)Z", ref global::android.view.inputmethod.InputMethodManager._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m4; public bool showSoftInput(android.view.View arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "showSoftInput", "(Landroid/view/View;I)Z", ref global::android.view.inputmethod.InputMethodManager._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m5; public void updateSelection(android.view.View arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "updateSelection", "(Landroid/view/View;IIII)V", ref global::android.view.inputmethod.InputMethodManager._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m6; public void updateCursor(android.view.View arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "updateCursor", "(Landroid/view/View;IIII)V", ref global::android.view.inputmethod.InputMethodManager._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m7; public void displayCompletions(android.view.View arg0, android.view.inputmethod.CompletionInfo[] arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "displayCompletions", "(Landroid/view/View;[Landroid/view/inputmethod/CompletionInfo;)V", ref global::android.view.inputmethod.InputMethodManager._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m8; public void updateExtractedText(android.view.View arg0, int arg1, android.view.inputmethod.ExtractedText arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "updateExtractedText", "(Landroid/view/View;ILandroid/view/inputmethod/ExtractedText;)V", ref global::android.view.inputmethod.InputMethodManager._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m9; public void toggleSoftInput(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "toggleSoftInput", "(II)V", ref global::android.view.inputmethod.InputMethodManager._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m10; public bool isFullscreenMode() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "isFullscreenMode", "()Z", ref global::android.view.inputmethod.InputMethodManager._m10); } private static global::MonoJavaBridge.MethodId _m11; public void showStatusIcon(android.os.IBinder arg0, java.lang.String arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "showStatusIcon", "(Landroid/os/IBinder;Ljava/lang/String;I)V", ref global::android.view.inputmethod.InputMethodManager._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m12; public void hideStatusIcon(android.os.IBinder arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "hideStatusIcon", "(Landroid/os/IBinder;)V", ref global::android.view.inputmethod.InputMethodManager._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.util.List InputMethodList { get { return getInputMethodList(); } } private static global::MonoJavaBridge.MethodId _m13; public global::java.util.List getInputMethodList() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.view.inputmethod.InputMethodManager.staticClass, "getInputMethodList", "()Ljava/util/List;", ref global::android.view.inputmethod.InputMethodManager._m13) as java.util.List; } public new global::java.util.List EnabledInputMethodList { get { return getEnabledInputMethodList(); } } private static global::MonoJavaBridge.MethodId _m14; public global::java.util.List getEnabledInputMethodList() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.view.inputmethod.InputMethodManager.staticClass, "getEnabledInputMethodList", "()Ljava/util/List;", ref global::android.view.inputmethod.InputMethodManager._m14) as java.util.List; } private static global::MonoJavaBridge.MethodId _m15; public bool isAcceptingText() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "isAcceptingText", "()Z", ref global::android.view.inputmethod.InputMethodManager._m15); } private static global::MonoJavaBridge.MethodId _m16; public bool hideSoftInputFromWindow(android.os.IBinder arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z", ref global::android.view.inputmethod.InputMethodManager._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; public bool hideSoftInputFromWindow(android.os.IBinder arg0, int arg1, android.os.ResultReceiver arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "hideSoftInputFromWindow", "(Landroid/os/IBinder;ILandroid/os/ResultReceiver;)Z", ref global::android.view.inputmethod.InputMethodManager._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m18; public void toggleSoftInputFromWindow(android.os.IBinder arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "toggleSoftInputFromWindow", "(Landroid/os/IBinder;II)V", ref global::android.view.inputmethod.InputMethodManager._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m19; public bool isWatchingCursor(android.view.View arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "isWatchingCursor", "(Landroid/view/View;)Z", ref global::android.view.inputmethod.InputMethodManager._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public void sendAppPrivateCommand(android.view.View arg0, java.lang.String arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "sendAppPrivateCommand", "(Landroid/view/View;Ljava/lang/String;Landroid/os/Bundle;)V", ref global::android.view.inputmethod.InputMethodManager._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m21; public void setInputMethod(android.os.IBinder arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "setInputMethod", "(Landroid/os/IBinder;Ljava/lang/String;)V", ref global::android.view.inputmethod.InputMethodManager._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m22; public void hideSoftInputFromInputMethod(android.os.IBinder arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "hideSoftInputFromInputMethod", "(Landroid/os/IBinder;I)V", ref global::android.view.inputmethod.InputMethodManager._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m23; public void showSoftInputFromInputMethod(android.os.IBinder arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "showSoftInputFromInputMethod", "(Landroid/os/IBinder;I)V", ref global::android.view.inputmethod.InputMethodManager._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m24; public void showInputMethodPicker() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.inputmethod.InputMethodManager.staticClass, "showInputMethodPicker", "()V", ref global::android.view.inputmethod.InputMethodManager._m24); } public static int SHOW_IMPLICIT { get { return 1; } } public static int SHOW_FORCED { get { return 2; } } public static int RESULT_UNCHANGED_SHOWN { get { return 0; } } public static int RESULT_UNCHANGED_HIDDEN { get { return 1; } } public static int RESULT_SHOWN { get { return 2; } } public static int RESULT_HIDDEN { get { return 3; } } public static int HIDE_IMPLICIT_ONLY { get { return 1; } } public static int HIDE_NOT_ALWAYS { get { return 2; } } static InputMethodManager() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.inputmethod.InputMethodManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/inputmethod/InputMethodManager")); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { internal enum JsonContractType { None, Object, Array, Primitive, String, Dictionary, #if !(NET35 || NET20 || PORTABLE40) Dynamic, #endif #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40) Serializable, #endif Linq } /// <summary> /// Handles <see cref="JsonSerializer"/> serialization callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> public delegate void SerializationCallback(object o, StreamingContext context); /// <summary> /// Handles <see cref="JsonSerializer"/> serialization error callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> /// <param name="errorContext">The error context.</param> public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext); /// <summary> /// Sets extension data for an object during deserialization. /// </summary> /// <param name="o">The object to set extension data on.</param> /// <param name="key">The extension data key.</param> /// <param name="value">The extension data value.</param> public delegate void ExtensionDataSetter(object o, string key, JToken value); /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public abstract class JsonContract { internal bool IsNullable; internal bool IsConvertable; internal bool IsSealed; internal bool IsEnum; internal Type NonNullableUnderlyingType; internal ReadType InternalReadType; internal JsonContractType ContractType; internal bool IsReadOnlyOrFixedSize; internal bool IsInstantiable; private List<SerializationCallback> _onDeserializedCallbacks; private IList<SerializationCallback> _onDeserializingCallbacks; private IList<SerializationCallback> _onSerializedCallbacks; private IList<SerializationCallback> _onSerializingCallbacks; private IList<SerializationErrorCallback> _onErrorCallbacks; /// <summary> /// Gets the underlying type for the contract. /// </summary> /// <value>The underlying type for the contract.</value> public Type UnderlyingType { get; private set; } /// <summary> /// Gets or sets the type created during deserialization. /// </summary> /// <value>The type created during deserialization.</value> public Type CreatedType { get; set; } /// <summary> /// Gets or sets whether this type contract is serialized as a reference. /// </summary> /// <value>Whether this type contract is serialized as a reference.</value> public bool? IsReference { get; set; } /// <summary> /// Gets or sets the default <see cref="JsonConverter" /> for this contract. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } // internally specified JsonConverter's to override default behavour // checked for after passed in converters and attribute specified converters internal JsonConverter InternalConverter { get; set; } /// <summary> /// Gets or sets all methods called immediately after deserialization of the object. /// </summary> /// <value>The methods called immediately after deserialization of the object.</value> public IList<SerializationCallback> OnDeserializedCallbacks { get { if (_onDeserializedCallbacks == null) _onDeserializedCallbacks = new List<SerializationCallback>(); return _onDeserializedCallbacks; } } /// <summary> /// Gets or sets all methods called during deserialization of the object. /// </summary> /// <value>The methods called during deserialization of the object.</value> public IList<SerializationCallback> OnDeserializingCallbacks { get { if (_onDeserializingCallbacks == null) _onDeserializingCallbacks = new List<SerializationCallback>(); return _onDeserializingCallbacks; } } /// <summary> /// Gets or sets all methods called after serialization of the object graph. /// </summary> /// <value>The methods called after serialization of the object graph.</value> public IList<SerializationCallback> OnSerializedCallbacks { get { if (_onSerializedCallbacks == null) _onSerializedCallbacks = new List<SerializationCallback>(); return _onSerializedCallbacks; } } /// <summary> /// Gets or sets all methods called before serialization of the object. /// </summary> /// <value>The methods called before serialization of the object.</value> public IList<SerializationCallback> OnSerializingCallbacks { get { if (_onSerializingCallbacks == null) _onSerializingCallbacks = new List<SerializationCallback>(); return _onSerializingCallbacks; } } /// <summary> /// Gets or sets all method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The methods called when an error is thrown during the serialization of the object.</value> public IList<SerializationErrorCallback> OnErrorCallbacks { get { if (_onErrorCallbacks == null) _onErrorCallbacks = new List<SerializationErrorCallback>(); return _onErrorCallbacks; } } /// <summary> /// Gets or sets the method called immediately after deserialization of the object. /// </summary> /// <value>The method called immediately after deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")] public MethodInfo OnDeserialized { get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; } set { OnDeserializedCallbacks.Clear(); OnDeserializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called during deserialization of the object. /// </summary> /// <value>The method called during deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")] public MethodInfo OnDeserializing { get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; } set { OnDeserializingCallbacks.Clear(); OnDeserializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called after serialization of the object graph. /// </summary> /// <value>The method called after serialization of the object graph.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")] public MethodInfo OnSerialized { get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; } set { OnSerializedCallbacks.Clear(); OnSerializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called before serialization of the object. /// </summary> /// <value>The method called before serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")] public MethodInfo OnSerializing { get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; } set { OnSerializingCallbacks.Clear(); OnSerializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The method called when an error is thrown during the serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")] public MethodInfo OnError { get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; } set { OnErrorCallbacks.Clear(); OnErrorCallbacks.Add(CreateSerializationErrorCallback(value)); } } /// <summary> /// Gets or sets the default creator method used to create the object. /// </summary> /// <value>The default creator method used to create the object.</value> public Func<object> DefaultCreator { get; set; } /// <summary> /// Gets or sets a value indicating whether the default creator is non public. /// </summary> /// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value> public bool DefaultCreatorNonPublic { get; set; } internal JsonContract(Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType"); UnderlyingType = underlyingType; IsSealed = underlyingType.IsSealed(); IsInstantiable = !(underlyingType.IsInterface() || underlyingType.IsAbstract()); IsNullable = ReflectionUtils.IsNullable(underlyingType); NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); if (NonNullableUnderlyingType == typeof(byte[])) { InternalReadType = ReadType.ReadAsBytes; } else if (NonNullableUnderlyingType == typeof(int)) { InternalReadType = ReadType.ReadAsInt32; } else if (NonNullableUnderlyingType == typeof(decimal)) { InternalReadType = ReadType.ReadAsDecimal; } else if (NonNullableUnderlyingType == typeof(string)) { InternalReadType = ReadType.ReadAsString; } else if (NonNullableUnderlyingType == typeof(DateTime)) { InternalReadType = ReadType.ReadAsDateTime; } #if !NET20 else if (NonNullableUnderlyingType == typeof(DateTimeOffset)) { InternalReadType = ReadType.ReadAsDateTimeOffset; } #endif else { InternalReadType = ReadType.Read; } } internal void InvokeOnSerializing(object o, StreamingContext context) { if (_onSerializingCallbacks != null) { foreach (SerializationCallback callback in _onSerializingCallbacks) { callback(o, context); } } } internal void InvokeOnSerialized(object o, StreamingContext context) { if (_onSerializedCallbacks != null) { foreach (SerializationCallback callback in _onSerializedCallbacks) { callback(o, context); } } } internal void InvokeOnDeserializing(object o, StreamingContext context) { if (_onDeserializingCallbacks != null) { foreach (SerializationCallback callback in _onDeserializingCallbacks) { callback(o, context); } } } internal void InvokeOnDeserialized(object o, StreamingContext context) { if (_onDeserializedCallbacks != null) { foreach (SerializationCallback callback in _onDeserializedCallbacks) { callback(o, context); } } } internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext) { if (_onErrorCallbacks != null) { foreach (SerializationErrorCallback callback in _onErrorCallbacks) { callback(o, context, errorContext); } } } internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo) { return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context }); } internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo) { return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext }); } } }
// // WindowFrame.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // WindowFrame.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using System.ComponentModel; using Xwt.Drawing; using Xwt.Motion; namespace Xwt { [BackendType (typeof(IWindowFrameBackend))] public class WindowFrame: XwtComponent, IAnimatable { EventHandler boundsChanged; EventHandler shown; EventHandler hidden; CloseRequestedHandler closeRequested; EventHandler closed; Point location; Size size; bool pendingReallocation; Image icon; WindowFrame transientFor; public override object Tag { get { return Backend.Tag; } set { Backend.Tag = value; } } protected class WindowBackendHost: BackendHost<WindowFrame,IWindowFrameBackend>, IWindowFrameEventSink { protected override void OnBackendCreated () { Backend.Initialize (this); base.OnBackendCreated (); Parent.location = Backend.Bounds.Location; Parent.size = Backend.Bounds.Size; Backend.EnableEvent (WindowFrameEvent.BoundsChanged); } public void OnBoundsChanged (Rectangle bounds) { Parent.OnBoundsChanged (new BoundsChangedEventArgs () { Bounds = bounds }); } public virtual void OnShown () { Parent.OnShown (); } public virtual void OnHidden () { Parent.OnHidden (); } public virtual bool OnCloseRequested () { return Parent.OnCloseRequested (); } public virtual void OnClosed () { Parent.OnClosed (); } } static WindowFrame () { MapEvent (WindowFrameEvent.Shown, typeof(WindowFrame), "OnShown"); MapEvent (WindowFrameEvent.Hidden, typeof(WindowFrame), "OnHidden"); MapEvent (WindowFrameEvent.CloseRequested, typeof(WindowFrame), "OnCloseRequested"); MapEvent (WindowFrameEvent.Closed, typeof(WindowFrame), "OnClosed"); } public WindowFrame () { if (!(base.BackendHost is WindowBackendHost)) throw new InvalidOperationException ("CreateBackendHost for WindowFrame did not return a WindowBackendHost instance"); } public WindowFrame (string title): this () { Backend.Title = title; } protected override void Dispose (bool disposing) { base.Dispose (disposing); // Don't dispose the backend if this object is being finalized // The backend has to handle the finalizing on its own if (disposing && BackendHost.BackendCreated) Backend.Dispose (); } IWindowFrameBackend Backend { get { return (IWindowFrameBackend) BackendHost.Backend; } } protected override BackendHost CreateBackendHost () { return new WindowBackendHost (); } protected new WindowBackendHost BackendHost { get { return (WindowBackendHost) base.BackendHost; } } public Rectangle ScreenBounds { get { return BackendBounds; } set { if (value.Width < 0) value.Width = 0; if (value.Height < 0) value.Height = 0; BackendBounds = value; if (Visible) AdjustSize (); } } public double X { get { return BackendBounds.X; } set { SetBackendLocation (value, Y); } } public double Y { get { return BackendBounds.Y; } set { SetBackendLocation (X, value); } } public double Width { get { return BackendBounds.Width; } set { if (value < 0) value = 0; SetBackendSize (value, -1); if (Visible) AdjustSize (); } } public double Height { get { return BackendBounds.Height; } set { if (value < 0) value = 0; SetBackendSize (-1, value); if (Visible) AdjustSize (); } } /// <summary> /// Size of the window, not including the decorations /// </summary> /// <value>The size.</value> public Size Size { get { return BackendBounds.Size; } set { if (value.Width < 0) value.Width = 0; if (value.Height < 0) value.Height = 0; SetBackendSize (value.Width, value.Height); if (Visible) AdjustSize (); } } public Point Location { get { return BackendBounds.Location; } set { SetBackendLocation (value.X, value.Y); } } public string Title { get { return Backend.Title; } set { Backend.Title = value; } } public Image Icon { get { return icon; } set { icon = value; Backend.SetIcon (icon != null ? icon.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null); } } public bool Decorated { get { return Backend.Decorated; } set { Backend.Decorated = value; } } public bool ShowInTaskbar { get { return Backend.ShowInTaskbar; } set { Backend.ShowInTaskbar = value; } } public WindowFrame TransientFor { get { return transientFor; } set { transientFor = value; Backend.SetTransientFor ((IWindowFrameBackend)(value as IFrontend).Backend); } } public bool Resizable { get { return Backend.Resizable; } set { Backend.Resizable = value; } } public bool Visible { get { return Backend.Visible; } set { Backend.Visible = value; } } [DefaultValue (true)] public bool Sensitive { get { return Backend.Sensitive; } set { Backend.Sensitive = value; } } public double Opacity { get { return Backend.Opacity; } set { Backend.Opacity = value; } } /// <summary> /// Gets or sets a value indicating whether this window is in full screen mode /// </summary> /// <value><c>true</c> if the window is in full screen mode; otherwise, <c>false</c>.</value> public bool FullScreen { get { return Backend.FullScreen; } set { Backend.FullScreen = value; } } /// <summary> /// Gets the screen on which most of the area of this window is placed /// </summary> /// <value>The screen.</value> public Screen Screen { get { if (!Visible) throw new InvalidOperationException ("The window is not visible"); return Desktop.GetScreen (Backend.Screen); } } public void Show () { if (!Visible) { AdjustSize (); Visible = true; } } internal virtual void AdjustSize () { } /// <summary> /// Presents a window to the user. This may mean raising the window in the stacking order, /// deiconifying it, moving it to the current desktop, and/or giving it the keyboard focus /// </summary> public void Present () { Backend.Present (); } protected virtual void OnShown () { if(shown != null) shown (this, EventArgs.Empty); } public void Hide () { Visible = false; } protected virtual void OnHidden () { if (hidden != null) hidden (this, EventArgs.Empty); } /// <summary> /// Closes the window /// </summary> /// <remarks>> /// Closes the window like if the user clicked on the close window button. /// The CloseRequested event is fired and subscribers can cancel the closing, /// so there is no guarantee that the window will actually close. /// This method doesn't dispose the window. The Dispose method has to be called. /// </remarks> public bool Close () { return Backend.Close (); } /// <summary> /// Called to check if the window can be closed /// </summary> /// <returns><c>true</c> if the window can be closed, <c>false</c> otherwise</returns> protected virtual bool OnCloseRequested () { if (closeRequested == null) return true; var eventArgs = new CloseRequestedEventArgs(); closeRequested (this, eventArgs); return eventArgs.AllowClose; } /// <summary> /// Called when the window has been closed by the user, or by a call to Close /// </summary> /// <remarks> /// This method is not called when the window is disposed, only when explicitly closed (either by code or by the user) /// </remarks> protected virtual void OnClosed () { if (closed != null) closed (this, EventArgs.Empty); } internal virtual void SetBackendSize (double width, double height) { Backend.SetSize (width, height); } internal virtual void SetBackendLocation (double x, double y) { location = new Point (x, y); Backend.Move (x, y); } internal virtual Rectangle BackendBounds { get { BackendHost.EnsureBackendLoaded (); return new Rectangle (location, size); } set { size = value.Size; location = value.Location; Backend.Bounds = value; } } protected virtual void OnBoundsChanged (BoundsChangedEventArgs a) { var bounds = new Rectangle (location, size); if (bounds != a.Bounds) { size = a.Bounds.Size; location = a.Bounds.Location; Reallocate (); if (boundsChanged != null) boundsChanged (this, a); } } internal void Reallocate () { if (!pendingReallocation) { pendingReallocation = true; BackendHost.ToolkitEngine.QueueExitAction (delegate { pendingReallocation = false; OnReallocate (); }); } } protected virtual void OnReallocate () { } void IAnimatable.BatchBegin () { } void IAnimatable.BatchCommit () { } public event EventHandler BoundsChanged { add { boundsChanged += value; } remove { boundsChanged -= value; } } public event EventHandler Shown { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.Shown, shown); shown += value; } remove { shown -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.Shown, shown); } } public event EventHandler Hidden { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.Hidden, hidden); hidden += value; } remove { hidden -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.Hidden, hidden); } } public event CloseRequestedHandler CloseRequested { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.CloseRequested, closeRequested); closeRequested += value; } remove { closeRequested -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.CloseRequested, closeRequested); } } /// <summary> /// Raised when the window has been closed by the user, or by a call to Close /// </summary> /// <remarks> /// This event is not raised when the window is disposed, only when explicitly closed (either by code or by the user) /// </remarks> public event EventHandler Closed { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.Closed, closed); closed += value; } remove { closed -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.Closed, closed); } } } public class BoundsChangedEventArgs: EventArgs { public Rectangle Bounds { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Grid.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Slash.Collections.Grid { using System; using System.Collections; using System.Linq; using System.Text; public class Grid<T> : IEnumerable { #region Fields private T[,] grid; #endregion #region Constructors and Destructors public Grid(int width, int height) { this.grid = new T[width,height]; } public Grid(T[,] grid) { this.grid = grid; } public Grid(Grid<T> grid) { this.grid = new T[grid.Width,grid.Height]; for (int i = 0; i < grid.Width; i++) { for (int j = 0; j < grid.Height; j++) { this.grid[i, j] = grid[i, j]; } } } #endregion #region Public Properties public int Height { get { return this.grid.GetUpperBound(1) + 1; } } public int Width { get { return this.grid.GetUpperBound(0) + 1; } } #endregion #region Public Indexers public T this[int x, int y] { get { return this.GetObjectAt(x, y); } set { this.SetObjectAt(value, x, y); } } #endregion #region Public Methods and Operators public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return this.Equals((Grid<T>)obj); } public IEnumerator GetEnumerator() { return this.grid.GetEnumerator(); } public override int GetHashCode() { return (this.grid != null ? this.grid.GetHashCode() : 0); } public T GetObjectAt(int x, int y) { if (x < 0 || x >= this.grid.GetLength(0)) { throw new ArgumentOutOfRangeException( "x", x, string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(0) - 1, x)); } if (y < 0 || y >= this.grid.GetLength(1)) { throw new ArgumentOutOfRangeException( "y", y, string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(1) - 1, y)); } return this.grid[x, y]; } public void Resize(int newWidth, int newHeight) { T[,] newGrid = new T[newWidth,newHeight]; for (int x = 0; x < newWidth && x < this.Width; x++) { for (int y = 0; y < newHeight && y < this.Height; y++) { newGrid[x, y] = this.grid[x, y]; } } this.grid = newGrid; } public void SetObjectAt(T gridObject, int x, int y) { if (x < 0 || x >= this.grid.GetLength(0)) { throw new ArgumentOutOfRangeException( "x", x, string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(0) - 1, x)); } if (y < 0 || y >= this.grid.GetLength(1)) { throw new ArgumentOutOfRangeException( "y", y, string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(1) - 1, y)); } this.grid[x, y] = gridObject; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < this.grid.GetLength(0); i++) { stringBuilder.Append("[ "); for (int j = 0; j < this.grid.GetLength(1); j++) { stringBuilder.AppendFormat("{0}, ", this.grid[i, j]); } stringBuilder.Length = stringBuilder.Length - 2; stringBuilder.AppendLine("]"); } return stringBuilder.ToString(); } public bool TryGetObject(int x, int y, out T gridObject) { if (x < 0 || x >= this.grid.GetLength(0) || y < 0 || y >= this.grid.GetLength(1)) { gridObject = default(T); return false; } gridObject = this.grid[x, y]; return true; } #endregion #region Methods protected bool Equals(Grid<T> other) { bool equal = this.grid.Rank == other.grid.Rank && Enumerable.Range(0, this.grid.Rank) .All( dimension => this.grid.GetLength(dimension) == other.grid.GetLength(dimension)) && this.grid.Cast<T>().SequenceEqual(other.grid.Cast<T>()); return equal; } #endregion } }
namespace CWDev.SLNTools.UIKit { partial class CreateFilterForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.Label labelSourceSolution; System.Windows.Forms.Label labelSelectTheProjectsYouWishToKeep; this.m_groupboxOptions = new System.Windows.Forms.GroupBox(); this.m_checkboxWatchForChangesOnFilteredSolution = new System.Windows.Forms.CheckBox(); this.m_labelSelected = new System.Windows.Forms.Label(); this.m_textboxSourceSolution = new System.Windows.Forms.TextBox(); this.m_labelErrorMessage = new System.Windows.Forms.Label(); this.m_menuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.m_menuitemOpen = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.m_menuitemSave = new System.Windows.Forms.ToolStripMenuItem(); this.m_menuitemSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.m_menuitemExit = new System.Windows.Forms.ToolStripMenuItem(); this.m_treeview = new System.Windows.Forms.TreeView(); this.m_buttonSaveAndQuit = new System.Windows.Forms.Button(); this.m_checkboxCopyReSharperFiles = new System.Windows.Forms.CheckBox(); labelSourceSolution = new System.Windows.Forms.Label(); labelSelectTheProjectsYouWishToKeep = new System.Windows.Forms.Label(); this.m_groupboxOptions.SuspendLayout(); this.m_menuStrip.SuspendLayout(); this.SuspendLayout(); // // labelSourceSolution // labelSourceSolution.AutoSize = true; labelSourceSolution.Location = new System.Drawing.Point(12, 40); labelSourceSolution.Name = "labelSourceSolution"; labelSourceSolution.Size = new System.Drawing.Size(85, 13); labelSourceSolution.TabIndex = 0; labelSourceSolution.Text = "&Source Solution:"; // // labelSelectTheProjectsYouWishToKeep // labelSelectTheProjectsYouWishToKeep.AutoSize = true; labelSelectTheProjectsYouWishToKeep.Location = new System.Drawing.Point(12, 74); labelSelectTheProjectsYouWishToKeep.Name = "labelSelectTheProjectsYouWishToKeep"; labelSelectTheProjectsYouWishToKeep.Size = new System.Drawing.Size(181, 13); labelSelectTheProjectsYouWishToKeep.TabIndex = 2; labelSelectTheProjectsYouWishToKeep.Text = "Select the &projects you wish to keep:"; // // m_groupboxOptions // this.m_groupboxOptions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_groupboxOptions.Controls.Add(this.m_checkboxCopyReSharperFiles); this.m_groupboxOptions.Controls.Add(this.m_checkboxWatchForChangesOnFilteredSolution); this.m_groupboxOptions.Location = new System.Drawing.Point(8, 299); this.m_groupboxOptions.Name = "m_groupboxOptions"; this.m_groupboxOptions.Size = new System.Drawing.Size(663, 47); this.m_groupboxOptions.TabIndex = 5; this.m_groupboxOptions.TabStop = false; this.m_groupboxOptions.Text = "Options (when the filter file is opened)"; // // m_checkboxWatchForChangesOnFilteredSolution // this.m_checkboxWatchForChangesOnFilteredSolution.AutoSize = true; this.m_checkboxWatchForChangesOnFilteredSolution.Location = new System.Drawing.Point(6, 19); this.m_checkboxWatchForChangesOnFilteredSolution.Name = "m_checkboxWatchForChangesOnFilteredSolution"; this.m_checkboxWatchForChangesOnFilteredSolution.Size = new System.Drawing.Size(223, 17); this.m_checkboxWatchForChangesOnFilteredSolution.TabIndex = 0; this.m_checkboxWatchForChangesOnFilteredSolution.Text = "&Watch for changes on the filtered solution"; this.m_checkboxWatchForChangesOnFilteredSolution.UseVisualStyleBackColor = true; // // m_labelSelected // this.m_labelSelected.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_labelSelected.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.m_labelSelected.Location = new System.Drawing.Point(448, 74); this.m_labelSelected.Name = "m_labelSelected"; this.m_labelSelected.Size = new System.Drawing.Size(220, 13); this.m_labelSelected.TabIndex = 3; // // m_textboxSourceSolution // this.m_textboxSourceSolution.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_textboxSourceSolution.Location = new System.Drawing.Point(117, 37); this.m_textboxSourceSolution.Name = "m_textboxSourceSolution"; this.m_textboxSourceSolution.ReadOnly = true; this.m_textboxSourceSolution.Size = new System.Drawing.Size(551, 20); this.m_textboxSourceSolution.TabIndex = 1; // // m_labelErrorMessage // this.m_labelErrorMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_labelErrorMessage.ForeColor = System.Drawing.Color.Red; this.m_labelErrorMessage.Location = new System.Drawing.Point(9, 349); this.m_labelErrorMessage.Name = "m_labelErrorMessage"; this.m_labelErrorMessage.Size = new System.Drawing.Size(659, 13); this.m_labelErrorMessage.TabIndex = 6; // // m_menuStrip // this.m_menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem}); this.m_menuStrip.Location = new System.Drawing.Point(0, 0); this.m_menuStrip.Name = "m_menuStrip"; this.m_menuStrip.Size = new System.Drawing.Size(683, 24); this.m_menuStrip.TabIndex = 0; this.m_menuStrip.Text = "m_menuStrip"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.m_menuitemOpen, this.toolStripSeparator1, this.m_menuitemSave, this.m_menuitemSaveAs, this.toolStripSeparator2, this.m_menuitemExit}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "&File"; // // m_menuitemOpen // this.m_menuitemOpen.Name = "m_menuitemOpen"; this.m_menuitemOpen.Size = new System.Drawing.Size(123, 22); this.m_menuitemOpen.Text = "Open..."; this.m_menuitemOpen.Click += new System.EventHandler(this.m_menuitemOpen_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(120, 6); // // m_menuitemSave // this.m_menuitemSave.Name = "m_menuitemSave"; this.m_menuitemSave.Size = new System.Drawing.Size(123, 22); this.m_menuitemSave.Text = "Save"; this.m_menuitemSave.Click += new System.EventHandler(this.m_menuitemSave_Click); // // m_menuitemSaveAs // this.m_menuitemSaveAs.Name = "m_menuitemSaveAs"; this.m_menuitemSaveAs.Size = new System.Drawing.Size(123, 22); this.m_menuitemSaveAs.Text = "Save As..."; this.m_menuitemSaveAs.Click += new System.EventHandler(this.m_menuitemSaveAs_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(120, 6); // // m_menuitemExit // this.m_menuitemExit.Name = "m_menuitemExit"; this.m_menuitemExit.Size = new System.Drawing.Size(123, 22); this.m_menuitemExit.Text = "Exit"; this.m_menuitemExit.Click += new System.EventHandler(this.m_menuitemExit_Click); // // m_treeview // this.m_treeview.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_treeview.CheckBoxes = true; this.m_treeview.Location = new System.Drawing.Point(8, 90); this.m_treeview.Name = "m_treeview"; this.m_treeview.Size = new System.Drawing.Size(663, 203); this.m_treeview.TabIndex = 4; this.m_treeview.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.m_treeview_AfterCheck); // // m_buttonSaveAndQuit // this.m_buttonSaveAndQuit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_buttonSaveAndQuit.Location = new System.Drawing.Point(570, 373); this.m_buttonSaveAndQuit.Name = "m_buttonSaveAndQuit"; this.m_buttonSaveAndQuit.Size = new System.Drawing.Size(101, 23); this.m_buttonSaveAndQuit.TabIndex = 7; this.m_buttonSaveAndQuit.Text = "&Save && Quit"; this.m_buttonSaveAndQuit.UseVisualStyleBackColor = true; this.m_buttonSaveAndQuit.Click += new System.EventHandler(this.m_buttonSaveAndQuit_Click); // // m_checkboxCopyReSharperFiles // this.m_checkboxCopyReSharperFiles.AutoSize = true; this.m_checkboxCopyReSharperFiles.Location = new System.Drawing.Point(235, 19); this.m_checkboxCopyReSharperFiles.Name = "m_checkboxCopyReSharperFiles"; this.m_checkboxCopyReSharperFiles.Size = new System.Drawing.Size(125, 17); this.m_checkboxCopyReSharperFiles.TabIndex = 1; this.m_checkboxCopyReSharperFiles.Text = "Copy &ReSharper files"; this.m_checkboxCopyReSharperFiles.UseVisualStyleBackColor = true; // // CreateFilterForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(683, 402); this.Controls.Add(this.m_groupboxOptions); this.Controls.Add(this.m_buttonSaveAndQuit); this.Controls.Add(this.m_treeview); this.Controls.Add(this.m_labelSelected); this.Controls.Add(this.m_labelErrorMessage); this.Controls.Add(labelSelectTheProjectsYouWishToKeep); this.Controls.Add(labelSourceSolution); this.Controls.Add(this.m_textboxSourceSolution); this.Controls.Add(this.m_menuStrip); this.MainMenuStrip = this.m_menuStrip; this.MinimumSize = new System.Drawing.Size(480, 294); this.Name = "CreateFilterForm"; this.Text = "Create Filter"; this.m_groupboxOptions.ResumeLayout(false); this.m_groupboxOptions.PerformLayout(); this.m_menuStrip.ResumeLayout(false); this.m_menuStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox m_textboxSourceSolution; private System.Windows.Forms.Label m_labelErrorMessage; private System.Windows.Forms.Label m_labelSelected; private System.Windows.Forms.MenuStrip m_menuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem m_menuitemOpen; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem m_menuitemSave; private System.Windows.Forms.ToolStripMenuItem m_menuitemSaveAs; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem m_menuitemExit; private System.Windows.Forms.TreeView m_treeview; private System.Windows.Forms.Button m_buttonSaveAndQuit; private System.Windows.Forms.CheckBox m_checkboxWatchForChangesOnFilteredSolution; private System.Windows.Forms.GroupBox m_groupboxOptions; private System.Windows.Forms.CheckBox m_checkboxCopyReSharperFiles; } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Data.SqlClient; using System.Text.RegularExpressions; using Subtext.Extensibility; using Subtext.Extensibility.Interfaces; using Subtext.Framework.Components; using Subtext.Framework.Data; using Subtext.Framework.Exceptions; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Infrastructure; namespace Subtext.Framework.Infrastructure.Installation { /// <summary> /// Class used to help make determine whether an installation is required or not. /// </summary> public class InstallationManager : IInstallationManager { public InstallationManager(IInstaller installer, ICache cache) { Installer = installer; Cache = cache; } protected ICache Cache { get; set; } protected IInstaller Installer { get; set; } public void Install(Version assemblyVersion) { Installer.Install(assemblyVersion); ResetInstallationStatusCache(); } public void CreateWelcomeContent(ISubtextContext context, IEntryPublisher entryPublisher, Blog blog) { var repository = context.Repository; CreateWelcomeCategories(repository, blog); var adminUrlHelper = new AdminUrlHelper(context.UrlHelper); Entry article = CreateWelcomeArticle(blog, entryPublisher, adminUrlHelper); Entry entry = CreateWelcomeBlogPost(context, blog, entryPublisher, adminUrlHelper, article); CreateWelcomeComment(repository, adminUrlHelper, entry); } private static void CreateWelcomeComment(ObjectProvider repository, AdminUrlHelper adminUrlHelper, Entry entry) { string commentBody = ScriptHelper.UnpackEmbeddedScriptAsString("WelcomeComment.htm"); string feedbackUrl = adminUrlHelper.FeedbackList(); commentBody = string.Format(commentBody, feedbackUrl); var comment = new FeedbackItem(FeedbackType.Comment) { Title = "re: Welcome to Subtext!", Entry = entry, Author = "Subtext", DateCreated = DateTime.Now, DateModified = DateTime.Now, Approved = true, Body = commentBody }; repository.Create(comment); } private static Entry CreateWelcomeBlogPost(ISubtextContext context, Blog blog, IEntryPublisher entryPublisher, AdminUrlHelper adminUrlHelper, IEntryIdentity article) { string body = ScriptHelper.UnpackEmbeddedScriptAsString("WelcomePost.htm"); string articleUrl = context.UrlHelper.EntryUrl(article); body = String.Format(body, articleUrl, adminUrlHelper.Home(), context.UrlHelper.HostAdminUrl("default.aspx")); var entry = new Entry(PostType.BlogPost) { Title = "Welcome to Subtext!", EntryName = "welcome-to-subtext", BlogId = blog.Id, Author = blog.Author, Body = body, DateCreated = DateTime.Now, DateModified = DateTime.Now, DateSyndicated = DateTime.Now, IsActive = true, IncludeInMainSyndication = true, DisplayOnHomePage = true, AllowComments = true }; entryPublisher.Publish(entry); return entry; } private static Entry CreateWelcomeArticle(Blog blog, IEntryPublisher entryPublisher, AdminUrlHelper adminUrlHelper) { string body = ScriptHelper.UnpackEmbeddedScriptAsString("WelcomeArticle.htm"); body = String.Format(body, adminUrlHelper.ArticlesList()); var article = new Entry(PostType.Story) { EntryName = "welcome-to-subtext-article", Title = "Welcome to Subtext!", BlogId = blog.Id, Author = blog.Author, Body = body, DateCreated = DateTime.Now, DateModified = DateTime.Now, IsActive = true, }; entryPublisher.Publish(article); return article; } private static void CreateWelcomeCategories(ObjectProvider repository, Blog blog) { repository.CreateLinkCategory(new LinkCategory { Title = "Programming", Description = "Blog posts related to programming", BlogId = blog.Id, IsActive = true, CategoryType = CategoryType.PostCollection, }); repository.CreateLinkCategory(new LinkCategory { Title = "Personal", Description = "Personal musings, random thoughts.", BlogId = blog.Id, IsActive = true, CategoryType = CategoryType.PostCollection }); } public void Upgrade(Version currentAssemblyVersion) { Installer.Upgrade(currentAssemblyVersion); ResetInstallationStatusCache(); } /// <summary> /// Determines whether an installation action is required by /// examining the specified unhandled Exception. /// </summary> /// <param name="unhandledException">Unhandled exception.</param> /// <param name="assemblyVersion">The version of the currently installed assembly.</param> /// <returns> /// <c>true</c> if an installation action is required; otherwise, <c>false</c>. /// </returns> public bool InstallationActionRequired(Version assemblyVersion, Exception unhandledException) { if(unhandledException is HostDataDoesNotExistException) { return true; } if(IsInstallationException(unhandledException)) { return true; } InstallationState status = GetInstallationStatus(assemblyVersion); switch(status) { case InstallationState.NeedsInstallation: case InstallationState.NeedsUpgrade: { return true; } } return false; } private static bool IsInstallationException(Exception exception) { var tableRegex = new Regex("Invalid object name '.*?'", RegexOptions.IgnoreCase | RegexOptions.Compiled); bool isSqlException = exception is SqlException; if(isSqlException && tableRegex.IsMatch(exception.Message)) { return true; } var spRegex = new Regex("'Could not find stored procedure '.*?'", RegexOptions.IgnoreCase | RegexOptions.Compiled); if(isSqlException && spRegex.IsMatch(exception.Message)) { return true; } return false; } public virtual InstallationState GetInstallationStatus(Version currentAssemblyVersion) { object cachedInstallationState = Cache["NeedsInstallation"]; if(cachedInstallationState != null) { return (InstallationState)cachedInstallationState; } var status = GetInstallationState(currentAssemblyVersion); Cache.Insert("NeedsInstallation", status); return status; } private InstallationState GetInstallationState(Version currentAssemblyVersion) { Version installationVersion = Installer.GetCurrentInstallationVersion(); if(installationVersion == null) { return InstallationState.NeedsInstallation; } if(Installer.NeedsUpgrade(installationVersion, currentAssemblyVersion)) { return InstallationState.NeedsUpgrade; } return InstallationState.Complete; } public bool InstallationActionRequired(InstallationState currentState) { bool needsUpgrade = (currentState == InstallationState.NeedsInstallation || currentState == InstallationState.NeedsUpgrade); return needsUpgrade; } public void ResetInstallationStatusCache() { object cachedInstallationState = Cache["NeedsInstallation"]; if(cachedInstallationState != null) { Cache.Remove("NeedsInstallation"); } } /// <summary> /// Determines whether the specified exception is due to a permission /// denied error. /// </summary> /// <param name="exception"></param> /// <returns></returns> public bool IsPermissionDeniedException(Exception exception) { var sqlexc = exception.InnerException as SqlException; return sqlexc != null && ( sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedInDatabase || sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedOnProcedure || sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedInOnColumn || sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedInOnObject ); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace memory_game.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * Licensed to the 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 NVelocity.Runtime.Parser { using System; using System.IO; using System.Text; /// <summary> NOTE : This class was originally an ASCII_CharStream autogenerated /// by Javacc. It was then modified via changing class name with appropriate /// fixes for CTORS, and mods to readChar(). /// /// This is safe because we *always* use Reader with this class, and never a /// InputStream. This guarantees that we have a correct stream of 16-bit /// chars - all encoding transformations have been done elsewhere, so we /// believe that there is no risk in doing this. Time will tell :) /// </summary> /// <summary> An implementation of interface CharStream, where the stream is assumed to /// contain only ASCII characters (without unicode processing). /// </summary> public sealed class VelocityCharStream : ICharStream { /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getEndColumn()"> /// </seealso> public int EndColumn { get { return bufcolumn[bufpos]; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getEndLine()"> /// </seealso> public int EndLine { get { return bufline[bufpos]; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getBeginColumn()"> /// </seealso> public int BeginColumn { get { return bufcolumn[tokenBegin]; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getBeginLine()"> /// </seealso> public int BeginLine { get { return bufline[tokenBegin]; } } public const bool staticFlag = false; internal int bufsize; private int nextBufExpand; internal int available; internal int tokenBegin; public int bufpos = -1; private int[] bufline; private int[] bufcolumn; private int column = 0; private int line = 1; private bool prevCharIsCR = false; private bool prevCharIsLF = false; private TextReader inputStream; private char[] buffer; private int maxNextCharInd = 0; private int inBuf = 0; private void ExpandBuff(bool wrapAround) { char[] newbuffer = new char[bufsize + nextBufExpand]; int[] newbufline = new int[bufsize + nextBufExpand]; int[] newbufcolumn = new int[bufsize + nextBufExpand]; try { if (wrapAround) { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); Array.Copy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); Array.Copy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); Array.Copy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (System.Exception t) { throw new System.ApplicationException(t.Message); } bufsize += nextBufExpand; nextBufExpand = bufsize; available = bufsize; tokenBegin = 0; } private bool FillBuff() { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > nextBufExpand) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) { bufpos = maxNextCharInd = 0; } else { ExpandBuff(false); } } else if (available > tokenBegin) { available = bufsize; } else if ((tokenBegin - available) < nextBufExpand) { ExpandBuff(true); } else { available = tokenBegin; } } int i; try { if ((i = inputStream.Read(buffer, maxNextCharInd, available - maxNextCharInd)) <= 0) { inputStream.Close(); throw new System.IO.IOException(); } else { maxNextCharInd += i; } return true; } catch { --bufpos; Backup(0); if (tokenBegin == -1) { tokenBegin = bufpos; } return false; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.BeginToken()"> /// </seealso> public char BeginToken() { tokenBegin = -1; char c = ReadChar(); tokenBegin = bufpos; return c; } private void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else { line += (column = 1); } } switch (c) { case '\r': prevCharIsCR = true; break; case '\n': prevCharIsLF = true; break; case '\t': column--; column += (8 - (column & 7)); break; default: break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.readChar()"> /// </seealso> public char ReadChar() { if (inBuf > 0) { --inBuf; /* * was : return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); */ return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]; } if (++bufpos >= maxNextCharInd) { if (!FillBuff()) { throw new IOException(); } } /* * was : char c = (char)((char)0xff & buffer[bufpos]); */ char c = buffer[bufpos]; UpdateLineColumn(c); return (c); } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.backup(int)"> /// </seealso> public void Backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public VelocityCharStream(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = nextBufExpand = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public VelocityCharStream(TextReader dstream, int startline, int startcolumn) : this(dstream, startline, startcolumn, 4096) { } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public void ReInit(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.Length) { available = bufsize = nextBufExpand = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public void ReInit(TextReader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public VelocityCharStream(Stream dstream, int startline, int startcolumn, int buffersize) : this(new StreamReader(dstream, Encoding.Default), startline, startcolumn, buffersize) { } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public VelocityCharStream(Stream dstream, int startline, int startcolumn) : this(dstream, startline, startcolumn, 4096) { } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public void ReInit(Stream dstream, int startline, int startcolumn, int buffersize) { ReInit(new StreamReader(dstream, Encoding.Default), startline, startcolumn, buffersize); } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public void ReInit(Stream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.GetImage()"> /// </seealso> public string GetImage() { if (bufpos >= tokenBegin) { return new string(buffer, tokenBegin, bufpos - tokenBegin + 1); } else { return new string(buffer, tokenBegin, bufsize - tokenBegin) + new string(buffer, 0, bufpos + 1); } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.GetSuffix(int)"> /// </seealso> public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) { Array.Copy(buffer, bufpos - len + 1, ret, 0, len); } else { Array.Copy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); Array.Copy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.Done()"> /// </seealso> public void Done() { buffer = null; bufline = null; bufcolumn = null; } /// <summary> Method to adjust line and column numbers for the start of a token.<BR></summary> /// <param name="newLine"> /// </param> /// <param name="newCol"> /// </param> public void AdjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using OpenTK.Graphics.OpenGL; using nzy3D.Colors; using nzy3D.Events; using nzy3D.Maths; using nzy3D.Plot3D.Rendering.Scene; using nzy3D.Plot3D.Rendering.View; namespace nzy3D.Plot3D.Primitives { /// <summary> /// A Parallelepiped is a parallelepiped rectangle that is Drawable /// and Wireframeable. /// A future version of Rectangle3d should consider it as a Composite3d. /// /// This class has been implemented for debugging purpose and inconsistency /// of its input w.r.t other primitives should not be considered /// (no setData function). /// /// @author Martin Pernollet /// </summary> public class Parallelepiped : AbstractWireframeable, ISingleColorable, IMultiColorable { private ColorMapper _mapper; private List<Polygon> _quads; private Color _color; public Parallelepiped() : base() { _bbox = new BoundingBox3d(); _quads = new List<Polygon>(6); } public Parallelepiped(BoundingBox3d b) : base() { _bbox = new BoundingBox3d(); _quads = new List<Polygon>(); setData(b); } public override void Draw(Rendering.View.Camera cam) { foreach (Polygon quad in _quads) { quad.Draw(cam); } } /// <summary> /// Return the transform that was affected to this composite. /// </summary> public override Transform.Transform Transform { get { return _transform; } set { _transform = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.Transform = value; } } } } } public override Color WireframeColor { get { return base.WireframeColor; } set { base.WireframeColor = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.WireframeColor = value; } } } } } public override bool WireframeDisplayed { get { return base.WireframeDisplayed; } set { base.WireframeDisplayed = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.WireframeDisplayed = value; } } } } } public override float WireframeWidth { get { return base.WireframeWidth; } set { base.WireframeWidth = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.WireframeWidth = value; } } } } } public override bool FaceDisplayed { get { return base.FaceDisplayed; } set { base.FaceDisplayed = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.FaceDisplayed = value; } } } } } public void setData(BoundingBox3d box) { _bbox.reset(); _bbox.Add(box); _quads = new List<Polygon>(6); // Add 6 polygons to list for (int i = 0; i <= 5; i++) { _quads.Add(new Polygon()); } _quads[0].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymin, _bbox.zmax))); _quads[0].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymin, _bbox.zmin))); _quads[0].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymax, _bbox.zmin))); _quads[0].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymax, _bbox.zmax))); _quads[1].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymax, _bbox.zmax))); _quads[1].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymax, _bbox.zmin))); _quads[1].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymin, _bbox.zmin))); _quads[1].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymin, _bbox.zmax))); _quads[2].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymax, _bbox.zmax))); _quads[2].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymax, _bbox.zmin))); _quads[2].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymax, _bbox.zmin))); _quads[2].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymax, _bbox.zmax))); _quads[3].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymin, _bbox.zmax))); _quads[3].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymin, _bbox.zmin))); _quads[3].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymin, _bbox.zmin))); _quads[3].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymin, _bbox.zmax))); _quads[4].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymin, _bbox.zmax))); _quads[4].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymin, _bbox.zmax))); _quads[4].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymax, _bbox.zmax))); _quads[4].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymax, _bbox.zmax))); _quads[5].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymin, _bbox.zmin))); _quads[5].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymin, _bbox.zmin))); _quads[5].Add(new Point(new Coord3d(_bbox.xmin, _bbox.ymax, _bbox.zmin))); _quads[5].Add(new Point(new Coord3d(_bbox.xmax, _bbox.ymax, _bbox.zmin))); } public Colors.ColorMapper ColorMapper { get { return _mapper; } set { _mapper = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.ColorMapper = value; } } } } } public Colors.Color Color { get { return _color; } set { _color = value; lock (_quads) { foreach (Polygon s in _quads) { if ((s != null)) { s.Color = value; } } } } } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
// Copyright (c) <2015> <Playdead> // This file is subject to the MIT License as seen in the root of this folder structure (LICENSE.TXT) // AUTHOR: Lasse Jon Fuglsang Pedersen <lasse@playdead.com> using System; using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [RequireComponent(typeof(VelocityBuffer))] public class FrustumJitter : MonoBehaviour { #region Point distributions private static float[] points_Still = new float[] { 0.5f, 0.5f, }; private static float[] points_Uniform2 = new float[] { -0.25f, -0.25f,//ll 0.25f, 0.25f,//ur }; private static float[] points_Uniform4 = new float[] { -0.25f, -0.25f,//ll 0.25f, -0.25f,//lr 0.25f, 0.25f,//ur -0.25f, 0.25f,//ul }; private static float[] points_Uniform4_Helix = new float[] { -0.25f, -0.25f,//ll 3 1 0.25f, 0.25f,//ur \/| 0.25f, -0.25f,//lr /\| -0.25f, 0.25f,//ul 0 2 }; private static float[] points_Uniform4_DoubleHelix = new float[] { -0.25f, -0.25f,//ll 3 1 0.25f, 0.25f,//ur \/| 0.25f, -0.25f,//lr /\| -0.25f, 0.25f,//ul 0 2 -0.25f, -0.25f,//ll 6--7 0.25f, -0.25f,//lr \ -0.25f, 0.25f,//ul \ 0.25f, 0.25f,//ur 4--5 }; private static float[] points_SkewButterfly = new float[] { -0.250f, -0.250f, 0.250f, 0.250f, 0.125f, -0.125f, -0.125f, 0.125f, }; private static float[] points_Rotated4 = new float[] { -0.125f, -0.375f,//ll 0.375f, -0.125f,//lr 0.125f, 0.375f,//ur -0.375f, 0.125f,//ul }; private static float[] points_Rotated4_Helix = new float[] { -0.125f, -0.375f,//ll 3 1 0.125f, 0.375f,//ur \/| 0.375f, -0.125f,//lr /\| -0.375f, 0.125f,//ul 0 2 }; private static float[] points_Rotated4_Helix2 = new float[] { -0.125f, -0.375f,//ll 2--1 0.125f, 0.375f,//ur \/ -0.375f, 0.125f,//ul /\ 0.375f, -0.125f,//lr 0 3 }; private static float[] points_Poisson10 = new float[] { -0.16795960f*0.25f, 0.65544910f*0.25f, -0.69096030f*0.25f, 0.59015970f*0.25f, 0.49843820f*0.25f, 0.83099720f*0.25f, 0.17230150f*0.25f, -0.03882703f*0.25f, -0.60772670f*0.25f, -0.06013587f*0.25f, 0.65606390f*0.25f, 0.24007600f*0.25f, 0.80348370f*0.25f, -0.48096900f*0.25f, 0.33436540f*0.25f, -0.73007030f*0.25f, -0.47839520f*0.25f, -0.56005300f*0.25f, -0.12388120f*0.25f, -0.96633990f*0.25f, }; private static float[] points_Pentagram = new float[] { 0.000000f*0.5f, 0.525731f*0.5f,// head -0.309017f*0.5f, -0.425325f*0.5f,// lleg 0.500000f*0.5f, 0.162460f*0.5f,// rarm -0.500000f*0.5f, 0.162460f*0.5f,// larm 0.309017f*0.5f, -0.425325f*0.5f,// rleg }; private static float[] points_Halton_2_3_x8 = new float[8 * 2]; private static float[] points_Halton_2_3_x16 = new float[16 * 2]; private static float[] points_Halton_2_3_x32 = new float[32 * 2]; private static float[] points_Halton_2_3_x256 = new float[256 * 2]; private static float[] points_MotionPerp2 = new float[] { 0.00f, -0.25f, 0.00f, 0.25f, }; private static void TransformPattern(float[] seq, float theta, float scale) { float cs = Mathf.Cos(theta); float sn = Mathf.Sin(theta); for (int i = 0, j = 1, n = seq.Length; i != n; i += 2, j += 2) { float x = scale * seq[i]; float y = scale * seq[j]; seq[i] = x * cs - y * sn; seq[j] = x * sn + y * cs; } } // http://en.wikipedia.org/wiki/Halton_sequence private static float HaltonSeq(int prime, int index = 1/* NOT! zero-based */) { float r = 0f; float f = 1f; int i = index; while (i > 0) { f /= prime; r += f * (i % prime); i = (int)Mathf.Floor(i / (float)prime); } return r; } private static void InitializeHalton_2_3(float[] seq) { for (int i = 0, n = seq.Length / 2; i != n; i++) { float u = HaltonSeq(2, i + 1) - 0.5f; float v = HaltonSeq(3, i + 1) - 0.5f; seq[2 * i + 0] = u; seq[2 * i + 1] = v; } } static bool _initialized = false; static FrustumJitter() { if (_initialized == false) { _initialized = true; // points_Pentagram Vector2 vh = new Vector2(points_Pentagram[0] - points_Pentagram[2], points_Pentagram[1] - points_Pentagram[3]); Vector2 vu = new Vector2(0.0f, 1.0f); TransformPattern(points_Pentagram, Mathf.Deg2Rad * (0.5f * Vector2.Angle(vu, vh)), 1.0f); // points_Halton_2_3_xN InitializeHalton_2_3(points_Halton_2_3_x8); InitializeHalton_2_3(points_Halton_2_3_x16); InitializeHalton_2_3(points_Halton_2_3_x32); InitializeHalton_2_3(points_Halton_2_3_x256); } } public enum Pattern { Still, Uniform2, Uniform4, Uniform4_Helix, Uniform4_DoubleHelix, SkewButterfly, Rotated4, Rotated4_Helix, Rotated4_Helix2, Poisson10, Pentagram, Halton_2_3_X8, Halton_2_3_X16, Halton_2_3_X32, Halton_2_3_X256, MotionPerp2, }; private static float[] AccessPointData(Pattern pattern) { switch (pattern) { case Pattern.Still: return points_Still; case Pattern.Uniform2: return points_Uniform2; case Pattern.Uniform4: return points_Uniform4; case Pattern.Uniform4_Helix: return points_Uniform4_Helix; case Pattern.Uniform4_DoubleHelix: return points_Uniform4_DoubleHelix; case Pattern.SkewButterfly: return points_SkewButterfly; case Pattern.Rotated4: return points_Rotated4; case Pattern.Rotated4_Helix: return points_Rotated4_Helix; case Pattern.Rotated4_Helix2: return points_Rotated4_Helix2; case Pattern.Poisson10: return points_Poisson10; case Pattern.Pentagram: return points_Pentagram; case Pattern.Halton_2_3_X8: return points_Halton_2_3_x8; case Pattern.Halton_2_3_X16: return points_Halton_2_3_x16; case Pattern.Halton_2_3_X32: return points_Halton_2_3_x32; case Pattern.Halton_2_3_X256: return points_Halton_2_3_x256; case Pattern.MotionPerp2: return points_MotionPerp2; default: Debug.LogError("missing point distribution"); return points_Halton_2_3_x16; } } public static int AccessLength(Pattern pattern) { return AccessPointData(pattern).Length / 2; } #endregion private Vector3 focalMotionPos = Vector3.zero; private Vector3 focalMotionDir = Vector3.right; public Pattern pattern = Pattern.Halton_2_3_X16; public float patternScale = 1f; public Vector4 activeSample = Vector4.zero;// xy = current sample, zw = previous sample public int activeIndex = -1; public Vector2 Sample(Pattern pattern, int index) { float[] points = AccessPointData(pattern); int n = points.Length / 2; int i = index % n; float x = patternScale * points[2 * i + 0]; float y = patternScale * points[2 * i + 1]; if (pattern != Pattern.MotionPerp2) return new Vector2(x, y); else return new Vector2(x, y).Rotate(Vector2.right.SignedAngle(focalMotionDir)); } void OnPreCull() { var camera = GetComponent<Camera>(); if (camera != null && camera.orthographic == false) { // update motion dir { Vector3 oldWorld = focalMotionPos; Vector3 newWorld = camera.transform.TransformVector(camera.nearClipPlane * Vector3.forward); Vector3 oldPoint = (camera.worldToCameraMatrix * oldWorld); Vector3 newPoint = (camera.worldToCameraMatrix * newWorld); Vector3 newDelta = (newPoint - oldPoint).WithZ(0f); var mag = newDelta.magnitude; if (mag != 0f) { var dir = newDelta / mag;// yes, apparently this is necessary instead of newDelta.normalized... because facepalm if (dir.sqrMagnitude != 0f) { focalMotionPos = newWorld; focalMotionDir = Vector3.Slerp(focalMotionDir, dir, 0.2f); //Debug.Log("CHANGE focalMotionDir " + focalMotionDir.ToString("G4") + " delta was " + newDelta.ToString("G4") + " delta.mag " + newDelta.magnitude); } } } // update jitter { activeIndex += 1; activeIndex %= AccessLength(pattern); Vector2 sample = Sample(pattern, activeIndex); activeSample.z = activeSample.x; activeSample.w = activeSample.y; activeSample.x = sample.x; activeSample.y = sample.y; camera.projectionMatrix = camera.GetPerspectiveProjection(sample.x, sample.y); } } else { activeSample = Vector4.zero; activeIndex = -1; } } void OnDisable() { var camera = GetComponent<Camera>(); if (camera != null) { camera.ResetProjectionMatrix(); } activeSample = Vector4.zero; activeIndex = -1; } }
// *********************************************************************** // Copyright (c) 2007-2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PLATFORM_DETECTION using System; using System.Collections; namespace NUnit.Framework.Internal { /// <summary> /// Summary description for PlatformHelperTests. /// </summary> [TestFixture] public class PlatformDetectionTests { private static readonly PlatformHelper win95Helper = new PlatformHelper( new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ), new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) ); private static readonly PlatformHelper winXPHelper = new PlatformHelper( new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ), new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) ); private void CheckOSPlatforms( OSPlatform os, string expectedPlatforms ) { Assert.That(expectedPlatforms, Is.SubsetOf(PlatformHelper.OSPlatforms).IgnoreCase, "Error in test: one or more expected platforms is not a valid OSPlatform."); CheckPlatforms( new PlatformHelper( os, RuntimeFramework.CurrentFramework ), expectedPlatforms, PlatformHelper.OSPlatforms ); } private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework, string expectedPlatforms ) { CheckPlatforms( new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ), expectedPlatforms, PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,NET-4.5,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH"); } private void CheckPlatforms( PlatformHelper helper, string expectedPlatforms, string checkPlatforms ) { string[] expected = expectedPlatforms.Split( new char[] { ',' } ); string[] check = checkPlatforms.Split( new char[] { ',' } ); foreach( string testPlatform in check ) { bool shouldPass = false; foreach( string platform in expected ) if ( shouldPass = platform.ToLower() == testPlatform.ToLower() ) break; bool didPass = helper.IsPlatformSupported( testPlatform ); if ( shouldPass && !didPass ) Assert.Fail( "Failed to detect {0}", testPlatform ); else if ( didPass && !shouldPass ) Assert.Fail( "False positive on {0}", testPlatform ); else if ( !shouldPass && !didPass ) Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason ); } } [Test] public void DetectWin95() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ), "Win95,Win32Windows,Win32,Win" ); } [Test] public void DetectWin98() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ), "Win98,Win32Windows,Win32,Win" ); } [Test] public void DetectWinMe() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ), "WinMe,Win32Windows,Win32,Win" ); } [Test] public void DetectNT3() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ), "NT3,Win32NT,Win32,Win" ); } [Test] public void DetectNT4() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ), "NT4,Win32NT,Win32,Win" ); } [Test] public void DetectWin2K() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ), "Win2K,NT5,Win32NT,Win32,Win" ); } [Test] public void DetectWinXP() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ), "WinXP,NT5,Win32NT,Win32,Win" ); } [Test] public void DetectWinXPProfessionalX64() { CheckOSPlatforms( new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ), "WinXP,NT5,Win32NT,Win32,Win" ); } [Test] public void DetectWin2003Server() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server), "Win2003Server,NT5,Win32NT,Win32,Win"); } [Test] public void DetectVista() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation), "Vista,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWin2008ServerOriginal() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server), "Win2008Server,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWin2008ServerR2() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server), "Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWindows7() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation), "Win7,Windows7,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWindows2012ServerOriginal() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.Server), "Win2012Server,Win2012ServerR1,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWindows2012ServerR2() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.Server), "Win2012Server,Win2012ServerR2,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWindows8() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.WorkStation), "Win8,Windows8,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWindows81() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.WorkStation), "Win8.1,Windows8.1,NT6,Win32NT,Win32,Win"); } [Test] public void DetectWindows10() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.WorkStation), "Win10,Windows10,Win32NT,Win32,Win"); } [Test] public void DetectWindowsServer() { CheckOSPlatforms( new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.Server), "WindowsServer10,Win32NT,Win32,Win"); } [Test] public void DetectUnixUnderMicrosoftDotNet() { CheckOSPlatforms( new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)), "UNIX,Linux"); } [Test] public void DetectUnixUnderMono() { CheckOSPlatforms( new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)), "UNIX,Linux"); } [Test] public void DetectXbox() { CheckOSPlatforms( new OSPlatform(PlatformID.Xbox, new Version(0, 0)), "Xbox"); } [Test] public void DetectMacOSX() { CheckOSPlatforms( new OSPlatform(PlatformID.MacOSX, new Version(0, 0)), "MacOSX"); } [Test] public void DetectNet10() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ), "NET,NET-1.0" ); } [Test] public void DetectNet11() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ), "NET,NET-1.1" ); } [Test] public void DetectNet20() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 50727, 0 ) ), "Net,Net-2.0" ); } [Test] public void DetectNet30() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(3, 0)), "Net,Net-2.0,Net-3.0"); } [Test] public void DetectNet35() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(3, 5)), "Net,Net-2.0,Net-3.0,Net-3.5"); } [Test] public void DetectNet40() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)), "Net,Net-4.0"); } [Test] public void DetectNet45() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Net, new Version(4, 5, 0, 0)), "Net,Net-4.0,Net-4.5"); } [Test] public void DetectSSCLI() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ), "SSCLI,Rotor" ); } [Test] public void DetectMono10() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ), "Mono,Mono-1.0" ); } [Test] public void DetectMono20() { CheckRuntimePlatforms( new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ), "Mono,Mono-2.0" ); } [Test] public void DetectMono30() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)), "Mono,Mono-2.0,Mono-3.0"); } [Test] public void DetectMono35() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)), "Mono,Mono-2.0,Mono-3.0,Mono-3.5"); } [Test] public void DetectMono40() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)), "Mono,Mono-4.0"); } [Test] public void DetectMonoTouch() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)), "MonoTouch"); } [Test] public void DetectNetCore() { CheckRuntimePlatforms( new RuntimeFramework(RuntimeType.NetCore, new Version(0, 0, 0)), "NetCore"); } [Test] public void DetectExactVersion() { Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) ); Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) ); Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) ); Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) ); } [Test] public void ArrayOfPlatforms() { string[] platforms = new string[] { "NT4", "Win2K", "WinXP" }; Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) ); Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) ); } [Test] public void PlatformAttribute_Include() { PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" ); Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) ); Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason); } [Test] public void PlatformAttribute_Exclude() { PlatformAttribute attr = new PlatformAttribute(); attr.Exclude = "Win2K,WinXP,NT4"; Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason ); Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) ); } [Test] public void PlatformAttribute_IncludeAndExclude() { PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" ); attr.Exclude = "Mono"; Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason ); Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) ); attr.Exclude = "Net"; Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason ); Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); Assert.AreEqual( "Not supported on Net", winXPHelper.Reason ); } [Test] public void PlatformAttribute_InvalidPlatform() { PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" ); Assert.Throws<InvalidPlatformException>( () => winXPHelper.IsPlatformSupported(attr), "Invalid platform name Net11"); } [Test] public void PlatformAttribute_ProcessBitNess() { PlatformAttribute attr32 = new PlatformAttribute("32-Bit"); PlatformAttribute attr64 = new PlatformAttribute("64-Bit"); PlatformHelper helper = new PlatformHelper(); // This test verifies that the two labels are known, // do not cause an error and return consistent results. bool is32BitProcess = helper.IsPlatformSupported(attr32); bool is64BitProcess = helper.IsPlatformSupported(attr64); Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit"); #if ASYNC // For .NET 4.0 and 4.5, we can check further Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess)); #endif } #if ASYNC [Test] public void PlatformAttribute_OperatingSystemBitNess() { PlatformAttribute attr32 = new PlatformAttribute("32-Bit-OS"); PlatformAttribute attr64 = new PlatformAttribute("64-Bit-OS"); PlatformHelper helper = new PlatformHelper(); bool is64BitOS = Environment.Is64BitOperatingSystem; Assert.That(helper.IsPlatformSupported(attr32), Is.Not.EqualTo(is64BitOS)); Assert.That(helper.IsPlatformSupported(attr64), Is.EqualTo(is64BitOS)); } #endif } } #endif
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using System.Collections.Generic; using System.Linq; using SharpMath.Collections; using SharpMath.LinearAlgebra; #pragma warning disable namespace SharpMath.Statistics.Regressions { [Serializable] public class AutomatedLinearRegression { public AutomatedLinearRegression(IEnumerable<LinearRegressionFactor> factors) { Factors = new ImmutableList<LinearRegressionFactor>(factors); } public static AutomatedLinearRegression Fit(IRegressionVariable regressand, IEnumerable<IRegressionVariable> regressors) { if (regressors == null) { throw new ArgumentNullException(); } return Fit(regressand, regressors.ToArray()); } public static AutomatedLinearRegression Fit(IRegressionVariable regressand, params IRegressionVariable[] regressors) { if (regressand == null || regressors == null) { throw new ArgumentNullException(); } int p = regressors.Length; for (int i = 0; i < p; i++) { if (regressors[i] == null) { throw new ArgumentNullException(); } } // The regressand is required not to be an infinite sequence. double[] y = regressand.Values.ToArray(); int n = y.Length; // The regressor sequences may be. But must be at least as long as the regressand. double[,] x = new double[n, p]; for (int i = 0; i < p; i++) { using (IEnumerator<double> iterator = regressors[i].Values.GetEnumerator()) { for (int j = 0; j < n; j++) { if (!iterator.MoveNext()) { throw new Exception("Regressor sequence ended unexpectedly."); } x[j, i] = iterator.Current; } } } LinearRegression lr = LinearRegression.Fit(new Vector(y), new Matrix(x)); //SimpleLinearRegression lr = new SimpleLinearRegression.Fit(new Vector(y), new Matrix(x)); LinearRegressionFactor[] factors = new LinearRegressionFactor[p]; for (int j = 0; j < p; j++) { double t = lr.Beta[j] / lr.Sigma[j]; // Null probability, $Pr(>|t|)$. // http://sourceforge.net/p/varianttools/mailman/message/29121481/ throw new NotImplementedException(); double pr;//double pr = 2.0 * Gsl.gsl_cdf_tdist_Q(Math.Abs(t), n - p); factors[j] = new LinearRegressionFactor(regressors[j], lr.Beta[j], lr.Sigma[j], pr); } return new AutomatedLinearRegression(factors); } public static AutomatedLinearRegression FitBySignificance(double significanceLevel, IRegressionVariable regressand, IEnumerable<IRegressionVariable> regressors) { if (significanceLevel < 0.0 || significanceLevel > 1.0) { throw new ArgumentOutOfRangeException(); } return FitBySignificanceFactors(significanceLevel, int.MaxValue, regressand, regressors); } public static AutomatedLinearRegression FitBySignificance(double significanceLevel, IRegressionVariable regressand, params IRegressionVariable[] regressors) { return FitBySignificance(significanceLevel, regressand, (IEnumerable<IRegressionVariable>)regressors); } public static AutomatedLinearRegression FitByFactors(int factors, IRegressionVariable regressand, IEnumerable<IRegressionVariable> regressors) { // The backward mode described here: // http://faculty.smu.edu/tfomby/eco5385/lecture/Multiple%20Linear%20Regression%20and%20Subset%20Selection.pdf if (factors < 1) { throw new ArgumentOutOfRangeException(); } return FitBySignificanceFactors(double.NegativeInfinity, factors, regressand, regressors); } public static AutomatedLinearRegression FitByFactors(int factors, IRegressionVariable regressand, params IRegressionVariable[] regressors) { return FitBySignificance(factors, regressand, (IEnumerable<IRegressionVariable>)regressors); } private static AutomatedLinearRegression FitBySignificanceFactors(double significanceLevel, int factors, IRegressionVariable regressand, IEnumerable<IRegressionVariable> regressors) { if (regressors.Count(r => r.Required) > factors) { throw new ArgumentException("Too many factors are required."); } // Threshold p-value. double p0 = 1.0 - significanceLevel; // Start by a non-automated regression. AutomatedLinearRegression lr = AutomatedLinearRegression.Fit(regressand, regressors); while (true) { // Find worst non-significant factor. LinearRegressionFactor f0 = lr.Factors.Where(f => !f.Regressor.Required).OrderByDescending(f => f.NullProbability).First(); if (lr.Factors.Count <= factors && f0.NullProbability <= p0) { // Satisfying maximum number of factors and worst significance level. return lr; } if (lr.Factors.Count == 1) { // About to remove last factor. return new AutomatedLinearRegression(new LinearRegressionFactor[0]); } lr = AutomatedLinearRegression.Fit(regressand, lr.Factors.Where(f => f != f0).Select(f => f.Regressor)); } } public static AutomatedLinearRegression FitByFactorsCombinatorial(int factors, IRegressionVariable regressand, IEnumerable<IRegressionVariable> regressors) { if (factors < 1) { throw new ArgumentOutOfRangeException(); } int n = regressors.Count(r => !r.Required); if (n <= factors) { // Already below maximum number of factors. return Fit(regressand, regressors); } throw new NotImplementedException(); } public static AutomatedLinearRegression FitByFactorsCombinatorial(int factors, IRegressionVariable regressand, params IRegressionVariable[] regressors) { return FitByFactorsCombinatorial(factors, regressand, (IEnumerable<IRegressionVariable>)regressors); } public ImmutableList<LinearRegressionFactor> Factors { get; private set; } } [Serializable] public class AutomatedLinearRegression<T> : AutomatedLinearRegression { public AutomatedLinearRegression(IEnumerable<LinearRegressionFactor> factors) : base(factors) { } public static AutomatedLinearRegression<T> Fit(IRegressionVariable regressand, IEnumerable<IRegressionVariable<T>> regressors) { return new AutomatedLinearRegression<T>(AutomatedLinearRegression.Fit(regressand, regressors).Factors); } public static AutomatedLinearRegression<T> Fit(IRegressionVariable regressand, params IRegressionVariable<T>[] regressors) { return Fit(regressand, (IEnumerable<IRegressionVariable<T>>)regressors); } public static AutomatedLinearRegression<T> FitBySignificance(double significanceLevel, IRegressionVariable regressand, IEnumerable<IRegressionVariable<T>> regressors) { return new AutomatedLinearRegression<T>(AutomatedLinearRegression.FitBySignificance(significanceLevel, regressand, regressors).Factors); } public static AutomatedLinearRegression<T> FitBySignificance(double significanceLevel, IRegressionVariable regressand, params IRegressionVariable<T>[] regressors) { return FitBySignificance(significanceLevel, regressand, (IEnumerable<IRegressionVariable<T>>)regressors); } public static AutomatedLinearRegression<T> FitByFactors(int factors, IRegressionVariable regressand, IEnumerable<IRegressionVariable<T>> regressors) { return new AutomatedLinearRegression<T>(AutomatedLinearRegression.FitByFactors(factors, regressand, regressors).Factors); } public static AutomatedLinearRegression<T> FitByFactors(int factors, IRegressionVariable regressand, params IRegressionVariable<T>[] regressors) { return FitByFactors(factors, regressand, (IEnumerable<IRegressionVariable<T>>)regressors); } /// <summary> /// The regresson value. /// </summary> public double Value(T value) { double x = 0.0; foreach (LinearRegressionFactor factor in Factors) { x += factor.Coefficient * ((IRegressionVariable<T>)factor.Regressor).Transform(value); } return x; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using FileHelpers.Options; namespace FileHelpers { /// <summary> /// Base class for all Field Types. /// Implements all the basic functionality of a field in a typed file. /// </summary> public abstract class FieldBase : ICloneable { #region " Private & Internal Fields " // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// type of object to be created, eg DateTime /// </summary> public Type FieldType { get; private set; } /// <summary> /// Provider to convert to and from text /// </summary> public ConverterBase Converter { get; private set; } /// <summary> /// Number of extra characters used, delimiters and quote characters /// </summary> internal virtual int CharsToDiscard { get { return 0; } } /// <summary> /// Field type of an array or it is just fieldType. /// What actual object will be created /// </summary> internal Type FieldTypeInternal { get; set; } /// <summary> /// Is this field an array? /// </summary> public bool IsArray { get; private set; } /// <summary> /// Array must have this many entries /// </summary> public int ArrayMinLength { get; set; } /// <summary> /// Array may have this many entries, if equal to ArrayMinLength then /// it is a fixed length array /// </summary> public int ArrayMaxLength { get; set; } /// <summary> /// Seems to be duplicate of FieldTypeInternal except it is ONLY set /// for an array /// </summary> internal Type ArrayType { get; set; } /// <summary> /// Do we process this field but not store the value /// </summary> public bool Discarded { get; set; } /// <summary> /// Unused! /// </summary> internal bool TrailingArray { get; set; } /// <summary> /// Value to use if input is null or empty /// </summary> internal object NullValue { get; set; } /// <summary> /// Are we a simple string field we can just assign to /// </summary> internal bool IsStringField { get; set; } /// <summary> /// Details about the extraction criteria /// </summary> internal FieldInfo FieldInfo { get; set; } /// <summary> /// indicates whether we trim leading and/or trailing whitespace /// </summary> public TrimMode TrimMode { get; set; } /// <summary> /// Character to chop off front and / rear of the string /// </summary> internal char[] TrimChars { get; set; } /// <summary> /// The field may not be present on the input data (line not long enough) /// </summary> public bool IsOptional { get; set; } /// <summary> /// The next field along is optional, optimise processing next records /// </summary> internal bool NextIsOptional { get { if (Parent.FieldCount > ParentIndex + 1) return Parent.Fields[ParentIndex + 1].IsOptional; return false; } } /// <summary> /// Am I the first field in an array list /// </summary> internal bool IsFirst { get { return ParentIndex == 0; } } /// <summary> /// Am I the last field in the array list /// </summary> internal bool IsLast { get { return ParentIndex == Parent.FieldCount - 1; } } /// <summary> /// Set from the FieldInNewLIneAtribute. This field begins on a new /// line of the file /// </summary> internal bool InNewLine { get; set; } /// <summary> /// Order of the field in the file layout /// </summary> internal int? FieldOrder { get; set; } /// <summary> /// Can null be assigned to this value type, for example not int or /// DateTime /// </summary> internal bool IsNullableType { get; private set; } /// <summary> /// Name of the field without extra characters (eg property) /// </summary> internal string FieldFriendlyName { get; set; } /// <summary> /// The field must be not be empty /// </summary> public bool IsNotEmpty { get; set; } /// <summary> /// Caption of the field displayed in header row (see EngineBase.GetFileHeader) /// </summary> internal string FieldCaption { get; set; } // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// Fieldname of the field we are storing /// </summary> internal string FieldName { get { return FieldInfo.Name; } } /* private static readonly char[] mWhitespaceChars = new[] { '\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u3000', '\ufeff' */ #endregion #region " CreateField " /// <summary> /// Check the Attributes on the field and return a structure containing /// the settings for this file. /// </summary> /// <param name="fi">Information about this field</param> /// <param name="recordAttribute">Type of record we are reading</param> /// <returns>Null if not used</returns> public static FieldBase CreateField(FieldInfo fi, TypedRecordAttribute recordAttribute) { FieldBase res = null; MemberInfo mi = fi; var memberName = "The field: '" + fi.Name; Type fieldType = fi.FieldType; string fieldFriendlyName = AutoPropertyName(fi); if (string.IsNullOrEmpty(fieldFriendlyName)==false) { var prop = fi.DeclaringType.GetProperty(fieldFriendlyName); if (prop != null) { memberName = "The property: '" + prop.Name; mi = prop; } else { fieldFriendlyName = null; } } // If ignored, return null #pragma warning disable 612,618 // disable obsolete warning if (mi.IsDefined(typeof (FieldNotInFileAttribute), true) || mi.IsDefined(typeof (FieldIgnoredAttribute), true) || mi.IsDefined(typeof (FieldHiddenAttribute), true)) #pragma warning restore 612,618 return null; var attributes = (FieldAttribute[]) mi.GetCustomAttributes(typeof (FieldAttribute), true); // CHECK USAGE ERRORS !!! // Fixed length record and no attributes at all if (recordAttribute is FixedLengthRecordAttribute && attributes.Length == 0) { throw new BadUsageException(memberName + "' must be marked the FieldFixedLength attribute because the record class is marked with FixedLengthRecord."); } if (attributes.Length > 1) { throw new BadUsageException(memberName + "' has a FieldFixedLength and a FieldDelimiter attribute."); } if (recordAttribute is DelimitedRecordAttribute && mi.IsDefined(typeof (FieldAlignAttribute), false)) { throw new BadUsageException(memberName + "' can't be marked with FieldAlign attribute, it is only valid for fixed length records and are used only for write purpose."); } if (fieldType.IsArray == false && mi.IsDefined(typeof (FieldArrayLengthAttribute), false)) { throw new BadUsageException(memberName + "' can't be marked with FieldArrayLength attribute is only valid for array fields."); } // PROCESS IN NORMAL CONDITIONS if (attributes.Length > 0) { FieldAttribute fieldAttb = attributes[0]; if (fieldAttb is FieldFixedLengthAttribute) { // Fixed Field if (recordAttribute is DelimitedRecordAttribute) { throw new BadUsageException(memberName + "' can't be marked with FieldFixedLength attribute, it is only for the FixedLengthRecords not for delimited ones."); } var attbFixedLength = (FieldFixedLengthAttribute) fieldAttb; var attbAlign = Attributes.GetFirst<FieldAlignAttribute>(mi); res = new FixedLengthField(fi, attbFixedLength.Length, attbAlign); ((FixedLengthField) res).FixedMode = ((FixedLengthRecordAttribute) recordAttribute).FixedMode; } else if (fieldAttb is FieldDelimiterAttribute) { // Delimited Field if (recordAttribute is FixedLengthRecordAttribute) { throw new BadUsageException(memberName + "' can't be marked with FieldDelimiter attribute, it is only for DelimitedRecords not for fixed ones."); } res = new DelimitedField(fi, ((FieldDelimiterAttribute) fieldAttb).Delimiter); } else { throw new BadUsageException( "Custom field attributes are not currently supported. Unknown attribute: " + fieldAttb.GetType().Name + " on field: " + fi.Name); } } else // attributes.Length == 0 { var delimitedRecordAttribute = recordAttribute as DelimitedRecordAttribute; if (delimitedRecordAttribute != null) { res = new DelimitedField(fi, delimitedRecordAttribute.Separator); } } if (res != null) { // FieldDiscarded res.Discarded = mi.IsDefined(typeof (FieldValueDiscardedAttribute), false); // FieldTrim Attributes.WorkWithFirst<FieldTrimAttribute>(mi, (x) => { res.TrimMode = x.TrimMode; res.TrimChars = x.TrimChars; }); // FieldQuoted Attributes.WorkWithFirst<FieldQuotedAttribute>(mi, (x) => { if (res is FixedLengthField) { throw new BadUsageException( memberName + "' can't be marked with FieldQuoted attribute, it is only for the delimited records."); } ((DelimitedField) res).QuoteChar = x.QuoteChar; ((DelimitedField) res).QuoteMode = x.QuoteMode; ((DelimitedField) res).QuoteMultiline = x.QuoteMultiline; }); // FieldOrder Attributes.WorkWithFirst<FieldOrderAttribute>(mi, x => res.FieldOrder = x.Order); // FieldCaption Attributes.WorkWithFirst<FieldCaptionAttribute>(mi, x => res.FieldCaption = x.Caption); // FieldOptional res.IsOptional = mi.IsDefined(typeof(FieldOptionalAttribute), false); // FieldInNewLine res.InNewLine = mi.IsDefined(typeof(FieldInNewLineAttribute), false); // FieldNotEmpty res.IsNotEmpty = mi.IsDefined(typeof(FieldNotEmptyAttribute), false); // FieldArrayLength if (fieldType.IsArray) { res.IsArray = true; res.ArrayType = fieldType.GetElementType(); // MinValue indicates that there is no FieldArrayLength in the array res.ArrayMinLength = int.MinValue; res.ArrayMaxLength = int.MaxValue; Attributes.WorkWithFirst<FieldArrayLengthAttribute>(mi, (x) => { res.ArrayMinLength = x.MinLength; res.ArrayMaxLength = x.MaxLength; if (res.ArrayMaxLength < res.ArrayMinLength || res.ArrayMinLength < 0 || res.ArrayMaxLength <= 0) { throw new BadUsageException(memberName + " has invalid length values in the [FieldArrayLength] attribute."); } }); } } if (string.IsNullOrEmpty(res.FieldFriendlyName)) res.FieldFriendlyName = res.FieldName; return res; } internal RecordOptions Parent { get; set; } internal int ParentIndex { get; set; } internal static string AutoPropertyName(FieldInfo fi) { if (fi.IsDefined(typeof(CompilerGeneratedAttribute), false)) { if (fi.Name.EndsWith("__BackingField") && fi.Name.StartsWith("<") && fi.Name.Contains(">")) return fi.Name.Substring(1, fi.Name.IndexOf(">") - 1); } return ""; } internal bool IsAutoProperty { get; set; } #endregion #region " Constructor " /// <summary> /// Create a field base without any configuration /// </summary> internal FieldBase() { IsNullableType = false; TrimMode = TrimMode.None; FieldOrder = null; InNewLine = false; //NextIsOptional = false; IsOptional = false; TrimChars = null; NullValue = null; TrailingArray = false; IsArray = false; IsNotEmpty = false; } /// <summary> /// Create a field base from a fieldinfo object /// Verify the settings against the actual field to ensure it will work. /// </summary> /// <param name="fi">Field Info Object</param> internal FieldBase(FieldInfo fi) : this() { FieldInfo = fi; FieldType = FieldInfo.FieldType; MemberInfo attibuteTarget = fi; this.FieldFriendlyName = AutoPropertyName(fi); if (string.IsNullOrEmpty(FieldFriendlyName) == false) { var prop = fi.DeclaringType.GetProperty(this.FieldFriendlyName); if (prop == null) { this.FieldFriendlyName = null; } else { this.IsAutoProperty = true; attibuteTarget = prop; } } if (FieldType.IsArray) FieldTypeInternal = FieldType.GetElementType(); else FieldTypeInternal = FieldType; IsStringField = FieldTypeInternal == typeof (string); object[] attribs = attibuteTarget.GetCustomAttributes(typeof (FieldConverterAttribute), true); if (attribs.Length > 0) { var conv = (FieldConverterAttribute) attribs[0]; this.Converter = conv.Converter; conv.ValidateTypes(FieldInfo); } else this.Converter = ConvertHelpers.GetDefaultConverter(FieldFriendlyName ?? fi.Name, FieldType); if (this.Converter != null) this.Converter.mDestinationType = FieldTypeInternal; attribs = attibuteTarget.GetCustomAttributes(typeof (FieldNullValueAttribute), true); if (attribs.Length > 0) { NullValue = ((FieldNullValueAttribute) attribs[0]).NullValue; // mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite; if (NullValue != null) { if (!FieldTypeInternal.IsAssignableFrom(NullValue.GetType())) { throw new BadUsageException("The NullValue is of type: " + NullValue.GetType().Name + " that is not asignable to the field " + FieldInfo.Name + " of type: " + FieldTypeInternal.Name); } } } IsNullableType = FieldTypeInternal.IsValueType && FieldTypeInternal.IsGenericType && FieldTypeInternal.GetGenericTypeDefinition() == typeof (Nullable<>); } #endregion #region " MustOverride (String Handling) " /// <summary> /// Extract the string from the underlying data, removes quotes /// characters for example /// </summary> /// <param name="line">Line to parse data from</param> /// <returns>Slightly processed string from the data</returns> internal abstract ExtractedInfo ExtractFieldString(LineInfo line); /// <summary> /// Create a text block containing the field from definition /// </summary> /// <param name="sb">Append string to output</param> /// <param name="fieldValue">Field we are adding</param> /// <param name="isLast">Indicates if we are processing last field</param> internal abstract void CreateFieldString(StringBuilder sb, object fieldValue, bool isLast); /// <summary> /// Convert a field value to a string representation /// </summary> /// <param name="fieldValue">Object containing data</param> /// <returns>String representation of field</returns> internal string CreateFieldString(object fieldValue) { if (this.Converter == null) { if (fieldValue == null) return string.Empty; else return fieldValue.ToString(); } else return this.Converter.FieldToString(fieldValue); } #endregion #region " ExtractValue " /// <summary> /// Get the data out of the records /// </summary> /// <param name="line">Line handler containing text</param> /// <returns></returns> internal object ExtractFieldValue(LineInfo line) { //-> extract only what I need if (InNewLine) { // Any trailing characters, terminate if (line.EmptyFromPos() == false) { throw new BadUsageException(line, "Text '" + line.CurrentString + "' found before the new line of the field: " + FieldInfo.Name + " (this is not allowed when you use [FieldInNewLine])"); } line.ReLoad(line.mReader.ReadNextLine()); if (line.mLineStr == null) { throw new BadUsageException(line, "End of stream found parsing the field " + FieldInfo.Name + ". Please check the class record."); } } if (IsArray == false) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; //total; if (Discarded) return GetDiscardedNullValue(); else return AssignFromString(info, line).Value; } else { if (ArrayMinLength <= 0) ArrayMinLength = 0; int i = 0; var res = new ArrayList(Math.Max(ArrayMinLength, 10)); while (line.mCurrentPos - CharsToDiscard < line.mLineStr.Length && i < ArrayMaxLength) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; try { var value = AssignFromString(info, line); if (value.NullValueUsed && i == 0 && line.IsEOL()) break; res.Add(value.Value); } catch (NullValueNotFoundException) { if (i == 0) break; else throw; } i++; } if (res.Count < ArrayMinLength) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has only {3} values, less than the minimum length of {4}", line.mReader.LineNumber.ToString(), line.mCurrentPos.ToString(), FieldInfo.Name, res.Count, ArrayMinLength)); } else if (IsLast && line.IsEOL() == false) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has more values than the maximum length of {3}", line.mReader.LineNumber, line.mCurrentPos, FieldInfo.Name, ArrayMaxLength)); } // TODO: is there a reason we go through all the array processing then discard it if (Discarded) return null; else return res.ToArray(ArrayType); } } #region " AssignFromString " private struct AssignResult { public object Value; public bool NullValueUsed; } /// <summary> /// Create field object after extracting the string from the underlying /// input data /// </summary> /// <param name="fieldString">Information extracted?</param> /// <param name="line">Underlying input data</param> /// <returns>Object to assign to field</returns> private AssignResult AssignFromString(ExtractedInfo fieldString, LineInfo line) { object val; var extractedString = fieldString.ExtractedString(); try { if (IsNotEmpty && String.IsNullOrEmpty(extractedString)) { throw new InvalidOperationException("The value is empty and must be populated."); } else if (this.Converter == null) { if (IsStringField) val = TrimString(extractedString); else { extractedString = extractedString.Trim(); if (extractedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else val = Convert.ChangeType(extractedString, FieldTypeInternal, null); } } else { var trimmedString = extractedString.Trim(); if (this.Converter.CustomNullHandling == false && trimmedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else { if (TrimMode == TrimMode.Both) val = this.Converter.StringToField(trimmedString); else val = this.Converter.StringToField(TrimString(extractedString)); if (val == null) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } } } return new AssignResult { Value = val }; } catch (ConvertException ex) { ex.FieldName = FieldInfo.Name; ex.LineNumber = line.mReader.LineNumber; ex.ColumnNumber = fieldString.ExtractedFrom + 1; throw; } catch (BadUsageException) { throw; } catch (Exception ex) { if (this.Converter == null || this.Converter.GetType().Assembly == typeof (FieldBase).Assembly) { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, ex.Message, ex); } else { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, "Your custom converter: " + this.Converter.GetType().Name + " throws an " + ex.GetType().Name + " with the message: " + ex.Message, ex); } } } private String TrimString(string extractedString) { switch (TrimMode) { case TrimMode.None: return extractedString; case TrimMode.Both: return extractedString.Trim(); case TrimMode.Left: return extractedString.TrimStart(); case TrimMode.Right: return extractedString.TrimEnd(); default: throw new Exception("Trim mode invalid in FieldBase.TrimString -> " + TrimMode.ToString()); } } /// <summary> /// Convert a null value into a representation, /// allows for a null value override /// </summary> /// <param name="line">input line to read, used for error messages</param> /// <returns>Null value for object</returns> private object GetNullValue(LineInfo line) { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "Not value found for the value type field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "'. " + Environment.NewLine + "You must use the [FieldNullValue] attribute because this is a value type and can't be null or use a Nullable Type instead of the current type."; throw new NullValueNotFoundException(line, msg); } else return null; } else return NullValue; } /// <summary> /// Get the null value that represent a discarded value /// </summary> /// <returns>null value of discard?</returns> private object GetDiscardedNullValue() { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "The field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "' is from a value type: " + FieldInfo.FieldType.Name + " and is discarded (null) you must provide a [FieldNullValue] attribute."; throw new BadUsageException(msg); } else return null; } else return NullValue; } #endregion #region " CreateValueForField " /// <summary> /// Convert a field value into a write able value /// </summary> /// <param name="fieldValue">object value to convert</param> /// <returns>converted value</returns> public object CreateValueForField(object fieldValue) { object val = null; if (fieldValue == null) { if (NullValue == null) { if (FieldTypeInternal.IsValueType && Nullable.GetUnderlyingType(FieldTypeInternal) == null) { throw new BadUsageException( "Null Value found. You must specify a FieldNullValueAttribute in the " + FieldInfo.Name + " field of type " + FieldTypeInternal.Name + ", because this is a ValueType."); } else val = null; } else val = NullValue; } else if (FieldTypeInternal == fieldValue.GetType()) val = fieldValue; else { if (this.Converter == null) val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); else { try { if (Nullable.GetUnderlyingType(FieldTypeInternal) != null && Nullable.GetUnderlyingType(FieldTypeInternal) == fieldValue.GetType()) val = fieldValue; else val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); } catch { val = Converter.StringToField(fieldValue.ToString()); } } } return val; } #endregion #endregion #region " AssignToString " /// <summary> /// convert field to string value and assign to a string builder /// buffer for output /// </summary> /// <param name="sb">buffer to collect record</param> /// <param name="fieldValue">value to convert</param> internal void AssignToString(StringBuilder sb, object fieldValue) { if (this.InNewLine == true) sb.Append(StringHelper.NewLine); if (IsArray) { if (fieldValue == null) { if (0 < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array is null, but the minimum length is {1}", FieldInfo.Name, ArrayMinLength)); } return; } var array = (IList) fieldValue; if (array.Count < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the minimum length is {2}", FieldInfo.Name, array.Count, ArrayMinLength)); } if (array.Count > this.ArrayMaxLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the maximum length is {2}", FieldInfo.Name, array.Count, ArrayMaxLength)); } for (int i = 0; i < array.Count; i++) { object val = array[i]; CreateFieldString(sb, val, IsLast && i == array.Count - 1); } } else CreateFieldString(sb, fieldValue, IsLast); } #endregion /// <summary> /// Copy the field object /// </summary> /// <returns>a complete copy of the Field object</returns> object ICloneable.Clone() { var res = CreateClone(); res.FieldType = FieldType; res.Converter = this.Converter; res.FieldTypeInternal = FieldTypeInternal; res.IsArray = IsArray; res.ArrayType = ArrayType; res.ArrayMinLength = ArrayMinLength; res.ArrayMaxLength = ArrayMaxLength; res.TrailingArray = TrailingArray; res.NullValue = NullValue; res.IsStringField = IsStringField; res.FieldInfo = FieldInfo; res.TrimMode = TrimMode; res.TrimChars = TrimChars; res.IsOptional = IsOptional; //res.NextIsOptional = NextIsOptional; res.InNewLine = InNewLine; res.FieldOrder = FieldOrder; res.IsNullableType = IsNullableType; res.Discarded = Discarded; res.FieldFriendlyName = FieldFriendlyName; res.IsNotEmpty = IsNotEmpty; res.FieldCaption = FieldCaption; res.Parent = Parent; res.ParentIndex = ParentIndex; return res; } /// <summary> /// Add the extra details that derived classes create /// </summary> /// <returns>field clone of right type</returns> protected abstract FieldBase CreateClone(); } }
using System; using System.Linq; using System.Threading.Tasks; using Orleans; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.CancellationTests { public class GrainCancellationTokenTests : OrleansTestingBase, IClassFixture<GrainCancellationTokenTests.Fixture> { private readonly Fixture fixture; public class Fixture : BaseTestClusterFixture { } public GrainCancellationTokenTests(Fixture fixture) { this.fixture = fixture; } [Theory, TestCategory("BVT"), TestCategory("Cancellation")] [InlineData(0)] [InlineData(10)] [InlineData(300)] public async Task GrainTaskCancellation(int delay) { var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10)); await Task.Delay(TimeSpan.FromMilliseconds(delay)); await tcs.Cancel(); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } [Theory, TestCategory("BVT"), TestCategory("Cancellation")] [InlineData(0)] [InlineData(10)] [InlineData(300)] public async Task MultipleGrainsTaskCancellation(int delay) { var tcs = new GrainCancellationTokenSource(); var grainTasks = Enumerable.Range(0, 5) .Select(i => this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()) .LongWait(tcs.Token, TimeSpan.FromSeconds(10))) .Select(task => Assert.ThrowsAsync<TaskCanceledException>(() => task)).ToList(); await Task.Delay(TimeSpan.FromMilliseconds(delay)); await tcs.Cancel(); await Task.WhenAll(grainTasks); } [Fact, TestCategory("BVT"), TestCategory("Cancellation")] public async Task TokenPassingWithoutCancellation_NoExceptionShouldBeThrown() { var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); try { await grain.LongWait(tcs.Token, TimeSpan.FromMilliseconds(1)); } catch (Exception ex) { Assert.True(false, "Expected no exception, but got: " + ex.Message); } } [Fact, TestCategory("BVT"), TestCategory("Cancellation")] public async Task PreCancelledTokenPassing() { var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); await tcs.Cancel(); var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10)); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } [Fact, TestCategory("BVT"), TestCategory("Cancellation")] public async Task CancellationTokenCallbacksExecutionContext() { var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); var grainTask = grain.CancellationTokenCallbackResolve(tcs.Token); await Task.Delay(TimeSpan.FromMilliseconds(100)); await tcs.Cancel(); var result = await grainTask; Assert.True(result); } [Fact, TestCategory("BVT"), TestCategory("Cancellation")] public async Task CancellationTokenCallbacksTaskSchedulerContext() { var grains = await GetGrains<bool>(false); var tcs = new GrainCancellationTokenSource(); var grainTask = grains.Item1.CallOtherCancellationTokenCallbackResolve(grains.Item2); await tcs.Cancel(); var result = await grainTask; Assert.True(result); } [Fact, TestCategory("Cancellation")] public async Task CancellationTokenCallbacksThrow_ExceptionShouldBePropagated() { var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); var grainTask = grain.CancellationTokenCallbackThrow(tcs.Token); await Task.Delay(TimeSpan.FromMilliseconds(100)); try { await tcs.Cancel(); } catch (AggregateException ex) { Assert.True(ex.InnerException is InvalidOperationException, "Exception thrown has wrong type"); return; } Assert.True(false, "No exception was thrown"); } [Theory, TestCategory("BVT"), TestCategory("Cancellation")] [InlineData(0)] [InlineData(10)] [InlineData(300)] public async Task InSiloGrainCancellation(int delay) { await GrainGrainCancellation(false, delay); } [Theory, TestCategory("BVT"), TestCategory("Cancellation")] [InlineData(0)] [InlineData(10)] [InlineData(300)] public async Task InterSiloGrainCancellation(int delay) { await GrainGrainCancellation(true, delay); } [SkippableTheory(Skip="https://github.com/dotnet/orleans/issues/5654"), TestCategory("BVT"), TestCategory("Cancellation")] [InlineData(0)] [InlineData(10)] [InlineData(300)] public async Task InterSiloClientCancellationTokenPassing(int delay) { await ClientGrainGrainTokenPassing(delay, true); } [Theory, TestCategory("BVT"), TestCategory("Cancellation")] [InlineData(0)] [InlineData(10)] [InlineData(300)] public async Task InSiloClientCancellationTokenPassing(int delay) { await ClientGrainGrainTokenPassing(delay, false); } private async Task ClientGrainGrainTokenPassing(int delay, bool interSilo) { var grains = await GetGrains<bool>(interSilo); var grain = grains.Item1; var target = grains.Item2; var tcs = new GrainCancellationTokenSource(); var grainTask = grain.CallOtherLongRunningTask(target, tcs.Token, TimeSpan.FromSeconds(10)); await Task.Delay(TimeSpan.FromMilliseconds(delay)); await tcs.Cancel(); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } private async Task GrainGrainCancellation(bool interSilo, int delay) { var grains = await GetGrains<bool>(interSilo); var grain = grains.Item1; var target = grains.Item2; var grainTask = grain.CallOtherLongRunningTaskWithLocalToken(target, TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(delay)); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } private async Task<Tuple<ILongRunningTaskGrain<T1>, ILongRunningTaskGrain<T1>>> GetGrains<T1>(bool placeOnDifferentSilos = true) { var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid()); var instanceId = await grain.GetRuntimeInstanceId(); var target = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid()); var targetInstanceId = await target.GetRuntimeInstanceId(); var retriesCount = 0; var retriesLimit = 10; while ((placeOnDifferentSilos && instanceId.Equals(targetInstanceId)) || (!placeOnDifferentSilos && !instanceId.Equals(targetInstanceId))) { if (retriesCount >= retriesLimit) throw new Exception("Could not make requested grains placement"); target = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid()); targetInstanceId = await target.GetRuntimeInstanceId(); retriesCount++; } return new Tuple<ILongRunningTaskGrain<T1>, ILongRunningTaskGrain<T1>>(grain, target); } } }